From c11982d306fbcd5f25dd63224f720922d49dc3a4 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:18:29 +0000 Subject: [PATCH] chore: sync mlx-agent v0.13.0 --- .claude-plugin/marketplace.json | 4 +- packages/codex/expected-integrity.json | 5 +- .../codex/mlx-agent/.codex-plugin/plugin.json | 2 +- packages/codex/mlx-agent/provenance.json | 4 +- .../codex/mlx-agent/skills/mlx-task/SKILL.md | 24 + .../codex/mlx-agent/src/mlx_agent/__init__.py | 2 +- .../mlx-agent/src/mlx_agent/acestep_fsq.py | 9 + .../mlx-agent/src/mlx_agent/acestep_runner.py | 144 + .../src/mlx_agent/allocator_cache.py | 119 + .../src/mlx_agent/backend_install.py | 7 + .../mlx-agent/src/mlx_agent/backend_runner.py | 14 + .../codex/mlx-agent/src/mlx_agent/backends.py | 16 +- .../src/mlx_agent/chat_completions.py | 24 + packages/codex/mlx-agent/src/mlx_agent/cli.py | 329 ++- .../mlx-agent/src/mlx_agent/command_args.py | 5 +- .../src/mlx_agent/command_executor.py | 2 +- .../codex/mlx-agent/src/mlx_agent/compute.py | 297 +- .../src/mlx_agent/conversion_monitor.py | 220 ++ .../codex/mlx-agent/src/mlx_agent/convert.py | 304 +- .../mlx-agent/src/mlx_agent/convert_queue.py | 64 +- .../mlx-agent/src/mlx_agent/decide_runner.py | 7 +- .../src/mlx_agent/describe_runner.py | 7 +- .../codex/mlx-agent/src/mlx_agent/embed.py | 74 + .../mlx-agent/src/mlx_agent/embed_runner.py | 37 + .../mlx-agent/src/mlx_agent/fetch_runner.py | 53 +- .../mlx-agent/src/mlx_agent/fetch_storage.py | 190 ++ .../mlx-agent/src/mlx_agent/front_door.py | 191 ++ .../src/mlx_agent/generate_runner.py | 7 +- .../codex/mlx-agent/src/mlx_agent/gguf.py | 314 +- .../mlx-agent/src/mlx_agent/gguf_runner.py | 26 +- .../mlx-agent/src/mlx_agent/identity_pass.py | 195 ++ .../mlx-agent/src/mlx_agent/inference_auth.py | 125 + .../src/mlx_agent/inference_defaults.py | 44 + .../src/mlx_agent/inference_telemetry.py | 115 + .../codex/mlx-agent/src/mlx_agent/intake.py | 19 +- .../mlx-agent/src/mlx_agent/intake_fetch.py | 153 +- .../mlx-agent/src/mlx_agent/intake_source.py | 4 +- .../mlx-agent/src/mlx_agent/jit_serve.py | 884 ++++-- .../mlx-agent/src/mlx_agent/media_settings.py | 52 + .../mlx-agent/src/mlx_agent/memory_budget.py | 220 ++ .../src/mlx_agent/memory_diagnostics.py | 44 + .../mlx-agent/src/mlx_agent/memory_policy.py | 316 ++ .../codex/mlx-agent/src/mlx_agent/mesh.py | 43 +- .../mlx-agent/src/mlx_agent/mesh_runner.py | 20 +- .../codex/mlx-agent/src/mlx_agent/music.py | 88 +- .../mlx-agent/src/mlx_agent/music_runner.py | 25 +- .../mlx-agent/src/mlx_agent/music_speed.py | 71 + .../mlx-agent/src/mlx_agent/owned_worker.py | 75 + .../mlx-agent/src/mlx_agent/private_serve.py | 313 ++ .../mlx-agent/src/mlx_agent/process_table.py | 110 + .../mlx-agent/src/mlx_agent/process_tree.py | 9 + .../src/mlx_agent/protected_service.py | 68 + .../src/mlx_agent/protected_worker.py | 53 + .../mlx-agent/src/mlx_agent/queue_bridge.py | 25 +- .../mlx-agent/src/mlx_agent/queue_cli.py | 8 +- .../mlx-agent/src/mlx_agent/residency.py | 432 +++ .../src/mlx_agent/resident_runner.py | 209 ++ .../src/mlx_agent/resident_worker.py | 104 + .../resources/backends/ace-step-build.lock | 18 + .../resources/backends/ace-step.json | 19 + .../resources/backends/ace-step.lock | 2608 +++++++++++++++++ .../mlx_agent/resources/backends/mlx-3d.json | 8 +- .../resources/backends/mlx-embeddings.json | 42 +- .../resources/backends/mlx-embeddings.lock | 6 +- .../resources/backends/mlx-video.lock | 6 +- .../mlx_agent/resources/backends/mlx-vlm.lock | 6 +- .../ports/mlx-3d/trellis2/__init__.py | 5 + .../resources/ports/mlx-3d/trellis2/closed.py | 136 + .../ports/mlx-3d/trellis2/components.py | 26 + .../ports/mlx-3d/trellis2/convert.py | 20 +- .../resources/ports/mlx-3d/trellis2/flow.py | 5 +- .../resources/ports/mlx-3d/trellis2/guide.py | 166 ++ .../ports/mlx-3d/trellis2/pipeline.py | 201 +- .../resources/ports/mlx-3d/trellis2/sparse.py | 35 +- .../ports/mlx-3d/triposg/denoiser_cache.py | 110 + .../ports/mlx-3d/triposg/geometry.py | 118 +- .../ports/mlx-3d/triposg/pipeline.py | 67 +- .../ports/mlx-3d/triposg/transformer.py | 79 +- .../ports/mlx-embeddings/kev/__init__.py | 5 + .../ports/mlx-embeddings/kev/convert.py | 185 ++ .../resources/ports/mlx-embeddings/kev/kev.py | 247 ++ .../ports/mlx-video/t2v/denoiser_cache.py | 182 ++ .../resources/ports/mlx-video/t2v/t2v.py | 55 +- .../resources/ports/mlx-vlm/qwen35/convert.py | 30 +- .../mlx_agent/resources/serve-recipes.json | 77 +- .../src/mlx_agent/runner_model_cache.py | 47 + .../codex/mlx-agent/src/mlx_agent/serve.py | 362 ++- .../mlx-agent/src/mlx_agent/serve_profiles.py | 38 +- .../codex/mlx-agent/src/mlx_agent/served.py | 183 ++ .../src/mlx_agent/service_registry.py | 11 +- .../mlx-agent/src/mlx_agent/serving_access.py | 26 + .../mlx-agent/src/mlx_agent/serving_plan.py | 147 + .../src/mlx_agent/source_evidence.py | 128 + .../mlx-agent/src/mlx_agent/speak_runner.py | 7 +- .../mlx-agent/src/mlx_agent/splash_runtime.py | 289 ++ .../src/mlx_agent/standalone_assets.py | 237 ++ .../mlx-agent/src/mlx_agent/strata_runtime.py | 133 +- .../codex/mlx-agent/src/mlx_agent/task_cli.py | 6 +- .../mlx-agent/src/mlx_agent/task_contracts.py | 13 +- .../mlx-agent/src/mlx_agent/task_kinds.py | 79 +- .../mlx-agent/src/mlx_agent/task_serve.py | 218 ++ .../mlx-agent/src/mlx_agent/task_serving.py | 541 ++++ .../codex/mlx-agent/src/mlx_agent/taxonomy.py | 16 +- .../mlx-agent/src/mlx_agent/transactions.py | 11 +- .../src/mlx_agent/transcribe_runner.py | 7 +- .../codex/mlx-agent/src/mlx_agent/video.py | 19 +- .../mlx-agent/src/mlx_agent/video_runner.py | 12 +- .../src/mlx_agent/worker_telemetry.py | 51 + .../src/mlx_agent/worker_transport.py | 66 + .../src/mlx_agent/workflow_activation.py | 255 ++ .../mlx-agent/src/mlx_agent/workflow_sets.py | 355 +++ providers/agy/catalog.json | 2 +- providers/hermes/catalog.json | 2 +- providers/openclaw/catalog.json | 2 +- providers/opencode/catalog.json | 2 +- releases.json | 4 +- 116 files changed, 13201 insertions(+), 855 deletions(-) create mode 100644 packages/codex/mlx-agent/skills/mlx-task/SKILL.md create mode 100644 packages/codex/mlx-agent/src/mlx_agent/acestep_fsq.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/acestep_runner.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/allocator_cache.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/conversion_monitor.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/embed.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/embed_runner.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/fetch_storage.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/front_door.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/identity_pass.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/inference_auth.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/inference_defaults.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/inference_telemetry.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/media_settings.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/memory_budget.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/memory_diagnostics.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/memory_policy.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/music_speed.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/owned_worker.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/private_serve.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/process_table.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/protected_service.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/protected_worker.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/residency.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resident_runner.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resident_worker.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step-build.lock create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step.json create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step.lock create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/closed.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/components.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/guide.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/denoiser_cache.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/__init__.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/convert.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/kev.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-video/t2v/denoiser_cache.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/runner_model_cache.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/served.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/serving_access.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/serving_plan.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/source_evidence.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/splash_runtime.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/standalone_assets.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/task_serve.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/task_serving.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/worker_telemetry.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/worker_transport.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/workflow_activation.py create mode 100644 packages/codex/mlx-agent/src/mlx_agent/workflow_sets.py diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 17a259a..d135bb0 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -13,8 +13,8 @@ "source": { "source": "github", "repo": "cavi-ai/mlx-agent", - "ref": "v0.12.0", - "sha": "fc585f36abdd9d47614327afec4719fa9049d729" + "ref": "v0.13.0", + "sha": "96995d85ba0ae369dbf1d6c1c570ab012a1bbbec" }, "description": "Discover, verify, and wire local MLX-optimized models on Apple Silicon." }, diff --git a/packages/codex/expected-integrity.json b/packages/codex/expected-integrity.json index bfac701..2449f5d 100644 --- a/packages/codex/expected-integrity.json +++ b/packages/codex/expected-integrity.json @@ -1,15 +1,16 @@ { "mlx-agent": { "repository": "cavi-ai/mlx-agent", - "source_commit": "fc585f36abdd9d47614327afec4719fa9049d729", + "source_commit": "96995d85ba0ae369dbf1d6c1c570ab012a1bbbec", "source_path": "providers/codex", - "tree": "b08974c6522c5e049f882f82bb3395fa91b6cf29669345a0b44c897f847dc73d", + "tree": "7317af0f4afada75a7f4b7a86310eb49ca2c431b81a9506ea5a3638dab81892a", "skills": [ "mlx-adopt", "mlx-bench", "mlx-doctor", "mlx-fleet", "mlx-scout", + "mlx-task", "mlx-watch", "mlx-wire" ] diff --git a/packages/codex/mlx-agent/.codex-plugin/plugin.json b/packages/codex/mlx-agent/.codex-plugin/plugin.json index 3379d96..c16659d 100644 --- a/packages/codex/mlx-agent/.codex-plugin/plugin.json +++ b/packages/codex/mlx-agent/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "mlx-agent", - "version": "0.12.0", + "version": "0.13.0", "description": "Structured local MLX discovery, adoption, and wiring for Apple Silicon agents.", "author": { "name": "Sasan Sotoodehfar", diff --git a/packages/codex/mlx-agent/provenance.json b/packages/codex/mlx-agent/provenance.json index 0d1295b..3b614c5 100644 --- a/packages/codex/mlx-agent/provenance.json +++ b/packages/codex/mlx-agent/provenance.json @@ -1,6 +1,6 @@ { "repository": "cavi-ai/mlx-agent", - "source_commit": "fc585f36abdd9d47614327afec4719fa9049d729", + "source_commit": "96995d85ba0ae369dbf1d6c1c570ab012a1bbbec", "source_path": "providers/codex", "included": [ ".codex-plugin", @@ -17,6 +17,6 @@ "exclusion_reason": "Codex skills use the packaged CLI entrypoint; MCP transport artifacts are not required or distributed by this catalog.", "integrity": { "algorithm": "sha256", - "tree": "b08974c6522c5e049f882f82bb3395fa91b6cf29669345a0b44c897f847dc73d" + "tree": "7317af0f4afada75a7f4b7a86310eb49ca2c431b81a9506ea5a3638dab81892a" } } diff --git a/packages/codex/mlx-agent/skills/mlx-task/SKILL.md b/packages/codex/mlx-agent/skills/mlx-task/SKILL.md new file mode 100644 index 0000000..63444a8 --- /dev/null +++ b/packages/codex/mlx-agent/skills/mlx-task/SKILL.md @@ -0,0 +1,24 @@ +--- +name: "mlx-task" +description: "Run, track and collect durable local inference tasks." +--- + +Use `$mlx-agent:mlx-task` to invoke this installed Codex skill explicitly. Codex does not support custom `/mlx-*` slash commands. + +# MLX Task + +Resolve `` as the absolute directory two levels above the directory containing this SKILL.md; it holds `scripts/` and `src/`. Never resolve the bundled executable from the shell working directory. + +canonical capability ID: mlx-agent.task + +List the supported inference kinds and their request contracts without loading a model: + +`python3 /scripts/mlx-agent task capabilities --json` + +Add `--model-path ` to read one local model's optional media settings. To run a task, write a `task-request` JSON file whose `kind`, `model_path` and `parameters` follow the returned contract, then start it with an absolute path: + +`python3 /scripts/mlx-agent task start --request --json` + +Follow it with `task status --id --json`, collect verified output paths with `task result --id --json`, and review recent runs with `task list --json`. `task cancel --id --json` stops a running task; `task verify-model --id --json` rechecks that the model still matches the one the task used. + +Present the returned status, metrics and artifact paths as returned. Tasks use only an existing local model and its installed backend; they must not download model weights, install a runtime, or change configuration. diff --git a/packages/codex/mlx-agent/src/mlx_agent/__init__.py b/packages/codex/mlx-agent/src/mlx_agent/__init__.py index f1b3184..9d15838 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/__init__.py +++ b/packages/codex/mlx-agent/src/mlx_agent/__init__.py @@ -3,4 +3,4 @@ from .contracts import ResultEnvelope __all__ = ["ResultEnvelope"] -__version__ = "0.12.0" +__version__ = "0.13.0" diff --git a/packages/codex/mlx-agent/src/mlx_agent/acestep_fsq.py b/packages/codex/mlx-agent/src/mlx_agent/acestep_fsq.py new file mode 100644 index 0000000..4819e78 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/acestep_fsq.py @@ -0,0 +1,9 @@ +"""Create ACE-Step's quantizer constants outside Transformers' meta device.""" +import torch +from vector_quantize_pytorch import ResidualFSQ as _ResidualFSQ + + +class ResidualFSQ(_ResidualFSQ): + def __init__(self, *args, **kwargs): + with torch.device("cpu"): + super().__init__(*args, **kwargs) diff --git a/packages/codex/mlx-agent/src/mlx_agent/acestep_runner.py b/packages/codex/mlx-agent/src/mlx_agent/acestep_runner.py new file mode 100644 index 0000000..82f9502 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/acestep_runner.py @@ -0,0 +1,144 @@ +"""Run inside the isolated ACE-Step backend; write a new WAV and measured metrics. + +ACE-Step copies its model code into the checkpoint folder it loads and keeps a progress cache in +its project root, so both live in a private folder of links to the checkpoint's weights and configs; +nothing is written into the model folder or the working directory. +The network is closed: every file comes from the folders beside the checkpoint. +""" + +import argparse +import json +import os +from pathlib import Path +import socket +import tempfile +import time + +SIBLINGS = ("vae", "Qwen3-Embedding-0.6B") + + +def offline(*args, **kwargs): + raise OSError("network access is disabled for music generation") + + +def link_folder(source, target): + """Link every file of a checkpoint folder except Python code into a new folder.""" + target.mkdir() + for entry in sorted(Path(source).iterdir()): + if entry.suffix == ".py" or entry.name == "__pycache__": + continue + (target / entry.name).symlink_to(entry.resolve()) + + +def stage(model, planner, directory): + """A checkpoints folder that holds links to the DiT, its VAE, text encoder and planner.""" + checkpoints = Path(directory) / "checkpoints" + checkpoints.mkdir() + for name in (model.name, *SIBLINGS, *([planner] if planner else [])): + link_folder(model.parent / name, checkpoints / name) + return checkpoints + + +def adapt_quantizer(checkpoint): + """Adapt the trusted model code copied into the private staging folder.""" + files = list(Path(checkpoint).glob("modeling_acestep_v15_*.py")) + if len(files) != 1 or files[0].is_symlink(): + raise RuntimeError("ACE-Step staged model code is missing or ambiguous") + path = files[0] + source = path.read_text(encoding="utf-8") + original = "from vector_quantize_pytorch import ResidualFSQ" + replacement = "from acestep_fsq import ResidualFSQ" + if source.count(original) != 1 or replacement in source: + raise RuntimeError("ACE-Step staged quantizer import is unexpected") + path.write_text(source.replace(original, replacement), encoding="utf-8") + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("model", "caption", "lyrics", "out"): + parser.add_argument("--" + name, required=True) + parser.add_argument("--duration", type=float, required=True) + parser.add_argument("--steps", type=int, required=True) + parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--shift", type=float, required=True) + parser.add_argument("--guidance", type=float, required=True) + parser.add_argument("--bpm", type=int) + parser.add_argument("--time-signature", type=int) + parser.add_argument("--reference") + parser.add_argument("--planner") + args = parser.parse_args(argv) + model, out = Path(args.model), Path(args.out) + from acestep.model_downloader import _CHECKPOINT_TO_VARIANT + if model.name not in _CHECKPOINT_TO_VARIANT: + print(json.dumps({"error": "unknown_checkpoint", "detail": model.name}), flush=True) + return 2 + socket.socket.connect = offline + socket.create_connection = offline + os.environ.update(HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", HF_HUB_DISABLE_IMPLICIT_TOKEN="1") + import mlx.core as mx + import soundfile + from acestep.handler import AceStepHandler + from acestep.inference import GenerationConfig, GenerationParams, generate_music + from acestep.llm_inference import LLMHandler + + class LocalHandler(AceStepHandler): + """Never download: the staged folders hold every file the DiT, VAE and text encoder read.""" + + def _ensure_models_present(self, *, checkpoint_path, config_path, prefer_source, vae_variant=None): + return None + + def _sync_model_code_if_needed(self, config_path, checkpoint_path): + super()._sync_model_code_if_needed(config_path, checkpoint_path) + adapt_quantizer(Path(checkpoint_path) / config_path) + + instrumental = args.lyrics.strip().lower() == "[instrumental]" + # The take is written beside the output, so linking it to the output name stays on one volume. + with tempfile.TemporaryDirectory(prefix="mlx-agent-acestep-") as directory, \ + tempfile.TemporaryDirectory(prefix=".acestep-", dir=out.parent) as scratch: + checkpoints = stage(model, args.planner, directory) + # ACE-Step keeps its progress cache under its project root, the working directory by default. + os.environ.update(ACESTEP_CHECKPOINTS_DIR=str(checkpoints), ACESTEP_PROJECT_ROOT=directory) + started = time.perf_counter() + handler = LocalHandler() + status, ok = handler.initialize_service( + project_root=directory, config_path=model.name, device="mps", use_flash_attention=False, + compile_model=False, offload_to_cpu=False, offload_dit_to_cpu=False, quantization=None, use_mlx_dit=True) + if not ok: + raise RuntimeError("ACE-Step did not load: {0}".format(status)) + planner = None + if args.planner: + planner = LLMHandler() + status, ok = planner.initialize(checkpoint_dir=str(checkpoints), lm_model_path=args.planner, + backend="mlx", device="mps") + if not ok: + raise RuntimeError("The ACE-Step planner did not load: {0}".format(status)) + load_seconds = time.perf_counter() - started + mx.reset_peak_memory() + params = GenerationParams( + task_type="text2music", caption=args.caption, lyrics="[Instrumental]" if instrumental else args.lyrics, + instrumental=instrumental, bpm=args.bpm, + timesignature=str(args.time_signature) if args.time_signature else "", + duration=args.duration, inference_steps=args.steps, guidance_scale=args.guidance, shift=args.shift, + seed=args.seed, thinking=planner is not None, use_cot_metas=planner is not None, + use_cot_caption=planner is not None, use_cot_language=planner is not None, + reference_audio=args.reference) + config = GenerationConfig(batch_size=1, use_random_seed=False, seeds=[args.seed], audio_format="wav") + started = time.perf_counter() + result = generate_music(dit_handler=handler, llm_handler=planner, params=params, config=config, + save_dir=scratch) + seconds = time.perf_counter() - started + if not result.success or not result.audios: + raise RuntimeError("ACE-Step generated nothing: {0}".format(result.error)) + written = Path(result.audios[0]["path"]) + info = soundfile.info(str(written)) + # A hard link claims the new output name or fails, so an existing file is never replaced. + os.link(written, out) + audio_seconds = info.frames / info.samplerate + print(json.dumps({"path": str(out), "sample_rate": info.samplerate, "audio_seconds": audio_seconds, + "seconds": seconds, "load_seconds": load_seconds, "real_time_factor": seconds / audio_seconds, + "peak_memory_gb": mx.get_peak_memory() / 1e9}), flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/codex/mlx-agent/src/mlx_agent/allocator_cache.py b/packages/codex/mlx-agent/src/mlx_agent/allocator_cache.py new file mode 100644 index 0000000..0083f54 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/allocator_cache.py @@ -0,0 +1,119 @@ +"""Optional free-buffer controls inside one admitted resident MLX worker.""" +import importlib +import sys +import time + +FIELDS = frozenset(('allocator_cache_limit_mib', 'cache_reclaim')) +MODES = ('off', 'idle', 'pressure') + + +class CacheUnavailable(ValueError): + pass + + +def policy(value=None): + value = {} if value is None else value + if not isinstance(value, dict) or set(value) - FIELDS: + raise ValueError('Unknown allocator cache policy fields.') + limit, mode = value.get('allocator_cache_limit_mib'), value.get('cache_reclaim', 'off') + if limit is not None and (type(limit) is not int or not 0 <= limit <= 1048576): + raise ValueError('Allocator cache limit must be null or an integer from 0 to 1048576 MiB.') + if mode not in MODES: + raise ValueError('Cache reclaim must be off, idle or pressure.') + return {'allocator_cache_limit_mib': limit, 'cache_reclaim': mode} + + +def from_memory(value): + return policy({key: value[key] for key in FIELDS if key in value}) + + +def requested(value): + settings = from_memory(value) + return settings['allocator_cache_limit_mib'] is not None or settings['cache_reclaim'] != 'off' + + +def validate_state(value): + if not isinstance(value, dict) or set(value) != {'available', 'applied_policy', 'last_reclaim', 'error'}: + raise ValueError('Invalid allocator cache state.') + if type(value['available']) is not bool or value['error'] is not None and not isinstance(value['error'], str): + raise ValueError('Invalid allocator cache availability.') + if value['applied_policy'] is not None: + policy(value['applied_policy']) + last = value['last_reclaim'] + if last is not None: + if not isinstance(last, dict) or set(last) != {'reason', 'before_cache_bytes', 'after_cache_bytes', 'released_cache_bytes', 'captured_at'}: + raise ValueError('Invalid allocator reclaim observation.') + if last['reason'] not in ('manual', 'idle', 'pressure', 'policy', 'limit'): + raise ValueError('Invalid allocator reclaim reason.') + if any(type(last[key]) is not int or last[key] < 0 for key in ('before_cache_bytes', 'after_cache_bytes', 'released_cache_bytes')): + raise ValueError('Invalid allocator reclaim size.') + if type(last['captured_at']) not in (int, float) or not 0 <= last['captured_at'] < float('inf'): + raise ValueError('Invalid allocator reclaim time.') + return value + + +class AllocatorCache: + def __init__(self): + self.desired = policy() + self.applied = None + self.default_limit = None + self.current_limit = None + self.last_reclaim = None + self.error = None + + @staticmethod + def _core(required=False): + core = sys.modules.get('mlx.core') + if core is None and required: + try: + core = importlib.import_module('mlx.core') + except (ImportError, RuntimeError) as error: + raise CacheUnavailable('The worker MLX allocator is unavailable.') from error + if core is None or not all(callable(getattr(core, name, None)) for name in + ('set_cache_limit', 'get_cache_memory', 'clear_cache', 'synchronize')): + if required: + raise CacheUnavailable('This backend does not expose MLX allocator cache controls.') + return None + return core + + def configure(self, value): + self.desired = policy(value) + + def apply_limit(self, enforce=True): + try: + limit = self.desired['allocator_cache_limit_mib'] + core = self._core(requested(self.desired) or self.default_limit is not None) + if core is not None: + if limit is not None: + previous = core.set_cache_limit(limit * 1024**2) + if self.default_limit is None: + self.default_limit = previous + self.current_limit = limit + if enforce and core.get_cache_memory() > limit * 1024**2: + self.reclaim('limit') + elif self.current_limit is not None: + core.set_cache_limit(self.default_limit) + self.current_limit = None + self.applied = dict(self.desired) + self.error = None + except (ValueError, RuntimeError, NotImplementedError) as error: + self.error = str(error) + raise CacheUnavailable(str(error)) from error + + def reclaim(self, reason): + try: + core = self._core(True) + core.synchronize() + before = core.get_cache_memory() + core.clear_cache() + after = core.get_cache_memory() + self.last_reclaim = {'reason': reason, 'before_cache_bytes': before, 'after_cache_bytes': after, + 'released_cache_bytes': max(0, before - after), 'captured_at': time.time()} + self.error = None + except (ValueError, RuntimeError, NotImplementedError) as error: + self.error = str(error) + raise CacheUnavailable(str(error)) from error + + def snapshot(self): + return validate_state({'available': self._core() is not None, 'applied_policy': self.applied, + 'last_reclaim': self.last_reclaim, 'error': self.error}) diff --git a/packages/codex/mlx-agent/src/mlx_agent/backend_install.py b/packages/codex/mlx-agent/src/mlx_agent/backend_install.py index 9bb8555..72c0732 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/backend_install.py +++ b/packages/codex/mlx-agent/src/mlx_agent/backend_install.py @@ -140,6 +140,13 @@ def plan_install(backend_id, manifests=None, root=None, python=None, version_inf plan["build_lock_sha256"] = hashlib.sha256(build_lock.read_bytes()).hexdigest() plan["argv"] += ["--build-lock", str(build_lock)] plan["network"] += ["github.com", "release-assets.githubusercontent.com"] + elif backend_id == "ace-step": + build_lock = BACKENDS_DIR / "ace-step-build.lock" + if not build_lock.is_file(): + raise BackendError("lock_missing", "The ACE-Step build lock is missing.", "Reinstall mlx-agent; the lock ships with it.") + plan["build_lock_sha256"] = hashlib.sha256(build_lock.read_bytes()).hexdigest() + plan["argv"] += ["--build-lock", str(build_lock)] + plan["network"] += ["github.com", "codeload.github.com"] plan = _finalize(plan) plan["argv"] = plan["argv"] + ["--preview-hash", plan["preview_hash"]] return plan diff --git a/packages/codex/mlx-agent/src/mlx_agent/backend_runner.py b/packages/codex/mlx-agent/src/mlx_agent/backend_runner.py index a555a0c..0874127 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/backend_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/backend_runner.py @@ -52,6 +52,20 @@ def main(argv=None): "--require-hashes", "--no-deps", "--only-binary=:all:", "-r", build_lock]) steps[2] += ["--no-binary=docopt", "--no-build-isolation"] steps.append([venv_python, str(Path(__file__).with_name("kokoro_runtime.py"))]) + elif arguments.id == "ace-step": + # ACE-Step installs from its pinned, hashed source archive, built with hashed + # hatchling and build isolation disabled; its dependencies stay binary-only. + build_lock = arguments.build_lock or str(Path(arguments.lock).with_name("ace-step-build.lock")) + steps.insert(1, [venv_python, "-m", "pip", "install", "--disable-pip-version-check", "--no-input", + "--require-hashes", "--no-deps", "--only-binary=:all:", "-r", build_lock]) + steps[2] += ["--no-binary=ace-step", "--no-build-isolation"] + steps[3] = [venv_python, "-c", ( + "import mlx.core; import soundfile; " + "from acestep.model_downloader import _CHECKPOINT_TO_VARIANT; " + "from acestep.handler import AceStepHandler; " + "from acestep.inference import GenerationConfig, GenerationParams, generate_music; " + "from acestep.llm_inference import LLMHandler" + )] for step in steps: print("$ " + " ".join(step), flush=True) completed = subprocess.run(step, stdin=subprocess.DEVNULL, check=False) diff --git a/packages/codex/mlx-agent/src/mlx_agent/backends.py b/packages/codex/mlx-agent/src/mlx_agent/backends.py index d19f226..46a6068 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/backends.py +++ b/packages/codex/mlx-agent/src/mlx_agent/backends.py @@ -20,12 +20,16 @@ INSTALL_MARKER = ".mlx-agent-backend.json" PORT_MARKER = ".mlx-agent-port.json" CATEGORIES = ("text_llm", "vision_language", "speech_to_text", "text_to_speech", "classification", "image_generation", - "video_generation", "music_generation", "mesh_generation") + "video_generation", "music_generation", "mesh_generation", "embedding") MAX_PROBE_FILES = 4000 MAX_PROBE_FILE_BYTES = 1024 * 1024 -QUANTIZED_BITS = (4, 5, 6, 8) +QUANTIZED_BITS = (2, 3, 4, 5, 6, 8) +FLOAT_BITS = (16, 32) +CONVERSION_BITS = QUANTIZED_BITS + FLOAT_BITS +OPTIONAL_DEFAULT_BITS = (4, 5, 6, 8) UNQUANTIZED_BITS = 32 # full-precision weights; only ports that declare it in port_bits accept it TYPE_PREFERENCE = { + "embedding": ("mlx-embeddings",), "speech_to_text": ("mlx-audio",), "text_to_speech": ("mlx-audio",), "music_generation": ("mlx-audio",), @@ -126,11 +130,11 @@ def _validate_manifest(value, path): raise _invalid(path, "port_quantize group_size must be 32, 64, or 128") bits = value.get("port_bits", {}) if not isinstance(bits, dict) or not set(bits) <= ported or not all( - _valid_widths(widths, QUANTIZED_BITS + (UNQUANTIZED_BITS,)) for widths in bits.values() + _valid_widths(widths, CONVERSION_BITS) for widths in bits.values() ): - raise _invalid(path, "port_bits map declared ports to the bit widths (4, 5, 6, 8, or 32 for unquantized) their conversions keep accurate") + raise _invalid(path, "port_bits map declared ports to supported conversion widths") if "q_bits" in value and not _valid_widths(value["q_bits"], QUANTIZED_BITS): - raise _invalid(path, "q_bits lists the bit widths (4, 5, 6 or 8) the backend's converter accepts") + raise _invalid(path, "q_bits lists the supported quantized widths the backend's converter accepts") converters = value.get("port_convert", {}) if not isinstance(converters, dict) or not set(converters) <= ported or not all( isinstance(module, str) and _PORT.fullmatch(module) for module in converters.values() @@ -265,7 +269,7 @@ def conversion_bits(model_type, backend_id, manifests): if widths: return widths declared = (manifests.get(backend_id) or {}).get("q_bits") - return sorted(declared) if declared else list(QUANTIZED_BITS) + return sorted(declared) if declared else list(CONVERSION_BITS if backend_id in (None, "mlx-lm") else OPTIONAL_DEFAULT_BITS) def port_files(model_type, backend_id, manifests): diff --git a/packages/codex/mlx-agent/src/mlx_agent/chat_completions.py b/packages/codex/mlx-agent/src/mlx_agent/chat_completions.py index 8400153..2831b81 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/chat_completions.py +++ b/packages/codex/mlx-agent/src/mlx_agent/chat_completions.py @@ -46,6 +46,30 @@ def end_of_sequence(model_path): return token if isinstance(token, str) and token else None +def _chat_template(model_path): + path = Path(model_path) + try: + return (path / "chat_template.jinja").read_text(encoding="utf-8") + except OSError: + pass + try: + config = json.loads((path / "tokenizer_config.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + return "" + template = config.get("chat_template") if isinstance(config, dict) else None + return template if isinstance(template, str) else json.dumps(template) + + +def vlm_tool_parser(model_path): + """Return the MLX-VLM tool parser a model's template needs but the server does not infer, or None. + + MLX-VLM selects its Qwen3-Coder XML parser only when the template puts a newline + between and workflow_sets.MAX_BYTES: + raise ValueError("Workflow definition is too large.") + data = workflow_sets.save_workflow(arguments.name, json.loads(raw), arguments.receipts_dir) + elif command == "list": + data = {"workflows": workflow_sets.list_workflows(arguments.receipts_dir)} + elif command == "delete": + workflow_sets.delete_workflow(arguments.name, arguments.receipts_dir) + data = {"name": arguments.name, "deleted": True} + else: + definition = workflow_sets.load_workflow(arguments.name, arguments.receipts_dir) + data = workflow_sets.preview_workflow(definition, receipts_dir=arguments.receipts_dir) if command == "preview" else definition + return _emit_serve_result(ResultEnvelope.ok(operation, data), arguments.json, + human=json.dumps(data, indent=2)) if arguments.serve_command == "discover": from .service_registry import discover_services data = discover_services(arguments.receipts_dir) @@ -1090,6 +1207,11 @@ def _run_serve(arguments): {"expected_start": arguments.expected_start} if arguments.expected_start is not None else {})) return _emit_serve_result(ResultEnvelope.ok(operation, outcome), arguments.json, human="Model unloaded; endpoint remains reachable on port {}.".format(arguments.port)) + if arguments.serve_command == 'reclaim-cache': + outcome = reclaim_serve_cache(arguments.port, arguments.receipts_dir, arguments.expected_pid, + expected_start=arguments.expected_start) + return _emit_serve_result(ResultEnvelope.ok(operation, outcome), arguments.json, + human='Allocator cache reclaimed on port {}.'.format(arguments.port)) if arguments.serve_command == "policy": outcome = configure_serve_memory(arguments.port, _memory_arguments(arguments), arguments.receipts_dir, arguments.expected_pid, **( {"expected_start": arguments.expected_start} if arguments.expected_start is not None else {})) @@ -1100,6 +1222,8 @@ def _run_serve(arguments): from .serve_profiles import load_profile settings = load_profile(arguments.profile, arguments.receipts_dir) for key, value in settings.items(): + if key == 'allocator_cache_limit_mib' and arguments.clear_allocator_cache_limit: + continue if key == "strata_decoding" and arguments.strata_speculation is not None: continue if key == "memory_budget_gb" and arguments.strata_expert_memory_gb is not None: @@ -1112,9 +1236,9 @@ def _run_serve(arguments): selected_runtime = "mlx_lm" if arguments.training_receipt and arguments.runtime == "auto" else arguments.runtime runtime, executable = resolve_serve_runtime( arguments.repo, arguments.path, selected_runtime, recipes, hf_cache=arguments.hf_cache) - if arguments.profile and runtime != "strata": - raise ServeError("invalid_arguments", "Saved serving profiles currently require Strata.", - "Select a prepared Strata model or omit --profile.") + if arguments.profile and any(key in settings for key in ("strata_context_tokens", "strata_decoding")) and runtime != "strata": + raise ServeError("invalid_arguments", "Profiles with Strata settings require the Strata runtime.", + "Select a prepared Strata model or a profile containing only common settings.") if arguments.strata_speculation is not None and runtime != "strata": raise ServeError("invalid_arguments", "--strata-speculation requires the Strata runtime.", "Select a prepared local Strata profile.") plan = plan_start( @@ -1127,6 +1251,8 @@ def _run_serve(arguments): training_receipt=arguments.training_receipt, path=arguments.path, jit=arguments.jit, + api_key_file=arguments.api_key_file, + api_key_sha256=arguments.api_key_sha256, receipts_dir=arguments.receipts_dir, hf_cache=arguments.hf_cache, runtime_executable=executable, @@ -1134,18 +1260,20 @@ def _run_serve(arguments): strata_decoding=arguments.strata_decoding, strata_expert_memory_gb=arguments.strata_expert_memory_gb, strata_context_tokens=arguments.strata_context_tokens, - memory_policy=_memory_arguments(arguments) if (arguments.idle_timeout is not None or arguments.keep_loaded - or arguments.min_headroom_gb is not None - or arguments.context_tokens is not None - or arguments.unload_under_pressure - or arguments.memory_budget_gb is not None) else None, + memory_policy=_start_memory_policy(arguments, runtime), thinking=arguments.thinking, + system_prompt=arguments.system_prompt, + default_temperature=arguments.default_temperature, + default_top_p=arguments.default_top_p, m5_prefill=arguments.m5_prefill, prompt_lookup=arguments.prompt_lookup, vision_cache=arguments.vision_cache, + splash_draft_model=arguments.splash_draft_model, + splash_max_memory_gb=arguments.splash_max_memory_gb, + splash_max_context_tokens=arguments.splash_max_context, ) if arguments.launchd: - if arguments.jit: + if plan.get("jit"): raise ServeError("invalid_arguments", "JIT endpoints require the supervised serve lifecycle.", "Use the app's endpoint supervisor instead of --launchd.") return _run_serve_launchd(arguments, plan, operation) @@ -1589,9 +1717,12 @@ def _add_intake_arguments(parser): ) fetch.add_argument("source") fetch.add_argument("--file", default=None) + fetch.add_argument("--additional-file", action="append", default=[], help="exact companion or shard at the same immutable revision (repeatable)") fetch.add_argument("--revision", default=None) fetch.add_argument("--hf-cache", default=None) fetch.add_argument("--local-dir", default=None) + fetch.add_argument("--storage-root", default=None, help="owned source-admission index (defaults to XDG state for immutable managed fetches)") + fetch.add_argument("--downloads-dir", default=None, help="reviewed support-file location (inside a managed local destination)") fetch.add_argument( "--model-type", default=None, help="model_type from intake resolve; a ported type downloads only the port's files", @@ -1666,9 +1797,23 @@ def _run_intake(arguments): jobs = status_fetch(arguments.receipts_dir) return _emit_serve_result(ResultEnvelope.ok(operation, {"jobs": jobs}), arguments.json) if arguments.intake_command == "fetch": - plan = plan_fetch(arguments.source, revision=arguments.revision, file=arguments.file, + from .fetch_storage import default_root + from .source_evidence import immutable_revision + storage = arguments.storage_root + if arguments.local_dir: + from .intake_source import parse_hf_source + requested_revision = arguments.revision or parse_hf_source(arguments.source)["revision"] + if not immutable_revision(requested_revision): + raise FetchError("immutable_revision_required", "A local model destination requires an immutable resolved commit.", + "Resolve the source, then pass its resolved_revision through --revision.") + if arguments.hf_cache: + raise FetchError("invalid_arguments", "A managed destination cannot copy a shared Hugging Face cache.", + "Use the existing cache in place, or omit --hf-cache for source-admitted managed storage.") + if storage is None: + storage = default_root() + plan = plan_fetch(arguments.source, revision=arguments.revision, file=arguments.file, additional_files=arguments.additional_file, hf_cache=arguments.hf_cache, local_dir=arguments.local_dir, - model_type=arguments.model_type) + model_type=arguments.model_type, downloads_dir=arguments.downloads_dir, storage_root=storage) outcome = start_fetch(plan, receipts_dir=arguments.receipts_dir, confirm=arguments.confirm, preview_hash=arguments.preview_hash) if outcome["status"] == "preview": @@ -1789,7 +1934,7 @@ def _run_backend(arguments): def _add_convert_arguments(parser): - from .convert import Q_BITS_CHOICES, UNQUANTIZED_BITS + from .convert import Q_BITS_CHOICES, FLOAT_BITS actions = parser.add_subparsers(dest="convert_command", required=True) start = actions.add_parser( "start", @@ -1807,13 +1952,20 @@ def _add_convert_arguments(parser): help="model_type from intake resolve; selects a port's own converter when it ships one", ) start.add_argument("--subfolder", default=None, help="checkpoint folder inside the repository (converts from the cache)") - start.add_argument("--q-bits", type=int, default=4, choices=Q_BITS_CHOICES + (UNQUANTIZED_BITS,)) + start.add_argument("--q-bits", type=int, default=4, choices=Q_BITS_CHOICES + FLOAT_BITS) start.add_argument("--out", default=None, help="output directory (default -MLX-bit)") start.add_argument("--confirm", action="store_true", help="authorize this reviewed conversion") start.add_argument("--preview-hash", help="hash returned by the separately reviewed convert preview") start.add_argument("--receipts-dir", default=None) start.add_argument("--hf-cache", default=None) start.add_argument("--source-path", default=None, help="exact downloaded checkpoint directory for --repo; no second download") + start.add_argument("--downloads-dir", default=None, help="exact reviewed support-file directory for --repo") + start.add_argument("--projector", help="exact matching local vision projector GGUF") + start.add_argument("--require-projector", action="store_true", help="refuse a missing or ambiguous vision projector") + start.add_argument("--fetch-receipt", help="completed immutable managed fetch receipt for the primary source") + start.add_argument("--dependency-fetch-receipt", action="append", default=[], help="completed managed dependency fetch receipt (repeatable)") + start.add_argument("--require-completion", action="store_true", help="record actual worker exit and normalized output provenance") + start.add_argument("--attempt-id", default=None, help=argparse.SUPPRESS) start.add_argument("--json", action="store_true") status = actions.add_parser("status", help="cross-check convert receipts against live processes") status.add_argument("--receipts-dir", default=None) @@ -1836,6 +1988,8 @@ def _add_convert_arguments(parser): "--no-signature", action="store_true", help="skip content signatures (faster, weaker duplicate detection)", ) + scan.add_argument("--compare-assets", action="store_true", help="compare same-size standalone model files by full SHA-256") + scan.add_argument("--asset-exclude-root", action="append", default=[], help="exclude a directory from standalone model-file scanning (repeatable)") scan.add_argument("--pending-only", action="store_true", help="list only unconverted models") scan.add_argument("--json", action="store_true") transcribe = actions.add_parser( @@ -1876,6 +2030,9 @@ def _add_convert_arguments(parser): music.add_argument("--duration", type=float, default=15.0) music.add_argument("--steps", type=int, default=30) music.add_argument("--seed", type=int, default=42) + music.add_argument("--bpm", type=int, help="tempo for ACE-Step models (30..300)") + music.add_argument("--time-signature", type=int, help="beats per bar for ACE-Step models: 2, 3, 4 or 6") + music.add_argument("--reference", help="absolute audio file whose style ACE-Step models follow") music.add_argument("--timeout", type=int, default=3600) music.add_argument("--json", action="store_true") speak = actions.add_parser( @@ -1915,6 +2072,14 @@ def _add_convert_arguments(parser): "Pixal3D 1024 or 1536 (default)") mesh.add_argument("--guidance", type=float, default=None, help="default: the model's own (TripoSG 7)") mesh.add_argument("--max-faces", type=int, default=500000) + mesh.add_argument('--denoiser-cache', choices=('off','adaptive'), default='off', + help='adaptive residual forecasting for TripoSG; may change geometry') + mesh.add_argument('--cache-memory-mib', type=int, default=256, + help='adaptive feature-memory cap in MiB, 8..4096 (default: 256)') + mesh.add_argument("--view", action="append", default=[], + help="TRELLIS.2: another image of the object, conditioning sampler steps in turn; repeatable") + mesh.add_argument("--guide", default=None, + help="TRELLIS.2: a GLB whose surface voxels replace the sampled sparse structure") mesh.add_argument("--timeout", type=int, default=3600) mesh.add_argument("--json", action="store_true") video = actions.add_parser( @@ -1930,6 +2095,10 @@ def _add_convert_arguments(parser): video.add_argument("--fps", type=int, default=None, help="playback rate written to the MP4 (default: the model's, 16 for Wan2.1)") video.add_argument("--steps", type=int, default=None, help="denoising steps (default: the model's, 50 for Wan2.1)") video.add_argument("--seed", type=int, default=42) + video.add_argument("--denoiser-cache", choices=("off", "adaptive"), default="off", + help="adaptive residual reuse for Wan2.1 T2V; may change generated frames") + video.add_argument("--cache-memory-mib", type=int, default=256, + help="adaptive feature-memory cap in MiB, 8..4096 (default: 256)") video.add_argument("--timeout", type=int, default=3600, help="seconds before the backend run is stopped") video.add_argument("--json", action="store_true") @@ -1949,6 +2118,18 @@ def _run_convert(arguments): from .video import plan_video, run_video from .mesh import plan_mesh, run_mesh operation = "convert-{0}".format(arguments.convert_command) + + def served_or_local(verb, runner, plan, out): + # A typed endpoint that already holds this model runs the job; the model never loads twice. + from . import served + kind, parameters = served.request(verb, arguments) + service = served.endpoint(arguments.path, kind) + if service is not None: + return served.run(service, kind, parameters, None if out is None else str(Path(out).expanduser()), + arguments.timeout) + from .compute import guarded_start + return guarded_start(verb, runner, plan, timeout=arguments.timeout) + try: if arguments.convert_command == "status": entries = status_convert(arguments.receipts_dir) @@ -1978,24 +2159,22 @@ def _run_convert(arguments): raise ValueError("--timeout must be 1..7200 seconds") plan = plan_generate(arguments.path, arguments.prompt, arguments.out, width=arguments.width, height=arguments.height, steps=arguments.steps, seed=arguments.seed) - from .compute import guarded_start - result = guarded_start("generate", run_generate, plan, timeout=arguments.timeout) + result = served_or_local("generate", run_generate, plan, arguments.out) return _emit_serve_result(ResultEnvelope.ok(operation, result), arguments.json, human=result["path"]) if arguments.convert_command == "music": if not 1 <= arguments.timeout <= 14400: raise ValueError("--timeout must be 1..14400 seconds") plan = plan_music(arguments.path, arguments.caption, arguments.lyrics, arguments.out, - duration=arguments.duration, steps=arguments.steps, seed=arguments.seed) - from .compute import guarded_start - result = guarded_start("music", run_music, plan, timeout=arguments.timeout) + duration=arguments.duration, steps=arguments.steps, seed=arguments.seed, + bpm=arguments.bpm, time_signature=arguments.time_signature, reference=arguments.reference) + result = served_or_local("music", run_music, plan, arguments.out) return _emit_serve_result(ResultEnvelope.ok(operation, result), arguments.json, human=result["path"]) if arguments.convert_command == "speak": if not 1 <= arguments.timeout <= 7200: raise ValueError("--timeout must be 1..7200 seconds") plan = plan_speak(arguments.path, arguments.text, arguments.out, voice=arguments.voice, speed=arguments.speed, lang_code=arguments.lang_code) - from .compute import guarded_start - result = guarded_start("speak", run_speak, plan, timeout=arguments.timeout) + result = served_or_local("speak", run_speak, plan, arguments.out) return _emit_serve_result(ResultEnvelope.ok(operation, result), arguments.json, human=result["path"]) if arguments.convert_command == "describe": if not 1 <= arguments.timeout <= 7200: @@ -2003,15 +2182,16 @@ def _run_convert(arguments): plan = plan_describe(arguments.path, arguments.prompt, image=arguments.image, video=arguments.video, max_tokens=arguments.max_tokens, temperature=arguments.temperature, fps=arguments.fps, max_pixels=arguments.max_pixels) - from .compute import guarded_start - result = guarded_start("describe", run_describe, plan, timeout=arguments.timeout) + result = served_or_local("describe", run_describe, plan, None) return _emit_serve_result(ResultEnvelope.ok(operation, result), arguments.json, human=result["text"]) if arguments.convert_command == "mesh": if not 1 <= arguments.timeout <= 14400: raise ValueError("--timeout must be 1..14400 seconds") plan = plan_mesh(arguments.path, arguments.image, arguments.out, steps=arguments.steps, seed=arguments.seed, resolution=arguments.resolution, guidance=arguments.guidance, - max_faces=arguments.max_faces) + max_faces=arguments.max_faces, denoiser_cache=arguments.denoiser_cache, + cache_memory_mib=arguments.cache_memory_mib, views=arguments.view, + guide=arguments.guide) from .compute import guarded_start result = guarded_start("mesh", run_mesh, plan, timeout=arguments.timeout) return _emit_serve_result(ResultEnvelope.ok(operation, result), arguments.json, human=result["path"]) @@ -2020,9 +2200,9 @@ def _run_convert(arguments): raise ValueError("--timeout must be 1..14400 seconds") plan = plan_video(arguments.path, arguments.prompt, arguments.out, width=arguments.width, height=arguments.height, frames=arguments.frames, fps=arguments.fps, - steps=arguments.steps, seed=arguments.seed) - from .compute import guarded_start - result = guarded_start("video", run_video, plan, timeout=arguments.timeout) + steps=arguments.steps, seed=arguments.seed, + denoiser_cache=arguments.denoiser_cache, cache_memory_mib=arguments.cache_memory_mib) + result = served_or_local("video", run_video, plan, arguments.out) return _emit_serve_result(ResultEnvelope.ok(operation, result), arguments.json, human=result["path"]) if arguments.convert_command == "scan": report = _convert_scan(arguments) @@ -2040,13 +2220,19 @@ def _run_convert(arguments): "Drop --backend when converting a GGUF file.", ) plan = plan_gguf_convert( - arguments.gguf, q_bits=arguments.q_bits, out=arguments.out + arguments.gguf, q_bits=arguments.q_bits, out=arguments.out, projector=arguments.projector, + require_projector=arguments.require_projector, fetch_receipt=arguments.fetch_receipt, + dependency_fetch_receipts=arguments.dependency_fetch_receipt, require_completion=arguments.require_completion, ) else: plan = plan_convert(arguments.repo, q_bits=arguments.q_bits, out=arguments.out, backend=arguments.backend, model_type=arguments.model_type, subfolder=arguments.subfolder, hf_cache=arguments.hf_cache, - source_path=arguments.source_path) + source_path=arguments.source_path, fetch_receipt=arguments.fetch_receipt, downloads_dir=arguments.downloads_dir, + dependency_fetch_receipts=arguments.dependency_fetch_receipt, + require_completion=arguments.require_completion) + if arguments.projector or arguments.require_projector: + raise ConvertError("invalid_arguments", "Projector selection is only valid with --gguf.", "Use the GGUF conversion source.") if not arguments.confirm: result = ResultEnvelope.ok( operation, {"plan": plan, "requires_confirmation": True} @@ -2067,6 +2253,7 @@ def _run_convert(arguments): receipts_dir=arguments.receipts_dir, confirm=True, preview_hash=arguments.preview_hash, + attempt_id=arguments.attempt_id, model_present=None if arguments.gguf else default_model_present(arguments.hf_cache), ) receipt = outcome["receipt"] @@ -2099,7 +2286,7 @@ def _run_convert(arguments): def _convert_scan(arguments): from .convert import ConvertError, load_receipts - from .gguf import MAX_SCAN_FILES, default_gguf_roots, inventory + from .gguf import MAX_SCAN_FILES, default_gguf_roots, families, inventory from .taxonomy import annotate_inventory roots = arguments.gguf_roots if arguments.gguf_roots is not None else ( [] if arguments.mlx_roots is not None else default_gguf_roots()) @@ -2115,12 +2302,20 @@ def _convert_scan(arguments): receipts=load_receipts(arguments.receipts_dir), signature=not arguments.no_signature, limit=arguments.limit or MAX_SCAN_FILES, + compare_assets=arguments.compare_assets, + asset_exclude_roots=arguments.asset_exclude_root, ) if arguments.pending_only: report = dict(report, models=[ item for item in report["models"] if item["status"] == "pending" ]) - return annotate_inventory(report) + from .splash_runtime import annotate_support + report = annotate_inventory(report) + annotate_support(report["outputs"]) + task_types = {item["path"]: item["task"].get("type") for item in report["models"] + report["outputs"] + if isinstance(item.get("task"), dict)} + report["families"] = families(report["storage"]["items"], task_types) + return report def _human_bytes(count): @@ -2162,7 +2357,8 @@ def _convert_scan_human(report, pending_only=False): )) for group in duplicates: if group["kind"] == "exact": - lines.append(" same model and quantization, keep {0}".format(group["keep"])) + description = "identical model files" if group.get("verification") == "full_sha256" else "same model and quantization" + lines.append(" {0}, keep {1}".format(description, group["keep"])) for path in group["redundant"]: lines.append(" redundant: {0}".format(path)) else: @@ -2738,6 +2934,27 @@ def wanted(name): def main(argv=None): raw = list(sys.argv[1:] if argv is None else argv) + if raw[:2] == ["serve", "protected-service"]: + from .protected_service import main as service_main + try: + return service_main(raw[2:]) + except (OSError, ValueError, ImportError, RuntimeError): + print("Protected MLX service unavailable; verify its runtime, private key and local model.", file=sys.stderr) + return 1 + if raw[:2] == ["serve", "front-door"]: + from .front_door import main as front_main + try: + return front_main(raw[2:]) + except (OSError, ValueError): + print("MLX front door unavailable; verify its port and private key.", file=sys.stderr) + return 1 + if raw[:2] == ["serve", "private-worker"]: + from .private_serve import main as private_main + try: + return private_main(raw[2:]) + except (OSError, ValueError, ImportError): + print("Private MLX worker unavailable; verify the installed runtime and local model.", file=sys.stderr) + return 1 if raw and raw[0] == "lab": from .lab import run return run(raw[1:]) diff --git a/packages/codex/mlx-agent/src/mlx_agent/command_args.py b/packages/codex/mlx-agent/src/mlx_agent/command_args.py index 4f3f7d7..aeebb1b 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/command_args.py +++ b/packages/codex/mlx-agent/src/mlx_agent/command_args.py @@ -22,6 +22,7 @@ class CommandArgumentError(ValueError): _RUNTIMES = {"ollama", "lmstudio", "mlx_lm", "mlx-vlm", "litellm"} +_BENCH_RUNTIMES = _RUNTIMES | {"strata", "splash"} _BENCH_WORKLOADS = {"chat", "prefix", "prefill", "concurrent", "cold"} _ROLES = {role for role, _keywords, _label in ROLES} _MODEL = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,95}/[A-Za-z0-9][A-Za-z0-9._-]{0,191}$") @@ -257,7 +258,7 @@ def _parse_bench(tokens): seen = set() values = { "--repo": (lambda value: _model(value), "repo"), - "--runtime": (lambda value: value if value in _RUNTIMES else None, "runtime"), + "--runtime": (lambda value: value if value in _BENCH_RUNTIMES else None, "runtime"), "--role": (lambda value: value if value in _ROLES else None, "role"), "--runs": (lambda value: _integer(value, "runs", 1, 10), "runs"), "--gen-tokens": (lambda value: _integer(value, "gen-tokens", 16, 2048), "gen-tokens"), @@ -297,7 +298,7 @@ def _parse_bench_coding(tokens): argv, index, seen = ["bench", "coding"], 1, set() values = { "--repo": _model, - "--runtime": lambda value: value if value in {"mlx_lm", "lmstudio", "mlx-vlm", "litellm"} else None, + "--runtime": lambda value: value if value in _BENCH_RUNTIMES - {"ollama"} else None, "--base-url": _endpoint, "--gen-tokens": lambda value: _integer(value, "gen-tokens", 256, 1024), "--timeout": lambda value: _decimal(value, "timeout", 1, 600), diff --git a/packages/codex/mlx-agent/src/mlx_agent/command_executor.py b/packages/codex/mlx-agent/src/mlx_agent/command_executor.py index b86e3f8..d97070e 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/command_executor.py +++ b/packages/codex/mlx-agent/src/mlx_agent/command_executor.py @@ -12,7 +12,7 @@ MAX_ARGUMENT_BYTES = 4096 _PROVIDERS = ("opencode",) -_CAPABILITIES = ("scout", "adopt", "wire", "bench", "doctor", "watch", "fleet") +_CAPABILITIES = ("scout", "adopt", "wire", "bench", "doctor", "watch", "fleet", "task") class CommandExecutorError(ValueError): diff --git a/packages/codex/mlx-agent/src/mlx_agent/compute.py b/packages/codex/mlx-agent/src/mlx_agent/compute.py index 071002b..0a2597c 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/compute.py +++ b/packages/codex/mlx-agent/src/mlx_agent/compute.py @@ -1,13 +1,16 @@ -"""One host compute owner shared by native and agent entrypoints.""" +"""Persisted host ownership: exclusive operations and shared served executions.""" from __future__ import annotations import fcntl import json import os +import secrets from pathlib import Path import stat import subprocess import sys +import threading +import time class ComputeBusy(ValueError): @@ -26,6 +29,13 @@ def process_identity(pid): return result.stdout.strip() if result.returncode == 0 else None +def process_birth_identity(pid): + result = subprocess.run(["/bin/ps", "-p", str(pid), "-o", "lstart="], + capture_output=True, text=True, timeout=5) + value = result.stdout.strip() if result.returncode == 0 else "" + return value or None + + def process_alive(pid): try: os.kill(pid, 0) @@ -40,19 +50,15 @@ def group_members(pgid): """Return live members, excluding zombies which no longer own compute.""" if type(pgid) is not int or pgid <= 0: raise ValueError("A process group requires a positive ID.") - result = subprocess.run(["/bin/ps", "-axo", "pid=,pgid=,stat="], capture_output=True, text=True, timeout=5) - if result.returncode != 0: - raise OSError("The process table is unavailable.") - members = [] - for line in result.stdout.splitlines(): - fields = line.split() - if len(fields) >= 3 and int(fields[1]) == pgid and not fields[2].startswith("Z"): - members.append(int(fields[0])) - return members + from .process_table import group + return group(pgid) class ComputeLease: - def __init__(self, operation, root=None, inspector=process_identity, alive=process_alive, group_probe=group_members): + def __init__(self, operation, root=None, inspector=process_identity, alive=process_alive, group_probe=group_members, shared=False): + self.shared = shared + self.host_descriptor = None + self.record_path = None self.operation = operation self.root = Path(root) if root is not None else compute_root() self.inspector, self.alive = inspector, alive @@ -78,76 +84,173 @@ def __enter__(self): info = self.root.stat() if info.st_uid != os.getuid() or info.st_mode & 0o077: raise ValueError("Compute state must be a private owned directory.") - descriptor = os.open(self.root / "owner.json", - os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600) + flags = os.O_RDWR | getattr(os, "O_NOFOLLOW", 0) + try: + descriptor = os.open(self.root / "owner.json", flags | os.O_CREAT | os.O_EXCL, 0o600) + except FileExistsError: + descriptor = os.open(self.root / "owner.json", flags) self.descriptor = descriptor + pending_path = None try: info = os.fstat(descriptor) - if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077: + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_nlink != 1: raise ValueError("Compute ownership must be a private regular file.") try: - fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + fcntl.flock(descriptor, (fcntl.LOCK_SH if self.shared else fcntl.LOCK_EX) | fcntl.LOCK_NB) except BlockingIOError: raise ComputeBusy("Another model operation owns this host.") from None - raw = os.read(descriptor, 8193) - if len(raw) > 8192: - raise ValueError("Compute ownership record is invalid.") - record = json.loads(raw) if raw else {} - if record: - fields = {"schema", "pid", "identity", "operation"} - if isinstance(record, dict) and record.get("schema") == 2: - fields.add("execution_group") - if not isinstance(record, dict) or set(record) != fields: - raise ValueError("Compute ownership record is invalid.") - pid = record["pid"] - if type(pid) is not int or pid <= 0 or record["schema"] not in (1, 2): - raise ValueError("Compute ownership record is invalid.") - if record["schema"] == 2: - group = record["execution_group"] - if (not isinstance(group, dict) or set(group) != {"pgid", "leader_identity"} - or type(group["pgid"]) is not int or group["pgid"] <= 0 - or not isinstance(group["leader_identity"], str) or not group["leader_identity"]): - raise ValueError("Compute execution group is invalid.") - try: - members = self.group_probe(group["pgid"]) - except (OSError, ValueError, subprocess.SubprocessError) as error: - raise ComputeBusy("The recorded execution group cannot be inspected; compute ownership is retained.") from error - if members: - raise ComputeBusy("A recorded task execution group still owns host compute (group {0}).".format(group["pgid"])) - observed = self.inspector(pid) - if self.alive(pid) and (record["identity"] is None or observed is None or observed == record["identity"]): - raise ComputeBusy("Host compute is owned by " + str(record["operation"]) + " (pid " + str(pid) + ").") + self._check_record(descriptor) + self._check_executions() + if self.shared: + self.host_descriptor = descriptor + self.record_path = self.root / ("execution-" + secrets.token_hex(16) + ".json") + staging = self.record_path.with_name('.' + self.record_path.name + '.pending') + self.descriptor = os.open(staging, flags | os.O_CREAT | os.O_EXCL, 0o600) + pending_path = staging + try: + fcntl.flock(self.descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + raise ComputeBusy("Another process is claiming this execution record.") from None identity = self.inspector(os.getpid()) if identity is None: raise ComputeBusy("The current process identity could not be established.") self._write({"schema": 1, "pid": os.getpid(), "identity": identity, "operation": self.operation}) + if pending_path is not None: + # Publish only a locked, complete record; scanners never see creation in flight. + os.replace(pending_path, self.record_path) + pending_path = None return self except BaseException: - os.close(descriptor) - self.descriptor = None + try: + if pending_path is not None: + pending_path.unlink(missing_ok=True) + finally: + if self.descriptor is not None and self.descriptor != descriptor: + os.close(self.descriptor) + os.close(descriptor) + self.host_descriptor = self.descriptor = None raise + def _check_record(self, descriptor): + raw = os.pread(descriptor, 8193, 0) + if len(raw) > 8192: + raise ValueError("Compute ownership record is invalid.") + record = json.loads(raw) if raw else {} + if not isinstance(record, dict): + raise ValueError("Compute ownership record is invalid.") + if record: + fields = {"schema", "pid", "identity", "operation"} + if isinstance(record, dict) and record.get("schema") == 2: + fields.add("execution_group") + if not isinstance(record, dict) or set(record) != fields: + raise ValueError("Compute ownership record is invalid.") + pid = record["pid"] + if (type(pid) is not int or pid <= 0 or type(record["schema"]) is not int + or record["schema"] not in (1, 2) + or not isinstance(record['operation'], str) or not record['operation'] + or record['identity'] is not None and not isinstance(record['identity'], str)): + raise ValueError("Compute ownership record is invalid.") + if record["schema"] == 2: + group = record["execution_group"] + if (not isinstance(group, dict) or set(group) != {"pgid", "leader_identity"} + or type(group["pgid"]) is not int or group["pgid"] <= 0 + or not isinstance(group["leader_identity"], str) or not group["leader_identity"]): + raise ValueError("Compute execution group is invalid.") + try: + members = self.group_probe(group["pgid"]) + except (OSError, ValueError, subprocess.SubprocessError) as error: + raise ComputeBusy("The recorded execution group cannot be inspected; compute ownership is retained.") from error + if members: + raise ComputeBusy("A recorded task execution group still owns host compute (group {0}).".format(group["pgid"])) + observed = self.inspector(pid) + if self.alive(pid) and (record["identity"] is None or observed is None or observed == record["identity"]): + raise ComputeBusy("Host compute is owned by " + str(record["operation"]) + " (pid " + str(pid) + ").") + + def _check_executions(self): + # A crashed gateway releases its flock, but its worker group may survive. + # Active shared records are protected by their own flock and the host lock. + for path in self.root.glob("execution-*.json"): + try: + descriptor = os.open(path, os.O_RDWR | os.O_NOFOLLOW | os.O_NONBLOCK) + except FileNotFoundError: + continue + try: + info = os.fstat(descriptor) + if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() + or info.st_mode & 0o077 or info.st_nlink != 1): + raise ValueError("Compute ownership must be a private regular file.") + try: + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + if not self.shared: + raise ComputeBusy("A served execution still owns host compute.") from None + continue + self._check_record(descriptor) + path.unlink(missing_ok=True) + finally: + os.close(descriptor) + + def enter_wait(self, seconds=0, cancelled=lambda: False): + """Bounded admission; cancellation never transfers ownership.""" + deadline = time.monotonic() + seconds + while True: + if cancelled(): + raise InterruptedError('Execution admission cancelled.') + try: + return self.__enter__() + except ComputeBusy: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise + time.sleep(min(.05, remaining)) + def bind_process_group(self, pid): if self.descriptor is None or type(pid) is not int or pid <= 0: raise ValueError("An active compute lease and positive group leader are required.") + self.execution_group = {"pgid": pid, "leader_identity": "unverified"} + self._write(dict(self.record, schema=2, execution_group=self.execution_group)) identity = self.inspector(pid) if not identity or os.getpgid(pid) != pid: raise ComputeBusy("The task execution group identity could not be established.") self.execution_group = {"pgid": pid, "leader_identity": identity} self._write(dict(self.record, schema=2, execution_group=self.execution_group)) - def handoff(self, pid): + def release_idle_process_group(self, pid, members=None): + """Release only after completion and inspection of the idle private group.""" + expected = {pid: self.execution_group["leader_identity"]} if members is None and self.execution_group else members + if (self.descriptor is None or self.execution_group is None or self.execution_group['pgid'] != pid + or self.inspector(pid) != self.execution_group['leader_identity'] + or not expected or set(self.group_probe(pid)) != set(expected) + or any(self.inspector(member) != identity for member, identity in expected.items())): + raise ComputeBusy("The resident worker has not returned to an inspected idle state.") + self.execution_group = None + self._write({key: value for key, value in self.record.items() if key != 'execution_group'} | {'schema': 1}) + + def handoff(self, pid, process_group=False): if type(pid) is not int or pid <= 0: raise ValueError("Detached compute owner requires a positive PID.") - identity = self.inspector(pid) + if process_group: + self.execution_group = {"pgid": pid, "leader_identity": "unverified"} + record = {"schema": 1, "pid": pid, "identity": None, "operation": self.operation} + if self.execution_group is not None: + record.update(schema=2, execution_group=dict(self.execution_group)) + # Persist ownership before asking ps about a process that already exists. + # Missing identity or a lost leader must never release surviving children. + self._write(record) + self.detached = True + try: + identity = self.inspector(pid) + except (OSError, ValueError, subprocess.SubprocessError) as error: + raise ComputeBusy("The launched process cannot be inspected; its ownership is retained.") from error if identity is None: if not self.alive(pid): - return # A process that already exited owns no compute. - self._write({"schema": 1, "pid": pid, "identity": None, "operation": self.operation}) - self.detached = True + return raise ComputeBusy("The launched process identity could not be established; its ownership is retained.") - self._write({"schema": 1, "pid": pid, "identity": identity, "operation": self.operation}) - self.detached = True + record["identity"] = identity + if record.get("execution_group", {}).get("pgid") == pid: + record["execution_group"]["leader_identity"] = identity + self.execution_group = record["execution_group"] + self._write(record) def __exit__(self, *_): if self.descriptor is not None: @@ -160,15 +263,103 @@ def __exit__(self, *_): group_stopped = False if not self.detached and group_stopped: self._write({}) + if self.record_path is not None: + self.record_path.unlink() finally: os.close(self.descriptor) self.descriptor = None + if self.host_descriptor is not None: + os.close(self.host_descriptor) + self.host_descriptor = None def guarded_start(operation, launch, *args, **kwargs): with ComputeLease(operation) as lease: + observed_conversion = operation == "convert" and bool(args and args[0].get("require_completion")) + if observed_conversion: + kwargs["wait_for_compute_lease"] = True result = launch(*args, **kwargs) pid = result.get("receipt", {}).get("pid") if pid is not None: - lease.handoff(pid) + lease.handoff(pid, process_group=observed_conversion) + if observed_conversion: + from .convert import register_monitor_lease + register_monitor_lease(result["receipt_path"], result["receipt"]) return result + + +class ExecutionAdmission: + """Batch requests to one backend under one shared host lease.""" + def __init__(self, operation, root=None, shared=False): + self.shared = shared + self.operation, self.root = operation, root + self.condition = threading.Condition() + self.lease = None + self.users = 0 + self.waiting = 0 + self.closed = False + + def acquire(self, seconds=0, cancelled=lambda: False): + deadline = time.monotonic() + seconds + with self.condition: + self.waiting += 1 + try: + while True: + if self.closed or cancelled(): + raise InterruptedError('Execution admission cancelled.') + if self.users: + self.users += 1 + return + lease = ComputeLease(self.operation, self.root, shared=self.shared() if callable(self.shared) else self.shared) + try: + lease.__enter__() + except ComputeBusy: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise + self.condition.wait(min(.05, remaining)) + continue + if self.closed or cancelled(): + lease.__exit__(None, None, None) + raise InterruptedError('Execution admission cancelled.') + self.lease, self.users = lease, 1 + return + finally: + self.waiting -= 1 + + def bind(self, pid, refresh=False): + """Bind the backend group; `refresh` records the leader again after it execs.""" + with self.condition: + if self.lease is None: + raise ComputeBusy('Model startup requires execution admission.') + if not refresh and self.lease.execution_group and self.lease.execution_group['pgid'] == pid: + return + self.lease.bind_process_group(pid) + + def release(self, idle): + with self.condition: + if self.users == 0: + return + self.users -= 1 + if self.users == 0: + try: + idle(self.lease) + except BaseException: + # Retain the descriptor until shutdown proves the group stopped. + self.closed = True + self.condition.notify_all() + raise + try: + self.lease.__exit__(None, None, None) + finally: + self.lease = None + self.condition.notify_all() + + def close(self): + with self.condition: + self.closed = True + if self.lease is not None: + self.lease.__exit__(None, None, None) + self.lease = None + self.users = 0 + self.condition.notify_all() diff --git a/packages/codex/mlx-agent/src/mlx_agent/conversion_monitor.py b/packages/codex/mlx-agent/src/mlx_agent/conversion_monitor.py new file mode 100644 index 0000000..c4ac14a --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/conversion_monitor.py @@ -0,0 +1,220 @@ +"""Observe one reviewed conversion worker and publish its actual completion.""" +from __future__ import annotations + +import argparse +from contextlib import contextmanager +from datetime import datetime, timezone +import fcntl +import json +import os +from pathlib import Path +import subprocess +import signal +import sys +import time + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from mlx_agent.source_evidence import completed_fetch, fingerprint, read_json, safe_path +from mlx_agent.transactions import _atomic_in_directory + + +@contextmanager +def receipt_lock(receipt_path): + path = safe_path(receipt_path) + descriptor = os.open(path.with_suffix(".lock"), os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600) + try: + fcntl.flock(descriptor, fcntl.LOCK_EX) + yield path + finally: + os.close(descriptor) + + +def _matches(receipt, request): + plan = request["plan"] + return (receipt.get("launch_id") == request["launch_id"] and receipt.get("pid") == os.getpid() + and receipt.get("attempt_id") == request.get("attempt_id") + and receipt.get("require_completion") is True and receipt.get("preview_hash") == plan["preview_hash"] + and receipt.get("argv") == plan["argv"] and receipt.get("source") == plan["source"] + and receipt.get("out") == plan["out"] and receipt.get("started_at") == request["started_at"]) + + +def _write(path, receipt): + _atomic_in_directory(path.parent, path.name, (json.dumps(receipt, sort_keys=True) + "\n").encode(), 0o600) + + +def _check_sources(plan): + source = plan["source"] + if source.get("fetch_receipt"): + current = completed_fetch(source["fetch_receipt"], source["path"]) + if current["origin"] != source["origin"] or current["fingerprint"] != source["fingerprint"]: + raise ValueError("The reviewed source changed before conversion.") + elif source.get("path") and source.get("fingerprint") and source.get("kind") == "hf-cache": + from mlx_agent.convert import local_source_fingerprint + if local_source_fingerprint(source["path"]) != source["fingerprint"]: + raise ValueError("The reviewed local source changed.") + if source.get("kind") == "gguf" and source.get("signature"): + from mlx_agent.gguf import file_signature + if file_signature(source["path"]) != source["signature"]: + raise ValueError("The reviewed GGUF source changed.") + for expected in source.get("dependencies", []): + if completed_fetch(expected["fetch_receipt"], expected["path"], bundle_root=True) != expected: + raise ValueError("A reviewed conversion dependency changed.") + projector = source.get("projector") + if projector: + from mlx_agent.gguf import file_signature + if (file_signature(projector["path"]) != projector["signature"] + or fingerprint(Path(projector["path"]).resolve()) != projector["fingerprint"]): + raise ValueError("The reviewed projector changed.") + + +def _owned_members(): + from mlx_agent.compute import group_members + group = os.getpid() + if os.getpgrp() != group: + raise ValueError("The conversion monitor no longer owns its isolated process group.") + return [pid for pid in group_members(group) if pid != os.getpid()] + + +def _wait_for_children(timeout=5): + deadline = time.monotonic() + timeout + while _owned_members(): + if time.monotonic() >= deadline: + return False + time.sleep(0.02) + return True + + +def _stop_owned_children(): + # The live monitor is the group leader, so this PGID cannot have been reused. + # Ignore TERM in the monitor long enough to persist the failed outcome. + if not _owned_members(): + return False + signal.signal(signal.SIGTERM, signal.SIG_IGN) + if os.getpgrp() != os.getpid(): + raise ValueError("Conversion process-group ownership changed.") + os.killpg(os.getpid(), signal.SIGTERM) + return not _wait_for_children(timeout=2) + + +def run(request_path, readiness_timeout=15): + request = read_json(request_path) + path = safe_path(request["receipt_path"]) + deadline = time.monotonic() + readiness_timeout + receipt = None + while time.monotonic() < deadline: + try: + candidate = read_json(path) + if (_matches(candidate, request) and + (not request.get("wait_for_compute_lease") or candidate.get("compute_lease_registered") is True)): + receipt = candidate + break + except (OSError, ValueError): + pass + time.sleep(0.02) + if receipt is None: + return 2 + plan = request["plan"] + worker = None + observed = False + error = None + code = None + kill_group = False + try: + _check_sources(plan) + if Path(plan["out"]).exists() or Path(plan["out"]).is_symlink(): + raise ValueError("The conversion destination became occupied.") + with receipt_lock(path): + receipt = read_json(path) + if not _matches(receipt, request): + return 2 + from mlx_agent.compute import process_identity + identity = process_identity(os.getpid()) + if os.getpgrp() != os.getpid() or not identity: + raise ValueError("The conversion monitor's isolated process group could not be established.") + receipt["execution_group"] = {"pgid": os.getpid(), "leader_identity": identity} + worker = subprocess.Popen(plan["argv"], stdin=subprocess.DEVNULL) + receipt["worker_pid"] = worker.pid + _write(path, receipt) + code = worker.wait() + observed = True + if not _wait_for_children(): + error = "Conversion descendants did not finish; the owned group was stopped and the output is incomplete." + kill_group = _stop_owned_children() + if code == 0 and error is None: + _check_sources(plan) + if code != 0: + error = "The conversion worker exited with status {0}.".format(code) + elif not safe_path(plan["out"]).is_dir(): + error = "The conversion worker exited without a model output directory." + except (OSError, ValueError, subprocess.SubprocessError) as failure: + error = str(failure) + if worker is not None and worker.poll() is None: + worker.terminate() + try: + code = worker.wait(timeout=2) + except subprocess.TimeoutExpired: + worker.kill() + code = worker.wait() + observed = True + try: + if not _wait_for_children(): + kill_group = _stop_owned_children() + except (OSError, ValueError, subprocess.SubprocessError): + pass # The retained compute group prevents another operation. + try: + with receipt_lock(path): + current = read_json(path) + if not _matches(current, request): + return 2 # A later launch owns this receipt; publish nothing into it. + if observed and code == 0 and error is None: + try: + output = safe_path(plan["out"]) + evidence = {"schema_version": "1.1", "tool": "mlx-agent.convert", + "created_at": datetime.now(timezone.utc).isoformat(), "source": plan["source"], + "q_bits": plan["q_bits"], "backend": plan.get("backend", "mlx-lm"), + "model_type": plan.get("model_type"), "recipe": plan.get("recipe"), + "launch_id": request["launch_id"], "attempt_id": request.get("attempt_id"), + "preview_hash": plan["preview_hash"], "out": str(output), + "output_fingerprint": fingerprint(output, exclude=("mlx-converter.json",))} + if plan.get("port_converter"): + evidence["port"] = plan["port_converter"] + _atomic_in_directory(output, "mlx-converter.json", (json.dumps(evidence, sort_keys=True) + "\n").encode(), 0o600) + except (OSError, ValueError) as failure: + error = "Output provenance could not be saved: " + str(failure) + current.update(completed_at=datetime.now(timezone.utc).isoformat(), exit_code=code, + exit_status="done" if observed and code == 0 and error is None else "failed", + completion_observed=observed) + if error: + current["error"] = error + _write(path, current) + return 0 if observed and code == 0 and error is None else 1 + + finally: + if kill_group and os.getpgrp() == os.getpid(): + try: + Path(request_path).unlink(missing_ok=True) + finally: + os.killpg(os.getpid(), signal.SIGKILL) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--request", required=True) + args = parser.parse_args(argv) + try: + return run(args.request) + except (OSError, ValueError, KeyError, TypeError): + return 2 + finally: + candidate = Path(args.request) + if candidate.name.startswith(".monitor-") and candidate.suffix == ".json": + try: + candidate.unlink() + except FileNotFoundError: + pass + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packages/codex/mlx-agent/src/mlx_agent/convert.py b/packages/codex/mlx-agent/src/mlx_agent/convert.py index 3be250c..2c9a719 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/convert.py +++ b/packages/codex/mlx-agent/src/mlx_agent/convert.py @@ -1,16 +1,20 @@ -"""Confirmation-gated local MLX quantization jobs.""" +"""Confirmation-gated local MLX conversion jobs.""" from __future__ import annotations import hashlib import json import re +import subprocess import sys +import uuid from datetime import datetime, timezone from pathlib import Path from .backends import ( QUANTIZED_BITS, + FLOAT_BITS, + CONVERSION_BITS, UNQUANTIZED_BITS, BackendError, backend_environment, @@ -28,7 +32,7 @@ spawn_with_env, sync_ports, ) -from .gguf import GGUF_PORT_BITS, GGUFError, describe_gguf, find_projector +from .gguf import GGUF_PORT_BITS, GGUFError, describe_gguf, find_projector, file_signature, read_gguf_header, PORT_PROJECTORS from .intake_source import validate_subfolder from .serve import ( _argv_matches, @@ -38,6 +42,7 @@ ) from .transactions import _atomic_in_directory from .wiring import _MODEL +from .source_evidence import completed_fetch, fingerprint, safe_path, read_json CONVERT_RECEIPT_SCHEMA_VERSION = "1.0" @@ -104,7 +109,8 @@ def cached_subfolder(repo, subfolder, hf_cache=None): def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backends_root_dir=None, model_type=None, - subfolder=None, hf_cache=None, source_path=None, downloads_dir=None): + subfolder=None, hf_cache=None, source_path=None, downloads_dir=None, fetch_receipt=None, + dependency_fetch_receipts=None, require_completion=False): """Render the exact conversion plan; side-effect free (a subfolder is looked up in the cache). ``model_type`` (from intake) selects a port's own converter when the port @@ -123,12 +129,17 @@ def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backend "invalid_arguments", "model_type must be a config model_type such as qwen2 or laya.", "Pass --model-type exactly as intake resolve reports it.", ) - _validate_q_bits(q_bits, (UNQUANTIZED_BITS,)) + _validate_q_bits(q_bits, FLOAT_BITS) if subfolder is not None: try: validate_subfolder(subfolder) except ValueError as error: raise ConvertError("invalid_arguments", str(error), "Pass --subfolder as the folder path inside the repository.") from error + primary, dependencies = _source_records(fetch_receipt, dependency_fetch_receipts, source_path) + if primary: + if primary["origin"]["repo"] != repo or primary["origin"].get("file") is not None or primary["origin"].get("subfolder") != subfolder: + raise ConvertError("source_mismatch", "The completed fetch does not match this repo checkpoint.", "Select the exact downloaded checkpoint.") + source_path = primary["path"] name = repo.split("/", 1)[1] + ("-" + subfolder.replace("/", "-") if subfolder else "") if out is None: out = "{0}-MLX-{1}bit".format(name, q_bits) @@ -146,7 +157,12 @@ def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backend ) hf_path = str(folder) flags = ["--hf-path", hf_path, "--mlx-path", str(out)] - if q_bits != UNQUANTIZED_BITS: + if q_bits in (2, 3, 16, 32): + require_completion = True + if backend in (None, "mlx-lm") and q_bits in FLOAT_BITS: + flags += ["--dtype", "float%d" % q_bits, "--dequantize"] + require_completion = True + elif q_bits != UNQUANTIZED_BITS: flags += ["--quantize", "--q-bits", str(q_bits)] plan = { "repo": repo, @@ -159,19 +175,13 @@ def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backend source = Path(hf_path) # Bind the reviewed plan to the local source, including config contents # and weight identities. Snapshot links may point to cache-owned blobs. - entries = [] - for item in sorted(source.rglob("*")): - if item.is_file(): - stat = item.stat() - content = hashlib.sha256(item.read_bytes()).hexdigest() if item.name.endswith(".json") and stat.st_size <= 1024 * 1024 else "" - entries.append([str(item.relative_to(source)), stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, content]) plan["source"]["path"] = str(source) - plan["source"]["fingerprint"] = hashlib.sha256(json.dumps(entries, separators=(",", ":")).encode()).hexdigest() - if q_bits == UNQUANTIZED_BITS and backend in (None, "mlx-lm"): - raise ConvertError("invalid_arguments", "This conversion has no unquantized recipe.", _bits_hint(Q_BITS_CHOICES)) + plan["source"]["fingerprint"] = local_source_fingerprint(source) + if model_type is not None: + plan["model_type"] = model_type if backend in (None, "mlx-lm"): plan["argv"] = [EXECUTABLE] + flags - return _finalize_plan(plan) + return _finish_source_plan(plan, primary, dependencies, require_completion) try: manifests = load_manifests() if manifests is None else manifests except BackendError as error: @@ -183,6 +193,11 @@ def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backend "No optional backend named {0}.".format(backend), "Run mlx-agent backend list to see the declared backends.", ) + if backend == "ace-step": + raise ConvertError( + "invalid_arguments", "ACE-Step checkpoints run as published; the ace-step backend converts nothing.", + "Generate with mlx-agent convert music --path .", + ) widths = conversion_bits(model_type, backend, manifests) if q_bits == UNQUANTIZED_BITS and q_bits not in widths: raise ConvertError("invalid_arguments", "This conversion has no unquantized recipe.", _bits_hint(widths)) @@ -193,6 +208,8 @@ def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backend "The {0} converts at {1} bits only.".format(owner, _joined(widths)), _bits_hint(widths), ) + if q_bits == UNQUANTIZED_BITS: + require_completion = True if backend == "mlx-audio" and _is_quantized_music_source(hf_path) and q_bits not in MUSIC_REQUANTIZE_BITS: raise ConvertError( "invalid_arguments", @@ -205,18 +222,26 @@ def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backend converter = port_converter(model_type, backend, manifests) recipe = recipe_for(repo, manifests) if converter else None if recipe and recipe["backend"] == backend and recipe["port"] == model_type: - flags = _recipe_flags(recipe, flags, hf_cache) + flags = _recipe_flags(recipe, flags, hf_cache, local_source=local_source if source_path is not None else None, dependencies=dependencies) plan["recipe"] = {key: recipe[key] for key in ("base", "base_revision", "lora", "lora_scale")} - requires = _required_sources(repo, model_type, manifests, hf_cache) if converter else {} + requires = _required_sources(repo, model_type, manifests, hf_cache, dependencies=dependencies if source_path is not None else None) if converter else {} for name, path in requires.items(): flags += ["--requires", "{0}={1}".format(name, path)] if requires: plan["requires"] = requires + if primary and primary.get("support"): + recorded_support = primary["support"]["downloads_dir"] + if downloads_dir is not None and safe_path(downloads_dir) != safe_path(recorded_support): + raise ConvertError("source_mismatch", "The support directory differs from the completed managed fetch.", "Use the support directory recorded by that fetch.") + downloads_dir = recorded_support + if source_path is not None and converter and port_downloads(model_type, manifests) and downloads_dir is None: + raise ConvertError("requirement_not_cached", "Managed conversion needs an explicit support directory.", "Download support into the managed source and pass its fetch receipt or --downloads-dir.") downloads = _required_downloads(repo, model_type, manifests, downloads_dir) if converter else {} for name, path in downloads.items(): flags += ["--download", "{0}={1}".format(name, path)] if downloads: plan["downloads"] = downloads + plan["downloads_dir"] = str(downloads_dir) if downloads_dir is not None else None if backend == "mlx-audio" and _is_quantized_music_source(hf_path): plan["argv"] = [str(python), str(MUSIC_REQUANTIZE_RUNNER)] + flags else: @@ -226,7 +251,7 @@ def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backend plan["ports"] = ports if converter: plan["port_converter"] = converter - return _finalize_plan(plan) + return _finish_source_plan(plan, primary, dependencies, require_completion) def _is_quantized_music_source(path): @@ -239,11 +264,15 @@ def _is_quantized_music_source(path): and isinstance(config.get("quantization"), dict) and bool(config["quantization"])) -def _required_sources(repo, model_type, manifests, hf_cache): +def _required_sources(repo, model_type, manifests, hf_cache, dependencies=None): """Cached snapshots of the other repositories a port's converter reads, each holding the files it needs.""" found = {} for name, files in sorted(port_requirements(model_type, manifests).items()): - snapshot = cached_snapshot(name, hf_cache) + if dependencies is not None: + proof = next((item for item in dependencies if item["origin"]["repo"] == name), None) + snapshot = Path(proof["path"]) if proof else None + else: + snapshot = cached_snapshot(name, hf_cache) missing = [item for item in files if snapshot is None or not (snapshot / item).is_file()] if missing: raise ConvertError( @@ -270,10 +299,17 @@ def _required_downloads(repo, model_type, manifests, downloads_dir): return found -def _recipe_flags(recipe, flags, hf_cache): +def _recipe_flags(recipe, flags, hf_cache, local_source=None, dependencies=()): """Converter flags for a recipe: the cached base snapshot and the cached LoRA, both local.""" - base = cached_snapshot(recipe["base"], hf_cache, revision=recipe["base_revision"]) - snapshot = cached_snapshot(recipe["repo"], hf_cache) + if local_source is not None: + proof = next((item for item in dependencies if item["origin"]["repo"] == recipe["base"] + and item["origin"]["revision"].lower() == recipe["base_revision"].lower() + and item["origin"].get("subfolder") is None), None) + base = Path(proof["path"]) if proof else None + snapshot = Path(local_source) + else: + base = cached_snapshot(recipe["base"], hf_cache, revision=recipe["base_revision"]) + snapshot = cached_snapshot(recipe["repo"], hf_cache) lora = snapshot / recipe["lora"] if snapshot is not None else None if base is None or lora is None or not lora.is_file(): raise ConvertError( @@ -287,6 +323,48 @@ def _recipe_flags(recipe, flags, hf_cache): return flags + ["--lora", str(lora), "--lora-scale", repr(float(recipe["lora_scale"]))] +def local_source_fingerprint(path): + source = Path(path) + entries = [] + for item in sorted(source.rglob("*")): + if item.is_file(): + info = item.stat() + content = hashlib.sha256(item.read_bytes()).hexdigest() if item.name.endswith(".json") and info.st_size <= 1024 * 1024 else "" + entries.append([str(item.relative_to(source)), info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, content]) + return hashlib.sha256(json.dumps(entries, separators=(",", ":")).encode()).hexdigest() + + +def _source_records(fetch_receipt, dependency_fetch_receipts, selected_path=None): + try: + primary = completed_fetch(fetch_receipt, selected_path) if fetch_receipt else None + dependencies = [completed_fetch(value, bundle_root=True) for value in dependency_fetch_receipts or []] + repos = [item["origin"]["repo"].casefold() for item in dependencies] + if len(dependencies) > 32 or len(set(repos)) != len(repos): + raise ValueError("Dependency fetch receipts must name distinct repositories (at most 32).") + return primary, dependencies + except (OSError, ValueError) as error: + raise ConvertError("source_evidence_invalid", str(error), "Download the exact immutable source and dependencies into fresh managed folders.") from error + + +def _finish_source_plan(plan, primary, dependencies, require_completion): + if primary: + plan["source"].update(origin=primary["origin"], fetch_receipt=primary["fetch_receipt"], fingerprint=primary["fingerprint"]) + if primary.get("support"): + plan["source"]["support"] = primary["support"] + if dependencies: + for dependency in dependencies: + if not any(value == dependency["path"] or value.endswith("=" + dependency["path"]) for value in plan["argv"]): + raise ConvertError("unused_dependency", "A dependency receipt is not used by this conversion plan.", "Pass only this converter's reviewed dependencies.") + plan["source"]["dependencies"] = dependencies + if plan.get("projector"): + plan["source"]["projector"] = dict(plan["projector"]) + if plan.get("recipe"): + plan["source"]["recipe"] = dict(plan["recipe"]) + if require_completion: + plan["require_completion"] = True + return _finalize_plan(plan) + + def _finalize_plan(plan): canonical = json.dumps(plan, sort_keys=True, separators=(",", ":")) plan["preview_hash"] = hashlib.sha256(canonical.encode("utf-8")).hexdigest() @@ -318,9 +396,13 @@ def _slugify(value, q_bits): return "{0}-{1}bit".format(slug[:96], q_bits) -def plan_gguf_convert(gguf_path, q_bits=4, out=None, runner=None, describe=describe_gguf): +def plan_gguf_convert(gguf_path, q_bits=4, out=None, runner=None, describe=describe_gguf, + projector=None, require_projector=False, fetch_receipt=None, + dependency_fetch_receipts=None, require_completion=False): """Render the exact GGUF to MLX conversion plan; pure and side-effect free.""" - _validate_q_bits(q_bits) + _validate_q_bits(q_bits, FLOAT_BITS) + if q_bits in (2, 3, 16, 32): + require_completion = True location = Path(str(gguf_path)).expanduser() if location.suffix.lower() != ".gguf": raise ConvertError( @@ -393,20 +475,53 @@ def plan_gguf_convert(gguf_path, q_bits=4, out=None, runner=None, describe=descr if draft is not None: plan["draft"] = dict(draft) port = draft["port"] if draft is not None else entry.get("port") - if port is not None and q_bits not in GGUF_PORT_BITS: + if port is not None and q_bits not in GGUF_PORT_BITS.get(port, ()): raise ConvertError( "invalid_arguments", - "The {0} port converts GGUF files at {1} bits only.".format(port, _joined(GGUF_PORT_BITS)), - _bits_hint(GGUF_PORT_BITS), + "The {0} port converts GGUF files at {1} bits only.".format(port, _joined(GGUF_PORT_BITS.get(port, ()))), + _bits_hint(GGUF_PORT_BITS.get(port, ())), ) if port is not None: plan["port_converter"] = port plan["argv"].extend(["--port", port]) - projector = find_projector(location, port) - if projector is not None: - plan["projector"] = projector - plan["argv"].extend(["--projector", projector["path"]]) - return _finalize_plan(plan) + selected_projector = _explicit_projector(location, port, projector) if projector else find_projector(location, port) + if selected_projector is not None: + selected_projector["signature"] = file_signature(selected_projector["path"]) + selected_projector["fingerprint"] = fingerprint(Path(selected_projector["path"]).resolve()) + plan["projector"] = selected_projector + plan["argv"].extend(["--projector", selected_projector["path"]]) + elif projector: + raise ConvertError("invalid_projector", "This GGUF converter does not support a projector.", "Select a supported vision model.") + if require_projector: + if "projector" not in plan: + raise ConvertError("projector_required", "The reviewed vision projector is missing or ambiguous.", "Download and select the exact matching projector before updating.") + plan["require_projector"] = True + primary, dependencies = _source_records(fetch_receipt, dependency_fetch_receipts, str(location)) + if primary and plan.get("projector"): + proof = read_json(primary["fetch_receipt"]) + root = safe_path(proof["local_dir"]) + target = safe_path(plan["projector"]["path"]) + relative = str(target.relative_to(root)) if target.is_relative_to(root) else None + if relative not in primary["origin"].get("additional_files", []): + raise ConvertError("source_mismatch", "The projector is outside the reviewed download file set.", "Include it with --additional-file at the same immutable revision.") + plan["projector"]["origin"] = dict(primary["origin"], file=relative, additional_files=[]) + plan["projector"]["fetch_receipt"] = primary["fetch_receipt"] + return _finish_source_plan(plan, primary, dependencies, require_completion) + + +def _explicit_projector(model, port, projector): + target = safe_path(projector) + try: + source = read_gguf_header(model)["metadata"] + candidate = read_gguf_header(target)["metadata"] + width = source.get("{0}.embedding_length".format(source.get("general.architecture"))) + if (target == Path(model).resolve() or candidate.get("general.architecture") != "clip" + or candidate.get("clip.projector_type") != PORT_PROJECTORS.get(port) + or candidate.get("clip.vision.projection_dim") != width): + raise ValueError("The selected projector does not match this model's vision type and embedding width.") + except (GGUFError, OSError, ValueError) as error: + raise ConvertError("invalid_projector", str(error), "Select the matching projector from the reviewed download.") from error + return {"path": str(target), "name": target.name, "bytes": target.stat().st_size, "signature": file_signature(target), "fingerprint": fingerprint(target.resolve())} def _slug(value): @@ -434,9 +549,15 @@ def _read_receipt(path, kind=CONVERT_RECEIPT_KIND): return value -def _write_receipt(root, receipt, filename): - content = (json.dumps(receipt, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") - _atomic_in_directory(root, filename, content, 0o600) +def _write_receipt(root, receipt, filename, expected=None): + from .conversion_monitor import receipt_lock + path = Path(root) / filename + with receipt_lock(path): + if expected is not None and _read_receipt(path) != expected: + return False + content = (json.dumps(receipt, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") + _atomic_in_directory(root, filename, content, 0o600) + return True def _source_kind(value): @@ -454,7 +575,7 @@ def _default_module_present(names): def start_convert(plan, receipts_dir=None, confirm=False, preview_hash=None, which=None, model_present=None, spawn=None, now=_utc_now, - pid_alive=None, module_present=None): + pid_alive=None, module_present=None, wait_for_compute_lease=False, attempt_id=None): """Execute a reviewed conversion plan; the only mutating entry point.""" from .serve import _default_spawn, _default_which @@ -476,6 +597,9 @@ def start_convert(plan, receipts_dir=None, confirm=False, preview_hash=None, "The supplied preview hash does not match this convert plan.", "Re-run convert start without --confirm and review the fresh plan.", ) + if attempt_id is not None and (not plan.get("require_completion") or not isinstance(attempt_id, str) + or re.fullmatch(r"[0-9a-f]{32}", attempt_id) is None): + raise ConvertError("invalid_arguments", "A conversion attempt requires --require-completion and a 32-character hexadecimal token.", "Use the durable queue to create a new attempt.") backend = plan.get("backend") if backend: manifest = load_manifests().get(backend) @@ -531,6 +655,8 @@ def start_convert(plan, receipts_dir=None, confirm=False, preview_hash=None, ) for receipt_path in sorted(root.glob("*.json")) if root.is_dir() else []: existing = _read_receipt(receipt_path) + if attempt_id is not None and existing and existing.get("attempt_id") == attempt_id: + raise ConvertError("attempt_exists", "This conversion attempt already has a receipt.", "Inspect its existing receipt before retrying with a new attempt.") if existing is None or existing.get("completed_at"): continue if pid_alive(existing["pid"]): @@ -546,7 +672,11 @@ def start_convert(plan, receipts_dir=None, confirm=False, preview_hash=None, except BackendError as error: raise ConvertError(error.code, str(error), error.remediation) from error root.mkdir(parents=True, exist_ok=True) - slug = _slug(plan) + launch_id = uuid.uuid4().hex if plan.get("require_completion") else None + slug = _slug(plan) + ("-" + launch_id if launch_id else "") + receipt_path = root / (slug + ".json") + if receipt_path.is_symlink() or (launch_id and receipt_path.exists()): + raise ConvertError("receipt_exists", "This conversion launch already has a receipt.", "Inspect conversion status before retrying.") log_path = root / "{0}.log".format(slug) if spawn is None: environment = backend_environment() @@ -557,7 +687,17 @@ def spawn(argv, log_path): return spawn_with_env(argv, log_path, environment) spawn = spawn or _default_spawn - pid = spawn(plan["argv"], str(log_path)) + started_at = now() + monitor_argv = None + if launch_id: + request_path = root / (".monitor-" + launch_id + ".json") + request = {"launch_id": launch_id, "started_at": started_at, + "attempt_id": attempt_id, + "wait_for_compute_lease": wait_for_compute_lease, + "receipt_path": str(receipt_path.absolute()), "plan": plan} + _atomic_in_directory(root, request_path.name, (json.dumps(request, sort_keys=True) + "\n").encode(), 0o600) + monitor_argv = [sys.executable, str(Path(__file__).with_name("conversion_monitor.py")), "--request", str(request_path.absolute())] + pid = spawn(monitor_argv or plan["argv"], str(log_path)) receipt = { "schema_version": CONVERT_RECEIPT_SCHEMA_VERSION, "kind": CONVERT_RECEIPT_KIND, @@ -569,15 +709,40 @@ def spawn(argv, log_path): "argv": list(plan["argv"]), "pid": pid, "log_path": str(log_path), - "started_at": now(), + "started_at": started_at, "preview_hash": plan["preview_hash"], "completed_at": None, "exit_status": None, } if backend: receipt["backend"] = backend + if plan.get("model_type"): + receipt["model_type"] = plan["model_type"] + if plan.get("downloads_dir"): + receipt["downloads_dir"] = plan["downloads_dir"] + if launch_id: + receipt.update(require_completion=True, launch_id=launch_id, monitor_argv=monitor_argv, + wait_for_compute_lease=wait_for_compute_lease, compute_lease_registered=False, + completion_observed=False, exit_code=None) + if attempt_id is not None: + receipt["attempt_id"] = attempt_id _write_receipt(root, receipt, "{0}.json".format(slug)) - return {"status": "started", "receipt": receipt} + result = {"status": "started", "receipt": receipt} + if launch_id: + result["receipt_path"] = str(receipt_path.absolute()) + return result + + +def register_monitor_lease(path, expected): + from .conversion_monitor import receipt_lock + with receipt_lock(path): + current = read_json(path) + keys = ("launch_id", "attempt_id", "pid", "source", "argv", "preview_hash", "out", "started_at") + if any(current.get(key) != expected.get(key) for key in keys) or not current.get("wait_for_compute_lease"): + raise ConvertError("receipt_changed", "The conversion receipt changed before compute registration.", "Inspect conversion status before retrying.") + current["compute_lease_registered"] = True + _atomic_in_directory(Path(path).parent, Path(path).name, (json.dumps(current, sort_keys=True) + "\n").encode(), 0o600) + expected.update(current) def load_receipts(receipts_dir=None): @@ -593,6 +758,36 @@ def load_receipts(receipts_dir=None): return receipts +def _processes_quiescent(receipt): + """Prove the recorded isolated group has no live members without signalling.""" + from .compute import group_members + group = receipt.get("execution_group") + if (not receipt.get("require_completion") or not isinstance(group, dict) + or type(group.get("pgid")) is not int or group["pgid"] != receipt["pid"] + or not isinstance(group.get("leader_identity"), str) or not group["leader_identity"]): + return False + try: + return not group_members(group["pgid"]) + except (OSError, ValueError, subprocess.SubprocessError): + return False + + +def _check_completed_output(receipt): + if receipt.get("completion_observed") is not True or receipt.get("exit_code") != 0: + raise ValueError("The conversion has no observed successful worker completion.") + output = safe_path(receipt["out"]) + evidence = read_json(output / "mlx-converter.json") + expected = {"schema_version": "1.1", "tool": "mlx-agent.convert", "source": receipt["source"], + "q_bits": receipt["q_bits"], "backend": receipt.get("backend", "mlx-lm"), + "model_type": receipt.get("model_type"), "preview_hash": receipt.get("preview_hash"), + "launch_id": receipt["launch_id"], "attempt_id": receipt.get("attempt_id"), + "out": str(output)} + if any(evidence.get(key) != value for key, value in expected.items()): + raise ValueError("The output provenance does not match its completed conversion receipt.") + if evidence.get("output_fingerprint") != fingerprint(output, exclude=("mlx-converter.json",)): + raise ValueError("The converted output changed after observed completion.") + + def status_convert(receipts_dir=None, pid_alive=_pid_alive, pid_command=_pid_command, now=_utc_now): """Cross-check convert receipts against live processes; marks exits once.""" @@ -607,7 +802,12 @@ def status_convert(receipts_dir=None, pid_alive=_pid_alive, pid_command=_pid_com entry = { "receipt": str(path), "repo": receipt["repo"], - "source": _source_kind(receipt), + "source": _source_kind(receipt), "source_details": dict(receipt.get("source") or {}), + "preview_hash": receipt.get("preview_hash"), "backend": receipt.get("backend", "mlx-lm"), + "model_type": receipt.get("model_type"), "downloads_dir": receipt.get("downloads_dir"), "completion_observed": receipt.get("completion_observed", False), + "exit_code": receipt.get("exit_code"), "exit_status": receipt.get("exit_status"), + "attempt_id": receipt.get("attempt_id"), + "processes_quiescent": _processes_quiescent(receipt), "q_bits": receipt["q_bits"], "out": receipt["out"], "pid": receipt["pid"], @@ -617,21 +817,37 @@ def status_convert(receipts_dir=None, pid_alive=_pid_alive, pid_command=_pid_com } if receipt.get("completed_at"): entry["state"] = receipt.get("exit_status") or "done" + if receipt.get("require_completion") and entry["state"] == "done": + try: + _check_completed_output(receipt) + except (OSError, ValueError, KeyError, TypeError) as error: + entry["state"] = "failed" + entry["error"] = str(error) entries.append(entry) continue if pid_alive(receipt["pid"]): command = pid_command(receipt["pid"]) entry["state"] = "running" if _argv_matches( - {"argv": receipt["argv"], "port": None, "repo": receipt["repo"]}, + {"argv": receipt.get("monitor_argv") or receipt["argv"], "port": None, + "repo": receipt["monitor_argv"][-1] if receipt.get("monitor_argv") else receipt["repo"]}, command, require_port=False, ) else "unknown" entries.append(entry) continue + if receipt.get("require_completion"): + entry["state"] = "failed" + entry["error"] = "The conversion monitor exited without observed worker completion." + entries.append(entry) + continue exit_status = "done" if Path(receipt["out"]).exists() else "failed" + original = dict(receipt) receipt["completed_at"] = now() receipt["exit_status"] = exit_status - _write_receipt(root, receipt, "{0}.json".format(_slug(receipt))) + if not _write_receipt(root, receipt, "{0}.json".format(_slug(receipt)), expected=original): + entry["state"] = "unknown" + entries.append(entry) + continue entry["state"] = exit_status entry["completed_at"] = receipt["completed_at"] entries.append(entry) diff --git a/packages/codex/mlx-agent/src/mlx_agent/convert_queue.py b/packages/codex/mlx-agent/src/mlx_agent/convert_queue.py index 5094975..b155912 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/convert_queue.py +++ b/packages/codex/mlx-agent/src/mlx_agent/convert_queue.py @@ -5,15 +5,17 @@ import json import itertools import os +import re import threading +import uuid from pathlib import Path from . import queue_bridge as bridge from .atomicio import write_text_atomic -from .backends import QUANTIZED_BITS +from .backends import CONVERSION_BITS -QUEUE_SCHEMA_VERSION = "1.1" +QUEUE_SCHEMA_VERSION = "1.2" LEGACY_QUEUE_SCHEMA_VERSION = "1.0" QUEUE_FILENAME = "convert-queue.json" ITEM_STATES = ("queued", "starting", "failed") @@ -22,6 +24,8 @@ "hf_cache", "label", "state", "failure", } LEGACY_QUEUE_ITEM_KEYS = QUEUE_ITEM_KEYS - {"failure"} +PREPARATION_FIELDS = {"backend", "model_type", "subfolder", "source_path", "projector", "require_projector", + "fetch_receipt", "dependency_fetch_receipts", "require_completion", "downloads_dir"} FAILURE_KEYS = {"code", "message", "remediation"} @@ -81,8 +85,21 @@ def _optional_string(value): def _validate_item(item, legacy=False): expected_keys = LEGACY_QUEUE_ITEM_KEYS if legacy else QUEUE_ITEM_KEYS - if not isinstance(item, dict) or set(item) != expected_keys: + if (not isinstance(item, dict) or not expected_keys <= set(item) + or set(item) - (expected_keys | PREPARATION_FIELDS | {"attempt_id"})): raise ValueError("queue item fields do not match schema") + if "attempt_id" in item and (item.get("require_completion") is not True + or not isinstance(item["attempt_id"], str) or re.fullmatch(r"[0-9a-f]{32}", item["attempt_id"]) is None): + raise ValueError("queue item attempt_id is invalid") + for field in PREPARATION_FIELDS - {"require_projector", "require_completion", "dependency_fetch_receipts"}: + if not _optional_string(item.get(field)): + raise ValueError("queue item {0} is invalid".format(field)) + for field in ("require_projector", "require_completion"): + if field in item and type(item[field]) is not bool: + raise ValueError("queue item {0} is invalid".format(field)) + dependencies = item.get("dependency_fetch_receipts", []) + if not isinstance(dependencies, list) or len(dependencies) > 32 or any(not isinstance(value, str) or not value for value in dependencies): + raise ValueError("queue item dependency fetch receipts are invalid") item_id = item["id"] if ( not isinstance(item_id, str) @@ -94,7 +111,7 @@ def _validate_item(item, legacy=False): raise ValueError("queue item kind is invalid") if not isinstance(item["preview_hash"], str) or not item["preview_hash"]: raise ValueError("queue item preview_hash is invalid") - if isinstance(item["q_bits"], bool) or item["q_bits"] not in QUANTIZED_BITS: + if isinstance(item["q_bits"], bool) or item["q_bits"] not in CONVERSION_BITS: raise ValueError("queue item q_bits is invalid") for field in ("out", "path", "repo", "hf_cache"): if not _optional_string(item[field]): @@ -128,7 +145,7 @@ def _validated_items(payload): if set(payload) != {"schema_version", "items"}: raise ValueError("queue state fields do not match schema") version = payload["schema_version"] - if version not in (LEGACY_QUEUE_SCHEMA_VERSION, QUEUE_SCHEMA_VERSION): + if version not in (LEGACY_QUEUE_SCHEMA_VERSION, "1.1", QUEUE_SCHEMA_VERSION): raise ValueError("queue schema version is unsupported") if not isinstance(payload["items"], list): raise ValueError("queue items must be a list") @@ -248,7 +265,9 @@ def __init__(self, path=None, store=None): self.last_error = None def enqueue(self, kind, preview_hash, q_bits, out=None, path=None, repo=None, - label=None, hf_cache=None): + label=None, hf_cache=None, backend=None, model_type=None, subfolder=None, + source_path=None, projector=None, require_projector=False, fetch_receipt=None, + dependency_fetch_receipts=None, require_completion=False, downloads_dir=None): if kind not in ("gguf", "repo"): raise ValueError("kind must be gguf or repo") if not isinstance(preview_hash, str) or not preview_hash: @@ -266,6 +285,12 @@ def enqueue(self, kind, preview_hash, q_bits, out=None, path=None, repo=None, "state": "queued", "failure": None, } + if q_bits in (2, 3, 16, 32): + require_completion = True + additions = dict(backend=backend, model_type=model_type, subfolder=subfolder, source_path=source_path, + projector=projector, require_projector=require_projector, fetch_receipt=fetch_receipt, + dependency_fetch_receipts=dependency_fetch_receipts, require_completion=require_completion, downloads_dir=downloads_dir) + item.update({key: value for key, value in additions.items() if value not in (None, False, [])}) with self._lock: self._publish_locked(self._items + [item]) return dict(item) @@ -357,6 +382,7 @@ def retry(self, item_id): "Wait for the current operation or choose a failed item.", ) retried = dict(item, state="queued", failure=None) + retried.pop("attempt_id", None) candidate = self._items[:index] + self._items[index + 1:] + [retried] self._publish_locked(candidate) return dict(retried) @@ -424,7 +450,7 @@ def _try_start_next(self, agent_path, runner=None): if item["state"] == "starting": try: - receipts = bridge.read_convert_receipts(entries) + receipts = bridge.read_convert_receipts(entries, include_path=True) except bridge.BridgeError as error: payload = { "status": "waiting_recovery", @@ -433,12 +459,16 @@ def _try_start_next(self, agent_path, runner=None): } self.last_error = payload return payload - if any(self._receipt_matches(item, receipt) for receipt in receipts): + matched = next((receipt for receipt in receipts if self._receipt_matches(item, receipt)), None) + if matched is not None: with self._lock: self._remove_locked(item["id"]) self.last_error = None - return {"status": "recovered", "item": item} + return {"status": "recovered", "item": item, "result": { + "status": "recovered", "receipt_path": matched["_receipt_path"], + "receipt": {key: value for key, value in matched.items() if key != "_receipt_path"}}} queued = dict(item, state="queued", failure=None) + queued.pop("attempt_id", None) with self._lock: if not self._replace_locked(item["id"], queued): return None @@ -448,6 +478,8 @@ def _try_start_next(self, agent_path, runner=None): return None starting = dict(item, state="starting", failure=None) + if starting.get("require_completion"): + starting["attempt_id"] = uuid.uuid4().hex with self._lock: if not self._replace_locked(item["id"], starting): return None @@ -460,6 +492,8 @@ def _try_start_next(self, agent_path, runner=None): q_bits=starting["q_bits"], out=starting.get("out"), runner=runner, + **{key: starting[key] for key in PREPARATION_FIELDS if key in starting}, + **({"attempt_id": starting["attempt_id"]} if "attempt_id" in starting else {}), ) else: result = bridge.start_repo( @@ -470,6 +504,8 @@ def _try_start_next(self, agent_path, runner=None): out=starting.get("out"), hf_cache=starting.get("hf_cache"), runner=runner, + **{key: starting[key] for key in PREPARATION_FIELDS if key in starting}, + **({"attempt_id": starting["attempt_id"]} if "attempt_id" in starting else {}), ) try: with self._lock: @@ -493,6 +529,7 @@ def _try_start_next(self, agent_path, runner=None): if error.code in ("job_in_progress", "compute_busy"): with self._lock: queued = dict(starting, state="queued", failure=None) + queued.pop("attempt_id", None) self._replace_locked(starting["id"], queued) return None failure = error.to_dict() @@ -519,15 +556,24 @@ def _try_start_next(self, agent_path, runner=None): def _receipt_matches(item, receipt): if not isinstance(receipt, dict): return False + if item.get("require_completion") and (item.get("state") != "starting" + or not item.get("attempt_id") or receipt.get("attempt_id") != item["attempt_id"]): + return False if receipt.get("preview_hash") != item["preview_hash"]: return False if item.get("out") is not None and receipt.get("out") != item.get("out"): return False if receipt.get("q_bits") != item["q_bits"]: return False + for field in ("backend", "model_type", "require_completion", "downloads_dir"): + if field in item and receipt.get(field, "mlx-lm" if field == "backend" else None) != item[field]: + return False source = receipt.get("source") if not isinstance(source, dict): return False + for field in ("source_path", "fetch_receipt"): + if item.get(field) is not None and source.get("path" if field == "source_path" else field) != item[field]: + return False if item["kind"] == "gguf": return source.get("path") == item["path"] return source.get("repo") == item["repo"] diff --git a/packages/codex/mlx-agent/src/mlx_agent/decide_runner.py b/packages/codex/mlx-agent/src/mlx_agent/decide_runner.py index 08fda0a..daf32e0 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/decide_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/decide_runner.py @@ -6,6 +6,11 @@ import sys import time +if __package__: + from .runner_model_cache import load_model +else: + from runner_model_cache import load_model + def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) @@ -18,7 +23,7 @@ def main(argv=None): request = json.load(handle) port = importlib.import_module(arguments.module) started = time.time() - model, tokenizer = port.load(arguments.model) + model, tokenizer = load_model(port.load, arguments.model) loaded = time.time() result = port.predict(model, tokenizer, request["state"], request["questions"]) result["seconds"] = round(time.time() - loaded, 3) diff --git a/packages/codex/mlx-agent/src/mlx_agent/describe_runner.py b/packages/codex/mlx-agent/src/mlx_agent/describe_runner.py index ef3ee5b..e18c99c 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/describe_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/describe_runner.py @@ -5,6 +5,11 @@ import sys import time +if __package__: + from .runner_model_cache import load_model +else: + from runner_model_cache import load_model + def _fit(image, max_pixels): """Shrink a PIL image, keeping its aspect ratio, until it holds at most max_pixels pixels.""" @@ -58,7 +63,7 @@ def main(argv=None): from mlx_vlm.prompt_utils import MODEL_CONFIG started = time.time() - model, processor = load(arguments.model) + model, processor = load_model(load, arguments.model) load_seconds = time.time() - started config = model.config model_type = str(getattr(config, "model_type", None) or "") diff --git a/packages/codex/mlx-agent/src/mlx_agent/embed.py b/packages/codex/mlx-agent/src/mlx_agent/embed.py new file mode 100644 index 0000000..aaccb0e --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/embed.py @@ -0,0 +1,74 @@ +"""Text embeddings from an existing local checkpoint in the pinned embedding backend.""" +import json +import math +from pathlib import Path +import subprocess + +from .backends import backend_python, is_installed, load_manifests, load_registries, lookup, normalize_type +from .inference_runner import InferenceError, RunnerContract, invoke + +TEXT_MODELS = frozenset(('bert', 'modernbert', 'qwen3', 'xlm_roberta', 'lfm2', 'llama_bidirec', 'gemma3_text')) + + +class EmbedError(InferenceError): + pass + + +def validate_parameters(parameters): + texts = parameters.get('input') + length = parameters.get('max_length', 512) + if (set(parameters) - {'input', 'max_length'} or not isinstance(texts, list) or not 1 <= len(texts) <= 128 + or any(not isinstance(text, str) or not text.strip() or len(text) > 32768 for text in texts) + or type(length) is not int or not 1 <= length <= 8192): + raise EmbedError('invalid_request', 'Embedding input needs 1–128 nonempty texts and max_length from 1 to 8192.', + 'Provide a bounded input array of text strings.') + return parameters + + +def validate_vectors(vectors, count): + if not isinstance(vectors, list) or len(vectors) != count or not vectors or not isinstance(vectors[0], list) or not vectors[0]: + raise ValueError('The embedding batch shape is invalid.') + width = len(vectors[0]) + if any(not isinstance(row, list) or len(row) != width or + any(type(value) not in (int, float) or not math.isfinite(value) for value in row) for row in vectors): + raise ValueError('Embeddings must be a finite rectangular matrix.') + return [[float(value) for value in row] for row in vectors] + + +def plan_embed(model_path, request_path, manifests=None, registries=None, root=None): + model, request = Path(model_path), Path(request_path) + try: + if not model.is_absolute() or not model.is_dir(): + raise ValueError('An existing absolute local model directory is required.') + config = json.loads((model / 'config.json').read_text()) + parameters = validate_parameters(json.loads(request.read_text())) + if normalize_type(config.get('model_type')) not in TEXT_MODELS: + raise ValueError('No vetted text embedding adapter implements this architecture.') + except (OSError, ValueError, AttributeError) as error: + raise EmbedError('model_unreadable', str(error), 'Select a supported local text embedding checkpoint.') from error + manifests = load_manifests() if manifests is None else manifests + registries = load_registries(manifests, root) if registries is None else registries + if not any(hit['category'] == 'embedding' for hit in lookup(config.get('model_type'), manifests, registries)): + raise EmbedError('not_embedding_model', 'The local architecture has no embedding adapter.', 'Select a supported text embedding model.') + manifest = manifests['mlx-embeddings'] + if not is_installed(manifest, root): + raise EmbedError('backend_not_installed', 'The embedding backend is not installed.', 'Install mlx-embeddings first.') + return {'backend': manifest['id'], 'model': str(model), 'request': str(request), 'count': len(parameters['input']), + 'argv': [str(backend_python(manifest, root)), str(Path(__file__).with_name('embed_runner.py')), + '--model', str(model), '--request', str(request)]} + + +CONTRACT = RunnerContract(verb='embed', error=EmbedError, + accept=lambda value, plan: isinstance(value.get('embeddings'), list), action='embed the text', + remediation='Check the local embedding checkpoint and backend.', activity='Text embedding', + timeout_remediation='Use a smaller batch.', environment={'HF_HUB_OFFLINE': '1', 'TRANSFORMERS_OFFLINE': '1'}) + + +def run_embed(plan, manifests=None, root=None, timeout=300, runner=subprocess.run): + result = invoke(plan, CONTRACT, manifests, root, timeout, runner) + try: + vectors = validate_vectors(result['embeddings'], plan['count']) + except ValueError as error: + raise EmbedError('invalid_embeddings', str(error), 'Check the embedding adapter output.') from error + return {'schema': 'embed/1', 'backend': plan['backend'], 'model': plan['model'], 'embeddings': vectors, + 'dimensions': len(vectors[0]), 'load_seconds': result.get('load_seconds'), 'seconds': result.get('seconds')} diff --git a/packages/codex/mlx-agent/src/mlx_agent/embed_runner.py b/packages/codex/mlx-agent/src/mlx_agent/embed_runner.py new file mode 100644 index 0000000..16fdceb --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/embed_runner.py @@ -0,0 +1,37 @@ +"""Generate text embeddings using the backend's trained pooling and normalization.""" +import argparse +import json +import os +from pathlib import Path +import time + +if __package__: + from .runner_model_cache import load_model +else: + from runner_model_cache import load_model + + +def main(argv=None): + parser = argparse.ArgumentParser() + parser.add_argument('--model', required=True) + parser.add_argument('--request', required=True) + args = parser.parse_args(argv) + model_path = Path(args.model) + if not model_path.is_absolute() or not model_path.is_dir(): + raise ValueError('Embedding inference requires existing local weights.') + os.environ.update(HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', HF_DATASETS_OFFLINE='1') + from mlx_embeddings import load, generate + parameters = json.loads(Path(args.request).read_text()) + started = time.perf_counter() + model, tokenizer = load_model(load, str(model_path), tokenizer_config={'local_files_only': True, 'trust_remote_code': False}) + loaded = time.perf_counter() + result = generate(model, tokenizer, texts=parameters['input'], max_length=parameters.get('max_length', 512)) + # Models supply their own trained pooling; an unsupported output is refused. + vectors = result.text_embeds.tolist() + print(json.dumps({'embeddings': vectors, 'load_seconds': loaded - started, + 'seconds': time.perf_counter() - loaded}, allow_nan=False), flush=True) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/packages/codex/mlx-agent/src/mlx_agent/fetch_runner.py b/packages/codex/mlx-agent/src/mlx_agent/fetch_runner.py index 187a5f0..42e23fa 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/fetch_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/fetch_runner.py @@ -9,6 +9,11 @@ from datetime import datetime, timezone from pathlib import Path +if __package__: + from .source_evidence import identities, safe_path +else: + from source_evidence import identities, safe_path + def _snapshot_download(**kwargs): from huggingface_hub import snapshot_download @@ -57,6 +62,13 @@ def main(argv=None, download=None, opener=None): parser.add_argument("--repo", required=True) parser.add_argument("--revision", default="main") parser.add_argument("--file", default=None) + parser.add_argument("--additional-file", action="append", default=[]) + parser.add_argument("--source-subfolder") + parser.add_argument("--fresh-destination", action="store_true") + parser.add_argument("--capture-identities", action="store_true") + parser.add_argument("--proof-token") + parser.add_argument("--preview-hash") + parser.add_argument("--started-at") parser.add_argument("--ignore", action="append", default=None) parser.add_argument("--allow", action="append", default=None) parser.add_argument("--base-repo", default=None, help="also download this pinned base snapshot first") @@ -73,7 +85,7 @@ def main(argv=None, download=None, opener=None): arguments = parser.parse_args(argv) kwargs = {"repo_id": arguments.repo, "revision": arguments.revision} if arguments.file: - kwargs["allow_patterns"] = [arguments.file] + kwargs["allow_patterns"] = [arguments.file] + sorted(arguments.additional_file) if arguments.allow: kwargs["allow_patterns"] = arguments.allow if arguments.ignore: @@ -83,6 +95,13 @@ def main(argv=None, download=None, opener=None): if arguments.local_dir: kwargs["local_dir"] = arguments.local_dir try: + if arguments.fresh_destination: + if not arguments.local_dir or arguments.cache_dir or not arguments.proof_token or arguments.base_repo or arguments.require: + raise ValueError("A managed download needs a new local destination and receipt identity.") + target = safe_path(arguments.local_dir) + target.parent.mkdir(parents=True, exist_ok=True) + safe_path(target) + target.mkdir(mode=0o700) if arguments.base_repo: base = {"repo_id": arguments.base_repo, "revision": arguments.base_revision or "main"} if arguments.base_ignore: @@ -101,17 +120,39 @@ def main(argv=None, download=None, opener=None): extra["cache_dir"] = arguments.cache_dir print("downloading required {0}".format(repo), flush=True) (download or _snapshot_download)(**extra) - for item in arguments.download: - sha256, size, url = item.split("=", 2) - name = url.rsplit("/", 1)[-1] - print("downloading {0}".format(url), flush=True) - fetch_file(url, sha256, int(size), Path(arguments.downloads_dir) / sha256 / name, opener) + def download_support(): + for item in arguments.download: + sha256, size, url = item.split("=", 2) + name = url.rsplit("/", 1)[-1] + print("downloading {0}".format(url), flush=True) + fetch_file(url, sha256, int(size), Path(arguments.downloads_dir) / sha256 / name, opener) + if not arguments.fresh_destination: + download_support() path = (download or _snapshot_download)(**kwargs) + if arguments.fresh_destination and arguments.download: + support = safe_path(arguments.downloads_dir) + if support == target or not support.is_relative_to(target) or support.exists(): + raise ValueError("The managed support destination is outside the reviewed source or already occupied.") + download_support() result, code = {"exit_status": "done", "path": str(path)}, 0 + if arguments.capture_identities: + result["files"] = identities(path) + selected = [arguments.file] + sorted(arguments.additional_file) if arguments.file else [] + names = {item["path"] for item in result["files"]} + if selected and not set(selected) <= names: + raise ValueError("The managed download did not contain every reviewed file.") print("downloaded {0} to {1}".format(arguments.repo, path), flush=True) except Exception as error: # noqa: BLE001 - recorded in the marker and the log result, code = {"exit_status": "failed", "error": str(error)}, 1 print("download failed: {0}".format(error), flush=True) + if arguments.proof_token: + result.update(repo=arguments.repo, revision=arguments.revision, file=arguments.file, + subfolder=arguments.source_subfolder, additional_files=sorted(arguments.additional_file), local_dir=arguments.local_dir, + preview_hash=arguments.preview_hash, proof_token=arguments.proof_token, started_at=arguments.started_at, + downloads_dir=arguments.downloads_dir, downloads=[{"sha256": item.split("=", 2)[0], "size": int(item.split("=", 2)[1]), "url": item.split("=", 2)[2]} for item in arguments.download]) + # --allow PREFIX/* represents an explicitly selected checkpoint. + if arguments.allow and len(arguments.allow) == 1 and arguments.allow[0].endswith("/*"): + result["subfolder"] = arguments.allow[0][:-2] result["finished_at"] = datetime.now(timezone.utc).isoformat() Path(arguments.marker).write_text(json.dumps(result, sort_keys=True) + "\n", encoding="utf-8") return code diff --git a/packages/codex/mlx-agent/src/mlx_agent/fetch_storage.py b/packages/codex/mlx-agent/src/mlx_agent/fetch_storage.py new file mode 100644 index 0000000..88fea58 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/fetch_storage.py @@ -0,0 +1,190 @@ +"""Per-source admission for immutable managed downloads. + +The index locates receipts; it is never evidence that model files are complete. +Every reuse revalidates the original receipt and its current source identities. +""" +from contextlib import contextmanager +import fcntl +import hashlib +import json +import os +from pathlib import Path +import stat +import unicodedata + +from .atomicio import write_text_atomic +from .source_evidence import completed_fetch, read_json, safe_path +from .serve import _pid_alive + + +class StorageError(ValueError): + def __init__(self, code, message): + super().__init__(message) + self.code = code + + +def default_root(): + state = os.environ.get("XDG_STATE_HOME") + base = Path(state).expanduser() if state else Path.home() / ".local/state" + if not base.is_absolute(): + raise ValueError("XDG_STATE_HOME must be absolute.") + return base / "mlx-agent/model-storage" + + +def _digest(value): + return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + +def identity(plan): + # Companions and fetch recipes belong to a selection, rather than creating + # another copy of the same primary file under a different key. + return {"repo": plan["repo"].casefold(), "revision": plan["revision"].lower(), + "file": plan["file"], "subfolder": plan.get("subfolder")} + + +def selection(plan): + return {key: plan.get(key) or None for key in ( + "additional_files", "allow_patterns", "ignore_patterns", "base", "requires", "downloads")} + + +def _root(value, create=False): + root = safe_path(value) + if create: + root.mkdir(mode=0o700, parents=True, exist_ok=True) + if root.exists(): + info = root.stat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o022: + raise ValueError("The storage index must be an owned directory without shared write access.") + return root + + +def _entry(root, key): + path = root / (key + ".json") + try: + return read_json(path) + except FileNotFoundError: + # A dangling link is an invalid index, never a missing registration. + if path.is_symlink(): + raise ValueError("The storage index cannot contain symbolic links.") + return None + + +def _sources(entry): + if entry is None: + return {} + if entry.get("schema") != 1 or not isinstance(entry.get("sources"), dict): + raise ValueError("The storage index is incomplete or invalid.") + return entry["sources"] + + +def _overlap(source, files, other): + previous = other["source"] + if (source["repo"], source["revision"]) != (previous["repo"], previous["revision"]): + return False + if source["file"] and previous["file"]: + return bool({source["file"], *(files["additional_files"] or [])} & + {previous["file"], *(other["selection"]["additional_files"] or [])}) + # A snapshot or checkpoint selection can include any file below its prefix. + prefix = (source.get("subfolder") or "") + "/" + prior = (previous.get("subfolder") or "") + "/" + if source["file"]: + return any(not previous.get("subfolder") or name.startswith(prior) + for name in [source["file"], *(files["additional_files"] or [])]) + if previous["file"]: + return any(not source.get("subfolder") or name.startswith(prefix) + for name in [previous["file"], *(other["selection"]["additional_files"] or [])]) + return prefix.startswith(prior) or prior.startswith(prefix) or prefix == "/" or prior == "/" + + +def inspect(plan, root): + root = _root(root) + source, files = identity(plan), selection(plan) + key, source_key = "sources", _digest(source) + index = _entry(root, key) + sources = _sources(index) + result = {"root": str(root), "key": key, "source_key": source_key, "generation": _digest(index), "mode": "download"} + entry = sources.get(source_key) + if entry is None: + destination = str(safe_path(plan["local_dir"])) + for other in sources.values(): + occupied = str(safe_path(other["directory"])) + left, right = (unicodedata.normalize("NFC", value).casefold().rstrip("/") for value in (destination, occupied)) + if left == right or left.startswith(right + "/") or right.startswith(left + "/"): + raise StorageError("storage_destination_conflict", "The destination overlaps another registered source; choose a separate model directory.") + if any(_overlap(source, files, other) for other in sources.values()): + raise StorageError("storage_selection_conflict", "An overlapping file or snapshot selection is already registered at this revision; use its existing source.") + return result + if entry.get("source") != source or not isinstance(entry.get("receipt"), str): + raise ValueError("The storage index entry is incomplete or invalid.") + if entry.get("selection") != files: + raise StorageError("storage_selection_conflict", "This primary source is already registered with a different companion or fetch selection.") + receipt_path = safe_path(entry["receipt"]) + receipt = read_json(receipt_path) + if identity(receipt) != source or selection(receipt) != files: + raise ValueError("The storage index does not match its source receipt.") + try: + completed_fetch(receipt_path) + except (OSError, ValueError, KeyError, TypeError) as error: + destination = safe_path(receipt["local_dir"]) + marker_path = receipt_path.with_name(receipt_path.stem + ".done.json") + if not destination.exists() and receipt.get("marker") == str(marker_path): + marker = read_json(marker_path) + bound = ("repo", "revision", "file", "subfolder", "additional_files", "local_dir", "preview_hash", "proof_token", "started_at", "downloads_dir", "downloads") + pid = receipt.get("pid") + if (receipt.get("proof_token") and marker.get("exit_status") in ("done", "failed") + and all(marker.get(key) == receipt.get(key) for key in bound) + and isinstance(pid, int) and pid > 0 and not _pid_alive(pid)): + # Explicit removal/quarantine of the old source permits a retry, + # always at its original location, after the worker has stopped. + result["local_dir"] = str(destination) + return result + raise StorageError("storage_source_changed", "The registered source is incomplete, running, missing or changed; inspect its original receipt before downloading again.") from error + result.update(mode="reuse", receipt=str(receipt_path), local_dir=receipt["local_dir"], fetch_preview_hash=receipt["preview_hash"]) + return result + + +@contextmanager +def admission(plan): + reviewed = plan["storage"] + root = _root(reviewed["root"], create=True) + lock = safe_path(root / ".admission.lock") + descriptor = os.open(lock, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0), 0o600) + try: + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_nlink != 1: + raise ValueError("The storage admission lock must be a private owned regular file.") + try: + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError as error: + raise StorageError("storage_busy", "Another process is admitting this source; wait for its receipt before retrying.") from error + current = _entry(root, reviewed["key"]) + if _digest(current) != reviewed["generation"]: + raise StorageError("storage_changed", "Source admission changed after preview; review the current source before continuing.") + yield root / (reviewed["key"] + ".json") + finally: + os.close(descriptor) + + +def register(path, plan, receipt): + sources = _sources(_entry(path.parent, path.stem)) + sources[plan["storage"]["source_key"]] = {"source": identity(plan), "selection": selection(plan), + "directory": str(safe_path(plan["local_dir"])), "receipt": str(receipt)} + write_text_atomic(path, json.dumps({"schema": 1, "sources": sources}, sort_keys=True)) + + +def reused_receipt(plan): + current = inspect(plan, plan["storage"]["root"]) + if current != plan["storage"]: + raise StorageError("storage_changed", "The registered source changed after preview.") + return read_json(current["receipt"]) + + +def reuse_outcome(plan): + receipt = reused_receipt(plan) + path = plan["storage"]["receipt"] + marker = read_json(receipt["marker"]) + job = {key: receipt.get(key) for key in ( + "repo", "revision", "file", "subfolder", "additional_files", "local_dir", "preview_hash", "log_path", "started_at")} + job.update(receipt=path, state="done", path=receipt["local_dir"], + completed_at=marker.get("finished_at"), files=marker["files"]) + return {"status": "reused", "receipt": receipt, "reused_fetch": job} diff --git a/packages/codex/mlx-agent/src/mlx_agent/front_door.py b/packages/codex/mlx-agent/src/mlx_agent/front_door.py new file mode 100644 index 0000000..bfd0cfd --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/front_door.py @@ -0,0 +1,191 @@ +"""Authenticated loopback front door that routes requests to discovered model routes by name.""" +from __future__ import annotations + +import argparse +import http.client +from http.server import ThreadingHTTPServer +import json +from pathlib import Path +import signal +import threading +import time + +from .jit_serve import GatewayError, GatewayHandler, MAX_BODY, MAX_REQUESTS, public_model_name + +CHAT_PATHS = ("/v1/chat/completions", "/v1/completions", "/v1/messages", "/v1/responses") +EMBEDDINGS_PATH = "/v1/embeddings" +SYSTEMONE_PATH = "/v1/systemone" +# Typed-route endpoints and the task kind a route must serve to answer them. +TASK_PATHS = {EMBEDDINGS_PATH: "embedding", SYSTEMONE_PATH: "classification"} +REFRESH_SECONDS = 5 + + +def route_table(services, digest): + """Stable name to route for live routes verifying `digest`; a name served twice maps to None.""" + table = {} + for entry in services: + if not (entry.get("alive") and entry.get("argv_match") and entry.get("api_key_sha256") == digest + and (entry.get("jit") or entry.get("runtime") == "tasks") and isinstance(entry.get("port"), int)): + continue + name = public_model_name(entry["path"]) if entry.get("path") else entry.get("repo") + if isinstance(name, str) and name: + table[name] = None if name in table else entry + return table + + +class FrontDoorServer(ThreadingHTTPServer): + daemon_threads = True + block_on_close = False + + def __init__(self, address, config, discover): + super().__init__(address, FrontDoorHandler) + self.config, self.discover = config, discover + self.digest = config.get("api_key_sha256") or config["access_key_sha256"] + self.slots = threading.BoundedSemaphore(MAX_REQUESTS + 4) + self.lock = threading.Lock() + self.table, self.loaded_at = {}, None + + def routes(self, refresh=False): + with self.lock: + if refresh or self.loaded_at is None or time.monotonic() - self.loaded_at >= REFRESH_SECONDS: + self.table = route_table(self.discover().get("services", []), self.digest) + self.loaded_at = time.monotonic() + return self.table + + def forget(self): + with self.lock: + self.loaded_at = None + + def process_request(self, request, client_address): + if not self.slots.acquire(blocking=False): + request.close() + return + try: + super().process_request(request, client_address) + except BaseException: + self.slots.release() + raise + + def process_request_thread(self, request, client_address): + try: + super().process_request_thread(request, client_address) + finally: + self.slots.release() + + +class FrontDoorHandler(GatewayHandler): + server_version = "MLX-Front-Door" + + def do_GET(self): + try: + self._guard() + if self.path == "/health": + self._json(200, {"status": "ok"}) + elif self.path == "/v1/models": + self._json(200, {"object": "list", "data": [ + dict({"id": name, "object": "model", "owned_by": "mlx-agent"}, + **({"task_kinds": route["task_kinds"]} if route.get("task_kinds") else {})) + for name, route in sorted(self.server.routes(refresh=True).items()) if route is not None]}) + else: + raise GatewayError(404, "not_found", "Unknown endpoint.") + except GatewayError as error: + self._error(error) + + def do_POST(self): + try: + self._guard() + if self.path not in CHAT_PATHS and self.path not in TASK_PATHS: + raise GatewayError(404, "not_found", "Unknown inference endpoint.") + if self.headers.get("Transfer-Encoding"): + raise GatewayError(400, "invalid_body", "Use a bounded Content-Length request.") + try: + length = int(self.headers.get("Content-Length", "0")) + except ValueError: + raise GatewayError(400, "invalid_body", "Invalid Content-Length.") from None + if not 0 <= length <= MAX_BODY: + raise GatewayError(413, "body_too_large", "Request exceeds {} bytes.".format(MAX_BODY)) + payload = self.rfile.read(length) + try: + model = json.loads(payload).get("model") + except (ValueError, UnicodeError, AttributeError): + raise GatewayError(400, "invalid_body", "Expected a JSON object.") from None + self._forward(self._route(model)["port"], payload) + except GatewayError as error: + self._error(error) + + def _route(self, model): + if not isinstance(model, str): + raise GatewayError(400, "invalid_body", "Name a model listed at /v1/models.") + table = self.server.routes() + if model not in table: + table = self.server.routes(refresh=True) + if model not in table: + raise GatewayError(404, "model_not_found", "No route with this key serves that model.") + route = table[model] + if route is None: + raise GatewayError(409, "ambiguous_model", "More than one route serves that model name.") + typed, kind = route.get("runtime") == "tasks", TASK_PATHS.get(self.path) + if (kind is not None) != typed or (typed and kind not in route.get("task_kinds", ())): + raise GatewayError(400, "unsupported_endpoint", "That model's route does not serve this endpoint.") + return route + + def _forward(self, port, payload): + # The guard admitted exactly one credential; the route verifies the same key digest. + headers = {"Content-Type": "application/json"} + for name in ("Authorization", "x-api-key"): + if self.headers.get(name) is not None: + headers[name] = self.headers[name] + connection = http.client.HTTPConnection("127.0.0.1", port, timeout=10) + started = False + try: + connection.request("POST", self.path, payload, headers) + connection.sock.settimeout(None) + response = connection.getresponse() + self.send_response(response.status) + self.send_header("Content-Type", response.getheader("Content-Type", "application/json")) + if response.status == 401: + self.send_header("WWW-Authenticate", "Bearer") + self.send_header("Connection", "close") + self.end_headers() + self.close_connection = True + started = True + while chunk := response.read1(65536): + self.wfile.write(chunk) + self.wfile.flush() + except (OSError, http.client.HTTPException): + if not started: + self.server.forget() + raise GatewayError(503, "route_unavailable", "The model route is unavailable.") from None + finally: + connection.close() + + +def main(argv=None): + parser = argparse.ArgumentParser(prog="mlx-agent serve front-door", description=__doc__) + parser.add_argument("--port", type=int, required=True) + key = parser.add_mutually_exclusive_group(required=True) + key.add_argument("--api-key-file") + key.add_argument("--api-key-sha256") + parser.add_argument("--receipts-dir", action="append", default=[]) + args = parser.parse_args(argv) + if not 1 <= args.port <= 65535: + parser.error("--port must be between 1 and 65535") + from .inference_auth import configuration_digest + from .service_registry import discover_services + if args.api_key_file: + path = str(Path(args.api_key_file).absolute()) + config = {"access_key_file": path, "access_key_sha256": configuration_digest(key_file=path)} + else: + config = {"api_key_sha256": configuration_digest(key_sha256=args.api_key_sha256)} + receipts = [str(Path(value).absolute()) for value in args.receipts_dir] + server = FrontDoorServer(("127.0.0.1", args.port), config, lambda: discover_services(receipts)) + previous = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)} + try: + for sig in previous: + signal.signal(sig, lambda *_: threading.Thread(target=server.shutdown, daemon=True).start()) + server.serve_forever() + finally: + server.server_close() + for sig, handler in previous.items(): + signal.signal(sig, handler) + return 0 diff --git a/packages/codex/mlx-agent/src/mlx_agent/generate_runner.py b/packages/codex/mlx-agent/src/mlx_agent/generate_runner.py index 5bc4d9e..04a32b8 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/generate_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/generate_runner.py @@ -6,6 +6,11 @@ import sys import time +if __package__: + from .runner_model_cache import load_model +else: + from runner_model_cache import load_model + def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) @@ -21,7 +26,7 @@ def main(argv=None): port = importlib.import_module(arguments.module) started = time.time() - model = port.load(arguments.model) + model = load_model(port.load, arguments.model) load_seconds = time.time() - started result = port.generate( model, arguments.prompt, arguments.out, width=arguments.width, height=arguments.height, diff --git a/packages/codex/mlx-agent/src/mlx_agent/gguf.py b/packages/codex/mlx-agent/src/mlx_agent/gguf.py index 497922b..1bc3cd8 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/gguf.py +++ b/packages/codex/mlx-agent/src/mlx_agent/gguf.py @@ -13,8 +13,9 @@ import re import struct from pathlib import Path +from stat import S_ISREG -from .backends import QUANTIZED_BITS +from .backends import QUANTIZED_BITS, CONVERSION_BITS MAX_SCAN_FILES = 4000 @@ -53,9 +54,8 @@ ARCHITECTURE_PORTS = {"qwen35": "qwen35"} # The llama.cpp vision projector type each port attaches from the model's folder. PORT_PROJECTORS = {"qwen35": "qwen3vl_merger"} -# Ports converted from GGUF quantize through their own tensor maps, checked at these widths only; -# other GGUFs convert at every quantized width. -GGUF_PORT_BITS = (4, 8) +# Port-specific output widths; DSpark retains MXFP4 experts and cannot offer floating output. +GGUF_PORT_BITS = {"qwen35": CONVERSION_BITS, "deepseek_v4_dspark": QUANTIZED_BITS} _MIN_NAME_MATCH = 6 # Trailing MLX quantization labels in folder names: Foo-MLX-4bit, Foo-4.4bpw, Foo-bf16, Foo-mxfp8. _MLX_QUANT_SUFFIX = re.compile( @@ -73,8 +73,16 @@ "model_type", "hidden_size", "num_hidden_layers", "intermediate_size", "num_attention_heads", "num_key_value_heads", "vocab_size", ) +# Task types that never stand in for a generator of the same architecture. +_SEPARATE_TASKS = ("embedding", "classification") +# Dimensions GGUF headers and config.json files both record: layers, hidden width, attention heads. +_SHAPE_GGUF_SUFFIXES = (".block_count", ".embedding_length", ".attention.head_count") +_SHAPE_CONFIG_KEYS = ("num_hidden_layers", "hidden_size", "num_attention_heads") _INTERESTING_KEYS = ( "general.architecture", + "general.type", + "general.base_model.0.name", + "general.base_model.0.repo_url", "general.name", "general.basename", "general.size_label", @@ -83,6 +91,8 @@ "general.parameter_count", "clip.projector_type", "clip.vision.projection_dim", + "qwen4exp.expert_count", + "qwen4exp.expert_feed_forward_length", ) _STRUCTURE_SUFFIXES = ( ".block_count", @@ -341,6 +351,35 @@ def _structure(metadata, tensor_count): return hashlib.sha256("|".join(fields).encode("utf-8")).hexdigest()[:16] +def _shape(architecture, layers, width, heads): + """A fingerprint of a model's architecture and size that is the same in every format, else None.""" + if not isinstance(architecture, str) or not architecture: + return None + if not all(isinstance(value, int) and not isinstance(value, bool) and value > 0 for value in (layers, width, heads)): + return None + family = re.sub(r"[^a-z0-9]", "", architecture.lower()) + return hashlib.sha256("{0}|{1}|{2}|{3}".format(family, layers, width, heads).encode("utf-8")).hexdigest()[:16] + + +def _gguf_shape(metadata): + architecture = metadata.get("general.architecture") + layers, width, heads = (metadata.get("{0}{1}".format(architecture, suffix)) for suffix in _SHAPE_GGUF_SUFFIXES) + predicted = metadata.get("{0}.nextn_predict_layers".format(architecture)) + if isinstance(layers, int) and isinstance(predicted, int) and 0 < predicted < layers: + # block_count includes the multi-token-prediction blocks; config.json counts them apart. + layers -= predicted + return _shape(architecture, layers, width, heads) + + +def _config_shape(value): + """The :func:`_shape` of a config.json object, read from its text_config when it has one.""" + if not isinstance(value, dict): + return None + nested = value.get("text_config") if isinstance(value.get("text_config"), dict) else {} + layers, width, heads = (value.get(key, nested.get(key)) for key in _SHAPE_CONFIG_KEYS) + return _shape(value.get("model_type", nested.get("model_type")), layers, width, heads) + + def _prediction_only(metadata, architecture, tensor_count): """A multi-token-prediction export: llama.cpp's nextn block without the layers it predicts from.""" layers = metadata.get("{0}.nextn_predict_layers".format(architecture)) @@ -367,10 +406,10 @@ def conversion_bits(entry): draft = entry.get("draft") port = draft.get("port") if draft is not None else entry.get("port") if port is not None: - return list(GGUF_PORT_BITS) + return list(GGUF_PORT_BITS.get(port, ())) if draft is not None or entry.get("companion") or not entry.get("readable"): return [] - return list(QUANTIZED_BITS) + return list(CONVERSION_BITS) def describe_gguf(path, signature=True): @@ -400,6 +439,7 @@ def describe_gguf(path, signature=True): "quantization": "unknown", "parameters": None, "structure": None, + "shape": None, "signature": None, "companion": any(token in stem.lower() for token in _COMPANION_NAMES), "draft": None, @@ -419,10 +459,21 @@ def describe_gguf(path, signature=True): entry["architecture"] = metadata.get("general.architecture") entry["companion"] = ( any(token in stem.lower() for token in _COMPANION_NAMES) + or str(metadata.get("general.type") or "").lower() == "mmproj" or str(entry["architecture"]).lower() in _COMPANION_ARCHITECTURES ) + identity = { + "artifact_kind": metadata.get("general.type"), + "declared_size": metadata.get("general.size_label"), + "base_model_name": metadata.get("general.base_model.0.name"), + "base_model_repo": metadata.get("general.base_model.0.repo_url"), + "projector_type": metadata.get("clip.projector_type"), + "projector_width": metadata.get("clip.vision.projection_dim"), + } + entry["identity"] = {key: value for key, value in identity.items() if value is not None} entry["quantization"] = _quantization(metadata, stem) entry["structure"] = _structure(metadata, header["tensor_count"]) + entry["shape"] = _gguf_shape(metadata) entry["tensor_count"] = header["tensor_count"] parameters = metadata.get("general.parameter_count") if isinstance(parameters, int) and not isinstance(parameters, bool): @@ -629,10 +680,14 @@ def scan_mlx_outputs(roots, limit=MAX_SCAN_FILES, errors=None): resolved = directory.resolve() if resolved not in seen: seen.add(resolved) + try: + shape = _gguf_shape(read_gguf_header(profile["gguf"])["metadata"]) + except GGUFError: + shape = None outputs.append({"path": str(directory), "name": directory.name, "model_key": _normalize_stem(directory.name), "quantization": None, "provenance": None, "runtime": "strata", "format": "gguf", - "weight_bytes": profile["weight_bytes"]}) + "weight_bytes": profile["weight_bytes"], "shape": shape, "repo": None}) dirnames[:] = [] if len(seen) >= limit: return sorted(outputs, key=lambda item: item["path"]) @@ -653,12 +708,21 @@ def scan_mlx_outputs(roots, limit=MAX_SCAN_FILES, errors=None): continue seen.add(resolved) dirnames[:] = [] + precision = None + if provenance and provenance.get("q_bits") in (16, 32) and marker is None: + bits = provenance["q_bits"] + source = provenance.get("source") or {} + explicit_float = source.get("kind") == "gguf" or (provenance.get("tool") == "mlx-agent.convert" and provenance.get("backend") == "mlx-lm") + precision = "FP%d" % bits if explicit_float else "Unquantized" outputs.append({ + "precision": precision, "path": str(directory), "name": directory.name, "model_key": _normalize_stem(directory.name), "quantization": marker, "provenance": provenance, + "shape": _config_shape(_read_json_object(directory / "config.json", MAX_CONFIG_BYTES)), + "repo": _hf_repo(directory), }) if len(seen) >= limit: return sorted(outputs, key=lambda item: item["path"]) @@ -788,6 +852,11 @@ def _hf_snapshot(directory): return len(parts) >= 3 and parts[-2] == "snapshots" and parts[-3].startswith("models--") +def _hf_repo(directory): + """The ``owner/name`` repository of a Hugging Face cache snapshot, else None.""" + return Path(directory).parts[-3][len("models--"):].replace("--", "/", 1) if _hf_snapshot(directory) else None + + def _mlx_name(directory): """Folder name of an MLX model; a cache snapshot uses its repository name.""" return Path(directory).parts[-3].split("--")[-1] if _hf_snapshot(directory) else Path(directory).name @@ -857,7 +926,7 @@ def _mlx_files(directory): def _mlx_quantization(output): marker = output.get("quantization") bits = marker.get("bits") if isinstance(marker, dict) else None - return "{0}-bit".format(bits) if isinstance(bits, int) and not isinstance(bits, bool) else "unknown" + return "{0}-bit".format(bits) if isinstance(bits, int) and not isinstance(bits, bool) else output.get("precision") or "unknown" def _ollama_stores(roots): @@ -914,6 +983,7 @@ def _describe_ollama(store, tree, manifest, signature): "name": name, "path": str(manifest), "blob": None, + "blobs": sorted({str(blob) for _kind, _layer, blob in described} | ({str(config_blob)} if config_blob else set())), "bytes": sum(size for size in sizes.values() if isinstance(size, int) and not isinstance(size, bool)), "modified_at": int(manifest.stat().st_mtime), } @@ -926,7 +996,7 @@ def _describe_ollama(store, tree, manifest, signature): record.update( format="gguf", blob=str(gguf), architecture=entry["architecture"], model_key=entry["model_key"], quantization=entry["quantization"], structure=entry["structure"], signature=entry["signature"], - readable=entry["readable"], draft=entry["draft"], + readable=entry["readable"], draft=entry["draft"], shape=entry["shape"], ) elif any(kind == "tensor" for kind, _layer, _blob in described): settings = next((_read_json_object(blob, MAX_CONFIG_BYTES) for kind, layer, blob in described @@ -939,6 +1009,7 @@ def _describe_ollama(store, tree, manifest, signature): format="safetensors", architecture=settings.get("model_type"), model_key=_mlx_name_key("{0}-{1}".format(model, tag)), quantization=label, structure=_config_structure(settings), signature=None, readable=True, draft=None, + shape=_config_shape(settings), ) else: return None @@ -1093,7 +1164,211 @@ def _keeper(members): return groups -def inventory(gguf_roots, mlx_roots=(), receipts=(), signature=True, limit=MAX_SCAN_FILES): +def _stored_file(location): + """A file's identity on disk (links followed), path and size; None when it cannot be read.""" + try: + stat = Path(location).stat() + except OSError: + return None + return {"id": "{0}:{1}".format(stat.st_dev, stat.st_ino), "path": str(location), "bytes": stat.st_size} + + +def _folder_files(directory): + """Every file in a model folder, hidden ones included: they leave with the folder.""" + files = [] + for dirpath, dirnames, filenames in os.walk(directory, followlinks=False): + dirnames.sort() + files.extend(item for item in (_stored_file(Path(dirpath) / name) for name in sorted(filenames)) if item) + return files + + +def _gguf_items(entries): + """GGUF models as storage items: a split model is one item, and the only model in a folder holds its projectors.""" + sets = {} + for entry in entries: + location = Path(entry["path"]) + shard = _SHARD.match(location.stem) if entry.get("shard") else None + key = (str(location.parent), shard.group("stem"), shard.group("total")) if shard else (entry["path"],) + sets.setdefault(key, []).append(entry) + models, companions = [], {} + for members in sets.values(): + members.sort(key=lambda item: (item.get("shard") or {}).get("index", 1)) + folder = str(Path(members[0]["path"]).parent) + if members[0].get("companion"): + companions.setdefault(folder, []).extend(members) + else: + models.append(members) + bases = {} + for members in models: + if members[0].get("draft") is None: + bases.setdefault(str(Path(members[0]["path"]).parent), []).append(members) + for folder, members in bases.items(): + if len(members) == 1 and folder in companions: + members[0].extend(companions.pop(folder)) + models.extend([item] for members in companions.values() for item in members) + items = [] + for members in models: + first = members[0] + items.append({ + "path": first["path"], "kind": "gguf", "format": "gguf", "name": first["name"], + "model_key": first["model_key"], "shape": first.get("shape") if first.get("draft") is None else None, + "files": [item for item in (_stored_file(member["path"]) for member in members) if item], + }) + return items + + +def _storage_items(entries, outputs, ollama): + items = _gguf_items(entries) + for output in outputs: + items.append({ + "path": output["path"], "kind": "folder", "format": output.get("format", "mlx"), + "name": _mlx_name(output["path"]), "model_key": _mlx_model_key(output["path"]), + "shape": output.get("shape"), "files": _folder_files(output["path"]), + }) + for model in ollama: + files = [_stored_file(location) for location in [model["path"]] + model.get("blobs", [])] + items.append({ + "path": model["path"], "kind": "ollama", "format": model["format"], "name": model["name"], + "model_key": model["model_key"], "shape": model.get("shape") if model.get("draft") is None else None, + "files": [item for item in files if item], + }) + return sorted(items, key=lambda item: item["path"]) + + +def _scan_root(path, roots): + """The deepest scan root holding ``path``.""" + matches = [root for root in roots if Path(path).is_relative_to(root)] + return max(matches, key=lambda root: len(Path(root).parts)) if matches else str(Path(path).parent) + + +def _store(item): + if item["kind"] == "ollama": + return "ollama" + parts = Path(item["path"]).parts + cached = any(parts[index] == "snapshots" and parts[index - 1].startswith("models--") for index in range(1, len(parts))) + return "huggingface" if cached else "folder" + + +def _unique_bytes(items): + files = {} + for item in items: + for stored in item["files"]: + files.setdefault(stored["id"], stored["bytes"]) + return sum(files.values()) + + +def _root_usage(root, claimed, counted, occupied): + """Bytes of every file under a scan root not yet ``counted``, and the bytes that belong to no model. + + Those are grouped by the outermost folder (or file) on their path that holds + no model, given the ``occupied`` paths: every model and its parent folders. + """ + base = Path(root) + total = 0 + other = {} + for dirpath, _dirnames, filenames in os.walk(base, followlinks=False): + for name in filenames: + location = Path(dirpath) / name + try: + stat = location.lstat() + except OSError: + continue + key = "{0}:{1}".format(stat.st_dev, stat.st_ino) + if not S_ISREG(stat.st_mode) or key in counted: + continue + counted.add(key) + total += stat.st_size + if key in claimed: + continue + group = base + for part in location.relative_to(base).parts: + group = group / part + if str(group) not in occupied: + break + other[str(group)] = other.get(str(group), 0) + stat.st_size + return total, other + + +def storage(entries, outputs, ollama, roots, assets=()): + """What every model occupies on disk, each file counted once however many models or links reach it. + + An item is a GGUF model (all its shards, plus the projectors beside it when it + is the only model in its folder), a model folder, or an Ollama model (its + manifest and blobs). ``files`` lists each file's disk identity, so the bytes a + removal frees are the files no remaining item still uses. Each file counts once + toward ``disk_bytes``, under the first root and store that hold it. Each root + also reports ``total_bytes``, every file beneath it, and ``other``: where the + bytes that belong to no recognized model sit. + """ + items = sorted(_storage_items(entries, outputs, ollama) + list(assets), key=lambda item: item["path"]) + claimed = set() + by_root = {root: 0 for root in roots} + by_store = {} + for item in items: + item["root"] = _scan_root(item["path"], roots) + item["store"] = _store(item) + own = {stored["id"]: stored["bytes"] for stored in item["files"]} + item["bytes"] = sum(own.values()) + fresh = sum(size for key, size in own.items() if key not in claimed) + claimed.update(own) + by_root[item["root"]] = by_root.get(item["root"], 0) + fresh + by_store[item["store"]] = by_store.get(item["store"], 0) + fresh + occupied = {str(parent) for item in items for parent in [Path(item["path"]), *Path(item["path"]).parents]} + counted = set() + usage = [] + for root, size in by_root.items(): + total, other = _root_usage(root, claimed, counted, occupied) + usage.append({ + "root": root, "bytes": size, "total_bytes": total, + "other": [{"path": path, "bytes": value} for path, value in sorted(other.items(), key=lambda pair: (-pair[1], pair[0]))], + }) + return { + "disk_bytes": sum(by_root.values()), + "roots": usage, + "stores": [{"store": store, "bytes": size} for store, size in sorted(by_store.items())], + "items": items, + } + + +def _display_stem(name): + """A model name without its file extension and trailing quantization labels.""" + stem = name[:-len(GGUF_SUFFIX)] if name.lower().endswith(GGUF_SUFFIX) else name + while True: + trimmed = _MLX_QUANT_SUFFIX.sub("", stem) + if trimmed == stem or not trimmed: + return stem + stem = trimmed + + +def families(items, task_types=None): + """Copies of one model across formats and stores. + + Items share a family when their architecture and size match (:func:`_shape`: + fine-tunes and quantizations of one base model), else when their names match + without quantization labels. ``task_types`` maps an item path to its task type; + embedding and classification models stay apart from generators of the same + architecture. ``bytes`` counts each file once. + """ + groups = {} + for item in items: + task = (task_types or {}).get(item["path"]) + if item["shape"]: + key = "shape:" + item["shape"] + (":" + task if task in _SEPARATE_TASKS else "") + else: + key = "name:" + item["model_key"] + groups.setdefault(key, []).append(item) + found = [] + for key, members in groups.items(): + name = min((item["kind"] == "ollama", len(_normalize_stem(_display_stem(item["name"]))), _display_stem(item["name"])) + for item in members)[2] + found.append({ + "family_id": key, "name": name, "copies": len(members), + "members": sorted(item["path"] for item in members), "bytes": _unique_bytes(members), + }) + return sorted(found, key=lambda family: (-family["bytes"], family["family_id"])) + + +def inventory(gguf_roots, mlx_roots=(), receipts=(), signature=True, limit=MAX_SCAN_FILES, compare_assets=False, asset_exclude_roots=()): """One read-only pass: what exists, what is converted, what is redundant.""" errors = [] entries = scan_gguf(gguf_roots, signature=signature, limit=limit, errors=errors) @@ -1102,14 +1377,25 @@ def inventory(gguf_roots, mlx_roots=(), receipts=(), signature=True, limit=MAX_S paired = pair_conversions(entries, outputs, receipts) duplicates = group_duplicates(paired + _ollama_gguf_entries(ollama)) + group_mlx_duplicates( outputs, signature=signature, ollama=ollama) + from .standalone_assets import scan as scan_assets + all_roots = list(dict.fromkeys([str(Path(root).expanduser()) for root in list(gguf_roots) + list(mlx_roots or gguf_roots)])) + assets, asset_duplicates, asset_scan = scan_assets(all_roots, _storage_items(paired, outputs, ollama), limit, compare_assets, asset_exclude_roots) + duplicates.extend(asset_duplicates) for group in duplicates: group["group_id"] = "{0}:{1}".format(group["kind"], group["identity"]) pending = [item for item in paired if item["status"] == "pending"] + roots = { + "gguf": [str(Path(root).expanduser()) for root in gguf_roots], + "mlx": [str(Path(root).expanduser()) for root in (mlx_roots or gguf_roots)], + } + stored = storage(paired, outputs, ollama, list(dict.fromkeys(roots["gguf"] + roots["mlx"])), assets) + sizes = {item["path"]: item["bytes"] for item in stored["items"]} + for output in outputs: + output["bytes"] = sizes.get(output["path"], 0) return { - "roots": { - "gguf": [str(Path(root).expanduser()) for root in gguf_roots], - "mlx": [str(Path(root).expanduser()) for root in (mlx_roots or gguf_roots)], - }, + "roots": roots, + "storage": stored, + "asset_scan": asset_scan, "models": paired, "root_errors": errors, "outputs": outputs, diff --git a/packages/codex/mlx-agent/src/mlx_agent/gguf_runner.py b/packages/codex/mlx-agent/src/mlx_agent/gguf_runner.py index 0bca59e..56f77e9 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/gguf_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/gguf_runner.py @@ -5,9 +5,9 @@ nothing from :mod:`mlx_agent`. Two bounded steps, in order: 1. dequantize the GGUF back to Hugging Face weights with ``transformers``; -2. quantize those weights into MLX with the ``mlx_lm.convert`` executable. +2. write quantized or floating MLX weights with the ``mlx_lm.convert`` executable. -The intermediate fp16 checkpoint is large and temporary; it is removed unless +The intermediate checkpoint is large and temporary; it is removed unless ``--keep-intermediate`` is passed. ``--port`` instead hands the GGUF to a bundled port that maps its tensors straight into MLX shards, for architectures ``transformers`` cannot load (llama.cpp's DSpark drafters, Qwen3.5). The worker writes a @@ -75,8 +75,8 @@ def _is_within_script_dir(candidate): PORTS_DIR = Path(__file__).resolve().parent / "resources" / "ports" # --port name to its converter under resources/ports///convert.py. GGUF_PORTS = {"deepseek_v4_dspark": "mlx-lm", "qwen35": "mlx-vlm"} -Q_BITS = (4, 5, 6, 8) -PORT_Q_BITS = (4, 8) +Q_BITS = (2, 3, 4, 5, 6, 8, 16, 32) +PORT_Q_BITS = {"qwen35": Q_BITS, "deepseek_v4_dspark": (2, 3, 4, 5, 6, 8)} SHARD_BYTES = 5 << 30 @@ -104,14 +104,18 @@ def _missing_modules(names=REQUIRED_MODULES): return missing -def dequantize(gguf_path, work_dir): +def dequantize(gguf_path, work_dir, q_bits=4): """Materialize Hugging Face weights from a GGUF file.""" from transformers import AutoModelForCausalLM, AutoTokenizer directory = str(gguf_path.parent) filename = gguf_path.name _log("dequantizing {0}".format(filename)) - model = AutoModelForCausalLM.from_pretrained(directory, gguf_file=filename) + if q_bits == 32: + import torch + model = AutoModelForCausalLM.from_pretrained(directory, gguf_file=filename, torch_dtype=torch.float32) + else: + model = AutoModelForCausalLM.from_pretrained(directory, gguf_file=filename) model.save_pretrained(str(work_dir)) del model tokenizer = AutoTokenizer.from_pretrained(directory, gguf_file=filename) @@ -130,9 +134,9 @@ def quantize(work_dir, out_dir, q_bits): executable, "--hf-path", str(work_dir), "--mlx-path", str(out_dir), - "-q", - "--q-bits", str(q_bits), ] + argv += (["--dtype", "float%d" % q_bits, "--dequantize"] if q_bits in (16, 32) + else ["-q", "--q-bits", str(q_bits)]) _log("running {0}".format(" ".join(argv))) completed = subprocess.run(argv, stdin=subprocess.DEVNULL, check=False) if completed.returncode != 0: @@ -241,8 +245,8 @@ def main(argv=None): if projector is not None and (arguments.port is None or not projector.is_file()): _log("--projector needs --port and an existing file: {0}".format(projector)) return 2 - if arguments.port and arguments.q_bits not in PORT_Q_BITS: - _log("--port converts at {0} bits only".format(" or ".join(str(bits) for bits in PORT_Q_BITS))) + if arguments.port and arguments.q_bits not in PORT_Q_BITS[arguments.port]: + _log("--port converts at {0} bits only".format(" or ".join(str(bits) for bits in PORT_Q_BITS[arguments.port]))) return 2 if out_dir.exists(): _log("output already exists: {0}".format(out_dir)) @@ -275,7 +279,7 @@ def main(argv=None): return 2 work_dir.mkdir(parents=True) try: - dequantize(gguf_path, work_dir) + dequantize(gguf_path, work_dir, arguments.q_bits) quantize(work_dir, out_dir, arguments.q_bits) write_provenance( out_dir, gguf_path, arguments.q_bits, diff --git a/packages/codex/mlx-agent/src/mlx_agent/identity_pass.py b/packages/codex/mlx-agent/src/mlx_agent/identity_pass.py new file mode 100644 index 0000000..4be3cf8 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/identity_pass.py @@ -0,0 +1,195 @@ +"""The identity pass: every bound file and runtime still matches the serving plan. + +serve and jit_serve import this module. The checks import those modules back, +so those imports stay inside the checks. +""" +from pathlib import Path + + +def _rejected(code, message, remediation): + from .serve import ServeError + + raise ServeError(code, message, remediation) + + +def _require_auth_identity(plan): + if plan.get("api_key_sha256") is None: + return + from .inference_auth import runtime_fingerprint, validate_digest + + try: + validate_digest(plan["api_key_sha256"]) + if not plan.get("jit") or plan.get("auth_runtime_sha256") != runtime_fingerprint(): + raise ValueError("Authentication configuration changed after preview.") + except ValueError as error: + _rejected("preview_stale", str(error), "Review a fresh authenticated serving plan.") + + +def _require_task_identity(plan): + if plan.get("task_identity") is None: + return + from .task_contracts import TaskError + from .task_identity import check_identity + from .task_serving import runtime_fingerprint + + try: + check_identity(plan["task_identity"]) + if runtime_fingerprint(plan["task_identity"]["backend"]) != plan.get("task_runtime_fingerprint"): + raise TaskError("runtime_changed", "The accepted inference adapter changed.") + except TaskError as error: + code = "runtime_changed" if error.code == "runtime_changed" else "preview_stale" + _rejected(code, str(error), "Review a fresh task serving plan.") + except OSError as error: + _rejected("preview_stale", str(error), "Review a fresh task serving plan.") + + +def _require_training_binding(plan): + binding = plan.get("training_binding") + if binding is None: + return + try: + from .training_artifacts import read_trained_adapter + + _, current = read_trained_adapter(binding["training_receipt"]) + if current == binding: + return + except (OSError, ValueError, TypeError, KeyError): + pass + _rejected("training_receipt_changed", "The training receipt or its pinned artifacts changed.", + "Review a fresh serving preview for the completed training receipt.") + + +def _argv_adapter(plan): + argv = plan.get("worker_argv") + if not isinstance(argv, list) or "--adapter-path" not in argv: + return None + index = argv.index("--adapter-path") + 1 + if index >= len(argv): + return False + return argv[index] + + +def _require_adapter_identity(plan): + named = _argv_adapter(plan) + path = plan.get("adapter_path") + if path is None and named is None: + return + if (named is False or (named is not None and ( + not isinstance(path, str) or named != path or not plan.get("adapter_identity")))): + _rejected("adapter_changed", "Adapter files changed after the serving preview.", + "Review a fresh serve plan before starting this adapter.") + if not isinstance(path, str): + _rejected("adapter_changed", "Adapter files changed after the serving preview.", + "Review a fresh serve plan before starting this adapter.") + try: + from .lora import adapter_identity + + local = Path(path).expanduser().absolute() + identity = adapter_identity(local) + if str(local) == path and identity == plan.get("adapter_identity"): + return + except (TypeError, ValueError, OSError): + pass + _rejected("adapter_changed", "Adapter files changed after the serving preview.", + "Review a fresh serve plan before starting this adapter.") + + +def _require_prefill_identity(plan): + if "prefill_kernel" not in plan: + return + from .prefill_runtime import can_wrap_runtime, identity + + configured = plan["prefill_kernel"] + facts = {key: value for key, value in configured.items() if key not in ("adapter_enabled", "runtime_executable")} + if facts != identity() or (configured.get("adapter_enabled") and not can_wrap_runtime(configured["runtime_executable"])): + _rejected("prefill_kernel_changed", "Prompt kernel source or dependencies changed.", + "Review a fresh serving preview.") + + +def _require_decode_identity(plan): + if "decode_profile" not in plan: + return + from .prompt_lookup_runtime import can_wrap_runtime, identity + + configured = plan["decode_profile"] + facts = {key: value for key, value in configured.items() if key not in ("adapter_enabled", "runtime_executable")} + if facts != identity() or (configured.get("adapter_enabled") and not can_wrap_runtime(configured["runtime_executable"])): + _rejected("decode_profile_changed", "Code-edit runtime source or dependencies changed.", + "Review a fresh serving preview.") + + +def _require_vision_identity(plan): + if "vision_profile" not in plan: + return + from .vision_runtime import identity + + configured = plan["vision_profile"] + facts = {key: value for key, value in configured.items() if key != "adapter_enabled"} + if facts != identity(configured["runtime_executable"]): + _rejected("vision_profile_changed", "Vision runtime source or dependencies changed.", + "Review a fresh serving preview.") + + +def _require_splash_identity(plan): + if plan.get("runtime") != "splash": + return + from .splash_runtime import SplashError, installed_runtime, read_draft, read_target + + try: + current = (read_target(plan["splash_model_dir"])["fingerprint"], + read_draft(plan["splash_draft_model"])["fingerprint"] if plan.get("splash_draft_model") else None, + installed_runtime(plan["splash_launcher"])["fingerprint"]) + except (SplashError, KeyError) as error: + _rejected("preview_stale", str(error), "Review a fresh Splash serve plan.") + if current != (plan["splash_model_fingerprint"], plan["splash_draft_fingerprint"], plan["splash_runtime_fingerprint"]): + _rejected("preview_stale", "The Splash target, draft or launcher changed after preview.", + "Review a fresh Splash serve plan.") + + +def _require_access_identity(plan): + if "private_worker" not in plan and "access_key_file" not in plan: + return + from .private_serve import identity + from .serving_access import read_access_key + + try: + if "private_worker" in plan and plan.get("runtime") != "mlx_lm": + raise ValueError("Private worker source changed.") + if "access_key_file" in plan: + read_access_key(plan["access_key_file"], plan["access_key_sha256"]) + if "private_worker" in plan and plan["private_worker"] != identity(): + raise ValueError("Private worker source changed.") + except (OSError, ValueError): + _rejected("preview_stale", "Protected serving inputs changed after preview.", + "Review a fresh serve plan.") + + +def _require_model_identity(plan): + if "fingerprint" not in plan or "local_path" not in plan: + return + from .jit_serve import model_fingerprint + + try: + current = model_fingerprint(plan["local_path"]) + except ValueError as error: + _rejected("model_changed", str(error), "Review a fresh serve plan.") + if current != plan["fingerprint"]: + _rejected("model_changed", "Model files changed. Stop and review a fresh serve plan.", + "Review a fresh serve plan.") + + +def recheck_bound_identity(plan): + """One pass over every identity bound into a reviewed serving plan.""" + for check in ( + _require_auth_identity, + _require_task_identity, + _require_training_binding, + _require_adapter_identity, + _require_prefill_identity, + _require_decode_identity, + _require_vision_identity, + _require_splash_identity, + _require_access_identity, + _require_model_identity, + ): + check(plan) diff --git a/packages/codex/mlx-agent/src/mlx_agent/inference_auth.py b/packages/codex/mlx-agent/src/mlx_agent/inference_auth.py new file mode 100644 index 0000000..9d95cfb --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/inference_auth.py @@ -0,0 +1,125 @@ +"""Optional bearer-key verification shared by local gateways and their workers.""" +import hashlib +import hmac +from pathlib import Path +import re + + +def validate_digest(value): + if not isinstance(value, str) or not re.fullmatch('[0-9a-f]{64}', value): + raise ValueError('API key verification requires a lowercase SHA-256 digest.') + return value + + +def key_file_digest(filename): + if __package__: + from .serving_access import read_access_key + else: + from serving_access import read_access_key + return read_access_key(filename)[1] + + +def configuration_digest(key_file=None, key_sha256=None): + if key_file is not None: + if key_sha256 is not None: + raise ValueError('Select one API key source.') + return key_file_digest(key_file) + return validate_digest(key_sha256) if key_sha256 is not None else None + + +def authorized(authorization, api_keys, digest): + """Reject ambiguous credentials and compare only fixed-length verification hashes.""" + if len(authorization) + len(api_keys) != 1: + return False + if authorization: + scheme, separator, token = authorization[0].partition(b' ') + if scheme.lower() != b'bearer' or not separator: + return False + else: + token = api_keys[0] + if not 1 <= len(token) <= 512 or any(b < 33 or b > 126 for b in token): + return False + return hmac.compare_digest(hashlib.sha256(token).hexdigest(), digest) + + +def authorized_headers(headers, digest): + return authorized([v.encode('latin-1') for v in headers.get_all('Authorization', [])], + [v.encode('latin-1') for v in headers.get_all('x-api-key', [])], digest) + + +def runtime_fingerprint(): + digest = hashlib.sha256() + for name in ('inference_auth.py', 'protected_worker.py', 'owned_worker.py'): + digest.update(Path(__file__).with_name(name).read_bytes()) + return digest.hexdigest() + + +def loopback_opener(): + import urllib.request + + class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + return urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect()) + + +class AuthenticatedASGI: + def __init__(self, app, digest): + self.app, self.digest = app, validate_digest(digest) + + async def __call__(self, scope, receive, send): + if scope['type'] in ('http', 'websocket'): + headers = scope.get('headers', []) + if not authorized([v for k, v in headers if k.lower() == b'authorization'], + [v for k, v in headers if k.lower() == b'x-api-key'], self.digest): + if scope['type'] == 'websocket': + await send({'type': 'websocket.close', 'code': 4401}) + else: + body = b'{"error":{"code":"authentication_required","message":"A valid API key is required."}}' + await send({'type': 'http.response.start', 'status': 401, 'headers': [ + (b'content-type', b'application/json'), (b'content-length', str(len(body)).encode()), + (b'www-authenticate', b'Bearer'), (b'connection', b'close')]}) + await send({'type': 'http.response.body', 'body': body}) + return + if scope['type'] in ('http', 'websocket'): + scope = dict(scope, headers=[(k, v) for k, v in scope.get('headers', []) + if k.lower() not in (b'authorization', b'x-api-key')]) + await self.app(scope, receive, send) + + +def protect_worker(digest, asgi=False): + """Install enforcement before importing the selected server, in its own process.""" + from http.server import BaseHTTPRequestHandler + validate_digest(digest) + parse = BaseHTTPRequestHandler.parse_request + + def parse_request(handler): + if not parse(handler): + return False + if authorized_headers(handler.headers, digest): + del handler.headers['Authorization'] + del handler.headers['x-api-key'] + return True + body = b'{"error":{"code":"authentication_required","message":"A valid API key is required."}}' + handler.send_response(401) + handler.send_header('WWW-Authenticate', 'Bearer') + handler.send_header('Content-Type', 'application/json') + handler.send_header('Content-Length', str(len(body))) + handler.send_header('Connection', 'close') + handler.end_headers() + handler.close_connection = True + if handler.command != 'HEAD': + handler.wfile.write(body) + return False + + BaseHTTPRequestHandler.parse_request = parse_request + if asgi: + import uvicorn + load = uvicorn.Config.load + + def load_authenticated(config): + load(config) + config.loaded_app = AuthenticatedASGI(config.loaded_app, digest) + + uvicorn.Config.load = load_authenticated diff --git a/packages/codex/mlx-agent/src/mlx_agent/inference_defaults.py b/packages/codex/mlx-agent/src/mlx_agent/inference_defaults.py new file mode 100644 index 0000000..f21faf7 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/inference_defaults.py @@ -0,0 +1,44 @@ +"""Validated defaults for chat requests through a managed model gateway.""" +import hashlib +import math + + +def validate(system_prompt=None, temperature=None, top_p=None): + result = {} + if system_prompt is not None: + if not isinstance(system_prompt, str) or '\x00' in system_prompt: + raise ValueError('System prompt must be text without null characters.') + try: + size = len(system_prompt.encode('utf-8')) + except UnicodeError: + raise ValueError('System prompt must be valid UTF-8 text.') from None + if size > 8192: + raise ValueError('System prompt must not exceed 8192 UTF-8 bytes.') + if system_prompt: + result['system_prompt'] = system_prompt + for name, value, lower, upper in (('temperature', temperature, 0, 2), ('top_p', top_p, 0, 1)): + if value is not None: + if type(value) not in (int, float) or not math.isfinite(value) or not lower <= value <= upper: + raise ValueError('{} must be between {} and {}.'.format(name, lower, upper)) + result[name] = float(value) + return result + + +def apply(body, defaults): + result = dict(body) + for field in ('temperature', 'top_p'): + if field in defaults: + result.setdefault(field, defaults[field]) + messages = body.get('messages') + if (defaults.get('system_prompt') and isinstance(messages, list) + and all(isinstance(message, dict) for message in messages) + and not any(message.get('role') in ('system', 'developer') for message in messages)): + result['messages'] = [{'role': 'system', 'content': defaults['system_prompt']}] + messages + return result + + +def summary(defaults): + result = {key: value for key, value in defaults.items() if key != 'system_prompt'} + if defaults.get('system_prompt'): + result['system_prompt_sha256'] = hashlib.sha256(defaults['system_prompt'].encode()).hexdigest() + return result diff --git a/packages/codex/mlx-agent/src/mlx_agent/inference_telemetry.py b/packages/codex/mlx-agent/src/mlx_agent/inference_telemetry.py new file mode 100644 index 0000000..97573ad --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/inference_telemetry.py @@ -0,0 +1,115 @@ +"""Bounded numeric observations for one inference gateway process.""" +import datetime +import json +import math +import threading +import time + +MAX_LINE = 65536 +MAX_TOKENS = 2**53 - 1 + + +def _timestamp(): + return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z') + + +class InferenceTelemetry: + def __init__(self, clock=time.monotonic): + self.clock = clock + self.started_at = _timestamp() + self.lock = threading.Lock() + self.requests = self.completed = self.failed = self.measured = 0 + self.input_tokens = self.output_tokens = 0 + self.last = None + + def begin(self): + request = RequestMeasurement(self, self.clock()) + with self.lock: + self.requests += 1 + return request + + def snapshot(self): + with self.lock: + return {'schema': 1, 'scope': 'gateway-process', 'started_at': self.started_at, + 'captured_at': _timestamp(), 'requests': self.requests, + 'completed_requests': self.completed, 'failed_requests': self.failed, + 'measured_requests': self.measured, + 'input_tokens': self.input_tokens if self.measured else None, + 'output_tokens': self.output_tokens if self.measured else None, + 'last_request': dict(self.last) if self.last else None} + + def finish(self, request, success): + with self.lock: + if request.finished: + return + request.finished = True + elapsed = self.clock() - request.started + elapsed = elapsed if math.isfinite(elapsed) and elapsed >= 0 else None + measured = success and request.tokens is not None + if success: + self.completed += 1 + else: + self.failed += 1 + if measured: + self.measured += 1 + self.input_tokens += request.tokens[0] + self.output_tokens += request.tokens[1] + self.last = {'completed_at': _timestamp(), 'outcome': 'completed' if success else 'failed', + 'input_tokens': request.tokens[0] if measured else None, + 'output_tokens': request.tokens[1] if measured else None, + 'response_seconds': elapsed, + 'output_tokens_per_second': request.tokens[1] / elapsed if measured and elapsed else None} + request.buffer.clear() + + +class RequestMeasurement: + def __init__(self, owner, started): + self.owner, self.started = owner, started + self.tokens = None + self.finished = False + self.buffer = bytearray() + self.discarding_line = False + self.stream_done = False + + def observe(self, value): + usage = value.get('usage') if isinstance(value, dict) else None + if not isinstance(usage, dict): + return + pair = usage.get('prompt_tokens'), usage.get('completion_tokens') + if all(type(value) is int and 0 <= value <= MAX_TOKENS for value in pair): + self.tokens = pair + + def observe_json(self, payload): + if b'"usage"' not in payload: + return + try: + self.observe(json.loads(payload)) + except (ValueError, TypeError, UnicodeError): + pass + + def feed(self, chunk): + """Inspect SSE usage without retaining an unbounded line or changing the relay.""" + offset = 0 + while offset < len(chunk): + end = chunk.find(b'\n', offset) + boundary = len(chunk) if end < 0 else end + length = boundary - offset + if len(self.buffer) + length > MAX_LINE: + self.buffer.clear() + self.discarding_line = True + elif not self.discarding_line: + self.buffer.extend(chunk[offset:boundary]) + if end < 0: + return + if not self.discarding_line and self.buffer.startswith(b'data: '): + payload = bytes(self.buffer[6:]).strip() + if payload == b'[DONE]': + self.stream_done = True + else: + self.observe_json(payload) + self.buffer.clear() + self.discarding_line = False + offset = end + 1 + + def finish(self, success): + self.owner.finish(self, success) diff --git a/packages/codex/mlx-agent/src/mlx_agent/intake.py b/packages/codex/mlx-agent/src/mlx_agent/intake.py index 2a6388e..1f88112 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/intake.py +++ b/packages/codex/mlx-agent/src/mlx_agent/intake.py @@ -9,7 +9,7 @@ import re from .backends import ( - QUANTIZED_BITS, choose_backend, component_matches, conversion_bits, load_manifests, load_registries, lookup, + CONVERSION_BITS, choose_backend, component_matches, conversion_bits, load_manifests, load_registries, lookup, port_downloads, port_files, port_for_files, port_for_pipeline, port_requirements, quantize_rule, recipe_for, snapshot_files, ) @@ -21,7 +21,7 @@ INTAKE_SCHEMA = "intake/1" TRANSPORT_ERRORS = (OSError, TimeoutError, http.client.HTTPException, ValueError) _BLOCKING_STATUSES = (401, 403, 404, 410) -ESTIMATE_BITS = QUANTIZED_BITS +ESTIMATE_BITS = CONVERSION_BITS ESTIMATE_MAX_SHARDS = 16 QUANT_GROUP_SIZE = 64 _DTYPE_BYTES = { @@ -127,8 +127,13 @@ def estimate_output_bytes(client, repo, revision, files, rule, warnings, support warnings.append("output size estimate unavailable: {0} has an unreadable tensor {1}".format(shard, name)) return None count = math.prod(shape) + if _quantizes(name, shape, rule) and not tensor.get("dtype", "").startswith(("F", "BF")): + warnings.append("output size estimate unavailable: packed weight dimensions do not describe logical parameters") + return None for bits in totals: - if _quantizes(name, shape, rule): + if bits in (16, 32): + totals[bits] += count * (bits // 8 if tensor.get("dtype", "").startswith(("F", "BF")) else width) + elif _quantizes(name, shape, rule): totals[bits] += -(-count * bits // 8) + (count // _group_size(rule)) * 2 * width else: totals[bits] += count * width @@ -402,10 +407,16 @@ def resolve(text, revision=None, client=None, manifests=None, registries=None): payload["q_bits"] = conversion_bits(payload["model_type"], backend, manifests) # A recipe's weights come from its base repository and a pipeline's from component folders, # whose quantization the header estimate does not model: no estimate rather than a wrong one. - if verdict in ("convertible", "convertible_after_install") and not recipe and not pipeline: + packed_config = bool(config.get("quantization") or config.get("quantization_config")) + if verdict in ("convertible", "convertible_after_install") and not recipe and not pipeline and not packed_config: payload["estimated_output_bytes"] = estimate_output_bytes( client, source["repo"], source["revision"], files, quantize_rule(payload["model_type"], backend, manifests), payload["warnings"], support_files=port_files(payload["model_type"], backend, manifests), prefix=prefix, ) + estimates = payload["estimated_output_bytes"] + if estimates is not None: + can_estimate_float = backend == "mlx-lm" and not config.get("quantization") + payload["estimated_output_bytes"] = {key: value for key, value in estimates.items() + if int(key) in payload["q_bits"] and (int(key) not in (16, 32) or can_estimate_float)} return payload diff --git a/packages/codex/mlx-agent/src/mlx_agent/intake_fetch.py b/packages/codex/mlx-agent/src/mlx_agent/intake_fetch.py index 9b44d6c..e889ea5 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/intake_fetch.py +++ b/packages/codex/mlx-agent/src/mlx_agent/intake_fetch.py @@ -6,6 +6,7 @@ import json import re import sys +import uuid from datetime import datetime, timezone from pathlib import Path @@ -16,6 +17,8 @@ from .convert import _default_module_present, _write_receipt, receipts_root from .intake_source import parse_hf_source, validate_file, validate_revision from .serve import _pid_alive +from .source_evidence import completed_fetch, immutable_revision, safe_path +from . import fetch_storage FETCH_RECEIPT_KIND = "fetch" FETCH_RUNNER = Path(__file__).resolve().with_name("fetch_runner.py") @@ -39,26 +42,38 @@ def _utc_now(): def plan_fetch(text, revision=None, file=None, hf_cache=None, local_dir=None, python=None, model_type=None, - manifests=None, downloads_dir=None): + manifests=None, downloads_dir=None, additional_files=None, storage_root=None): """A download plan. A snapshot of a ported model type (``model_type`` from intake) takes only the port's files; any other snapshot skips formats MLX never reads. A subfolder source takes only that folder.""" source = parse_hf_source(text) if revision: source["revision"] = validate_revision(revision) if file is not None: - source["file"] = validate_file(file) + source["file"] = validate_file(file, allow_support=True) local = None if local_dir is not None: local = Path(str(local_dir)).expanduser() if not local.is_absolute(): raise FetchError("invalid_arguments", "--local-dir must be an absolute path.", "Pass the full destination directory.") + extra = sorted(additional_files or []) + if extra and (not source["file"] or source.get("subfolder") or not immutable_revision(source["revision"]) or local is None or hf_cache is not None): + raise FetchError("invalid_arguments", "Additional files require a primary file, immutable revision and new local destination without a shared cache.", + "Select the exact files at one commit and pass --local-dir.") + if len(extra) > 64 or len(set(extra)) != len(extra) or source["file"] in extra: + raise FetchError("invalid_arguments", "The additional file set is duplicated or exceeds its limit.", "Select each companion or shard once (at most 64).") + for name in extra: + validate_file(name, allow_support=True) + fresh = local is not None and hf_cache is None and immutable_revision(source["revision"]) + if fresh and source["file"] and source.get("subfolder"): + raise FetchError("invalid_arguments", "A managed file selection must name its repository-relative path without a separate subfolder.", "Use org/name with --file folder/name instead.") python = str(python or sys.executable) argv = [python, str(FETCH_RUNNER), "--repo", source["repo"], "--revision", source["revision"]] ignore_patterns, allow_patterns = [], [] prefix = source["subfolder"] + "/" if source.get("subfolder") else "" ported = recipe = None requires, downloads = {}, [] + support_dir = None if not source["file"] and model_type: manifests = load_manifests() if manifests is None else manifests ported = snapshot_files(model_type, manifests) @@ -66,13 +81,17 @@ def plan_fetch(text, revision=None, file=None, hf_cache=None, local_dir=None, py recipe = recipe if recipe and recipe["port"] == model_type else None if source["file"]: argv += ["--file", source["file"]] + for name in extra: + argv += ["--additional-file", name] elif recipe: # The recipe's model is its pinned base snapshot plus the LoRA this repository ships. allow_patterns = [recipe["lora"]] ignore_patterns = list(FETCH_IGNORE_PATTERNS) - argv += ["--allow", recipe["lora"], "--base-repo", recipe["base"], "--base-revision", recipe["base_revision"]] - for pattern in ignore_patterns: - argv += ["--base-ignore", pattern] + argv += ["--allow", recipe["lora"]] + if not fresh: + argv += ["--base-repo", recipe["base"], "--base-revision", recipe["base_revision"]] + for pattern in ignore_patterns: + argv += ["--base-ignore", pattern] else: if ported: allow_patterns = [prefix + name for name in ported] @@ -85,22 +104,35 @@ def plan_fetch(text, revision=None, file=None, hf_cache=None, local_dir=None, py for pattern in ignore_patterns: argv += ["--ignore", pattern] requires = port_requirements(model_type, manifests) if ported and not prefix else {} - for repo, names in sorted(requires.items()): - argv += [item for name in names for item in ("--require", repo + "=" + name)] + if not fresh: + for repo, names in sorted(requires.items()): + argv += [item for name in names for item in ("--require", repo + "=" + name)] downloads = port_downloads(model_type, manifests) if ported and not prefix else [] for entry in downloads: argv += ["--download", "{0}={1}={2}".format(entry["sha256"], entry["size"], entry["url"])] if downloads: - argv += ["--downloads-dir", str(downloads_dir if downloads_dir is not None else downloads_root())] + if fresh: + support_dir = safe_path(downloads_dir) if downloads_dir is not None else safe_path(local) / "support" + if support_dir == safe_path(local) or not support_dir.is_relative_to(safe_path(local)): + raise FetchError("invalid_arguments", "Managed support files must stay beneath the reviewed local destination.", "Choose a support folder inside --local-dir.") + else: + support_dir = Path(downloads_dir) if downloads_dir is not None else downloads_root() + argv += ["--downloads-dir", str(support_dir)] if hf_cache: argv += ["--cache-dir", str(hf_cache)] if local is not None: argv += ["--local-dir", str(local)] + if fresh: + argv += ["--fresh-destination", "--capture-identities"] + if source.get("subfolder"): + argv += ["--source-subfolder", source["subfolder"]] slug = _UNSAFE.sub("-", "{0}--{1}".format( source["repo"].replace("/", "--"), source["file"] or (source.get("subfolder") or "snapshot").replace("/", "--") )).strip("-.")[:160] plan = { "repo": source["repo"], "revision": source["revision"], "file": source["file"], + "additional_files": extra, "fresh_destination": fresh, + "downloads_dir": str(support_dir) if support_dir is not None else None, "subfolder": source.get("subfolder"), "base": {"repo": recipe["base"], "revision": recipe["base_revision"]} if recipe else None, "cache_dir": str(hf_cache) if hf_cache else None, @@ -109,12 +141,49 @@ def plan_fetch(text, revision=None, file=None, hf_cache=None, local_dir=None, py "allow_patterns": allow_patterns, "slug": slug, "argv": argv, "network": ["huggingface.co"], } + dependencies = {repo: {"repo": repo, "revision": None, "files": list(names)} for repo, names in sorted(requires.items())} + if recipe: + dependencies[recipe["base"]] = {"repo": recipe["base"], "revision": recipe["base_revision"], "files": []} + plan["required_dependencies"] = list(dependencies.values()) if requires: plan["requires"] = {repo: list(names) for repo, names in sorted(requires.items())} if downloads: plan["downloads"] = [dict(entry) for entry in downloads] plan["network"] = plan["network"] + sorted({entry["url"].split("/")[2] for entry in downloads}) - canonical = json.dumps(plan, sort_keys=True, separators=(",", ":")) + if storage_root is not None: + if not fresh: + raise FetchError("invalid_arguments", "Storage admission requires an immutable managed destination.", + "Resolve the commit and pass --local-dir without --hf-cache.") + try: + storage = fetch_storage.inspect(plan, storage_root) + except fetch_storage.StorageError as error: + raise FetchError(error.code, str(error), "Inspect the registered source receipt; preserve existing files.") from error + except (OSError, ValueError, KeyError, TypeError) as error: + raise FetchError("storage_invalid", str(error), "Repair the storage index without replacing model files.") from error + if storage.get("local_dir"): + previous = plan["local_dir"] + plan["local_dir"] = storage["local_dir"] + argv[argv.index("--local-dir") + 1] = storage["local_dir"] + if support_dir is not None: + plan["downloads_dir"] = str(Path(storage["local_dir"]) / Path(support_dir).relative_to(previous)) + argv[argv.index("--downloads-dir") + 1] = plan["downloads_dir"] + plan["storage"] = storage + if storage["mode"] == "reuse": + plan["argv"] = [] + plan["network"] = [] + if storage["mode"] == "download": + from .convert import cached_snapshot + cached = cached_snapshot(source["repo"], revision=source["revision"]) + if cached is not None: + raise FetchError("source_already_cached", "This revision already has a Hugging Face cache snapshot at {0}.".format(cached), + "Scan or register that cache and use its existing source; inspect incomplete files before retrying.") + # Approval binds the source, recipe and filesystem/network action. Admission + # state is independently rechecked under the lock and must not invalidate a + # saved source approval merely because its own first launch registered it. + approval = {key: value for key, value in plan.items() if key != "storage"} + if plan.get("storage", {}).get("mode") == "reuse": + approval["reuse"] = {key: plan["storage"][key] for key in ("receipt", "fetch_preview_hash")} + canonical = json.dumps(approval, sort_keys=True, separators=(",", ":")) plan["preview_hash"] = hashlib.sha256(canonical.encode("utf-8")).hexdigest() return plan @@ -137,32 +206,70 @@ def start_fetch(plan, receipts_dir=None, confirm=False, preview_hash=None, spawn if preview_hash != plan["preview_hash"]: raise FetchError("preview_stale", "The supplied preview hash does not match this fetch plan.", "Re-run intake fetch without --confirm and review the fresh plan.") + if plan.get("storage"): + try: + with fetch_storage.admission(plan) as index: + if plan["storage"]["mode"] == "reuse": + return fetch_storage.reuse_outcome(plan) + return _launch_fetch(plan, receipts_dir, spawn, pid_alive, module_present, now, env, index) + except fetch_storage.StorageError as error: + raise FetchError(error.code, str(error), "Review a fresh preview before retrying; preserve the registered source.") from error + except (OSError, ValueError, KeyError, TypeError) as error: + raise FetchError("storage_invalid", str(error), "Inspect the storage index and source receipt before retrying.") from error + return _launch_fetch(plan, receipts_dir, spawn, pid_alive, module_present, now, env) + + +def _launch_fetch(plan, receipts_dir, spawn, pid_alive, module_present, now, env, index=None): + if index is not None: + from .convert import cached_snapshot + if cached_snapshot(plan["repo"], revision=plan["revision"]) is not None: + raise FetchError("source_already_cached", "This revision now exists in the Hugging Face cache.", "Use the existing cache source instead of creating another copy.") missing = (module_present or _default_module_present)(FETCH_MODULES) if missing: raise FetchError("runtime_not_installed", "Downloads need {0} in this interpreter.".format(", ".join(missing)), "Run mlx-agent from the workbench .venv; fetch never installs runtimes.") + if plan.get("fresh_destination"): + destination = safe_path(plan["local_dir"]) + if destination.exists(): + raise FetchError("destination_exists", "The managed download destination already exists.", "Choose a fresh destination; existing files are never replaced.") root = receipts_root(receipts_dir, kind=FETCH_RECEIPT_KIND) - receipt_path = root / "{0}.json".format(plan["slug"]) + slug = plan["slug"] + ("-" + uuid.uuid4().hex if plan.get("fresh_destination") else "") + receipt_path = root / "{0}.json".format(slug) existing = _read_json(receipt_path) if existing and not existing.get("completed_at") and isinstance(existing.get("pid"), int) \ and pid_alive(existing["pid"]) and not Path(existing.get("marker", "")).exists(): raise FetchError("job_in_progress", "A download of {0} is still running.".format(plan["repo"]), "Wait for it to finish (intake status).") root.mkdir(parents=True, exist_ok=True) - marker = root / "{0}.done.json".format(plan["slug"]) + marker = root / "{0}.done.json".format(slug) if marker.exists(): marker.unlink() - log_path = root / "{0}.log".format(plan["slug"]) + log_path = root / "{0}.log".format(slug) + started_at = now() + proof_token = uuid.uuid4().hex if plan.get("fresh_destination") else None argv = list(plan["argv"]) + ["--marker", str(marker)] - pid = (spawn or spawn_with_env)(argv, str(log_path), backend_environment(env)) + if proof_token: + argv += ["--proof-token", proof_token, "--preview-hash", plan["preview_hash"], "--started-at", started_at] receipt = { "schema_version": "1.0", "kind": FETCH_RECEIPT_KIND, "repo": plan["repo"], "revision": plan["revision"], "file": plan["file"], "subfolder": plan.get("subfolder"), - "local_dir": plan["local_dir"], "cache_dir": plan["cache_dir"], "slug": plan["slug"], "argv": argv, "pid": pid, - "log_path": str(log_path), "marker": str(marker), "started_at": now(), + "additional_files": plan.get("additional_files", []), "fresh_destination": plan.get("fresh_destination", False), "proof_token": proof_token, + "downloads_dir": plan.get("downloads_dir"), "downloads": plan.get("downloads", []), + "required_dependencies": plan.get("required_dependencies", []), + "local_dir": plan["local_dir"], "cache_dir": plan["cache_dir"], "slug": slug, "argv": argv, "pid": None, + "log_path": str(log_path), "marker": str(marker), "started_at": started_at, "preview_hash": plan["preview_hash"], "completed_at": None, "exit_status": None, } + for key in ("allow_patterns", "ignore_patterns", "base", "requires"): + if key in plan: + receipt[key] = plan[key] + if index is not None: + # Publish intent before launching. A crash cannot lose the only pointer + # to a potentially running worker and admit a duplicate source. + _write_receipt(root, receipt, receipt_path.name) + fetch_storage.register(index, plan, receipt_path) + receipt["pid"] = (spawn or spawn_with_env)(argv, str(log_path), backend_environment(env)) _write_receipt(root, receipt, receipt_path.name) return {"status": "started", "receipt": receipt} @@ -181,14 +288,26 @@ def status_fetch(receipts_dir=None, pid_alive=_pid_alive): entry = { "receipt": str(path), "repo": receipt.get("repo"), "revision": receipt.get("revision"), "file": receipt.get("file"), "subfolder": receipt.get("subfolder"), "local_dir": receipt.get("local_dir"), + "additional_files": receipt.get("additional_files", []), "preview_hash": receipt.get("preview_hash"), "files": [], + "downloads_dir": receipt.get("downloads_dir"), "downloads": receipt.get("downloads", []), + "required_dependencies": receipt.get("required_dependencies", []), "state": "failed", + "processes_quiescent": not pid_alive(receipt["pid"]), "path": None, "log_path": receipt.get("log_path"), "started_at": receipt.get("started_at"), "completed_at": None, } marker = _read_json(receipt.get("marker", "")) if marker: - entry["state"] = "done" if marker.get("exit_status") == "done" else "failed" - entry["path"] = marker.get("path") + bound = not receipt.get("fresh_destination") or all(marker.get(key) == receipt.get(key) for key in ( + "repo", "revision", "file", "subfolder", "additional_files", "local_dir", "preview_hash", "proof_token", "started_at", "downloads_dir", "downloads")) + if receipt.get("fresh_destination") and bound and marker.get("exit_status") == "done": + try: + completed_fetch(path) + except (OSError, ValueError, KeyError, TypeError): + bound = False + entry["state"] = "done" if marker.get("exit_status") == "done" and bound else "failed" + entry["files"] = marker.get("files", []) if bound else [] + entry["path"] = marker.get("path") if bound else None entry["completed_at"] = marker.get("finished_at") elif pid_alive(receipt["pid"]): entry["state"] = "running" diff --git a/packages/codex/mlx-agent/src/mlx_agent/intake_source.py b/packages/codex/mlx-agent/src/mlx_agent/intake_source.py index a89e393..56cc62d 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/intake_source.py +++ b/packages/codex/mlx-agent/src/mlx_agent/intake_source.py @@ -33,8 +33,8 @@ def validate_revision(text): return text -def validate_file(text): - if not isinstance(text, str) or not text.lower().endswith(".gguf"): +def validate_file(text, allow_support=False): + if not isinstance(text, str) or (not allow_support and not text.lower().endswith(".gguf")): raise IntakeSourceError("Only .gguf files can be picked: {0!r}".format(text)) parts = text.split("/") if not all(_FILE_SEGMENT.fullmatch(part) for part in parts): diff --git a/packages/codex/mlx-agent/src/mlx_agent/jit_serve.py b/packages/codex/mlx-agent/src/mlx_agent/jit_serve.py index b3f5843..7095bbb 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/jit_serve.py +++ b/packages/codex/mlx-agent/src/mlx_agent/jit_serve.py @@ -15,6 +15,7 @@ import os import re import selectors +import secrets import signal import socket import subprocess @@ -29,71 +30,22 @@ if not __package__: sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from mlx_agent import chat_completions, responses_api -from mlx_agent.contextfit import CONTEXT_MAX, CONTEXT_MIN, extract_architecture, kv_cache_bytes from mlx_agent.messages_api import (MessagesRequestError, StreamTranslator, WorkerResponseError, error_body, from_chat_response, to_chat_request) from mlx_agent.transactions import _atomic_in_directory +from mlx_agent.residency import MemoryRegistry, MemoryAdmissionError +from mlx_agent import allocator_cache +from mlx_agent.inference_telemetry import InferenceTelemetry +from mlx_agent import inference_defaults +from mlx_agent.compute import ComputeBusy, ComputeLease, ExecutionAdmission, group_members, process_identity, process_birth_identity +from mlx_agent.identity_pass import recheck_bound_identity +from mlx_agent.memory_policy import (PolicyRejected, enforce_configure, execution_wait_seconds, reject_cache_outside_tasks, + release_reason, releases_after_request, reservation, validate as validate_memory_policy) MAX_BODY = 16 * 1024 * 1024 MAX_REQUESTS = 32 STORED_RESPONSES = 64 - - -STRATA_CONTEXT = "Strata JIT admission already includes the KV cache at --strata-context-tokens." - - -def validate_memory_policy(policy=None): - defaults = {"idle_timeout_seconds": 0, "keep_loaded": False, "minimum_headroom_gb": None} - if policy is None: - return defaults - if not isinstance(policy, dict) or set(policy) - set(defaults) - {"context_tokens", "unload_under_pressure", "model_memory_budget_gb"}: - raise ValueError("Unknown memory policy fields.") - result = dict(defaults, **policy) - # Null and absent both mean no KV term; policies without a context keep their existing form. - context = result.pop("context_tokens", None) - pressure = result.pop("unload_under_pressure", False) - budget = result.pop("model_memory_budget_gb", None) - if budget is not None: - if type(budget) not in (int, float) or not math.isfinite(budget) or not 1 <= budget <= 1024: - raise ValueError("Model memory budget must be a finite value from 1 to 1024 GB.") - result["model_memory_budget_gb"] = budget - if result["minimum_headroom_gb"] is None: - result["minimum_headroom_gb"] = 2 - idle, keep, reserve = (result[key] for key in defaults) - if type(idle) is not int or not 0 <= idle <= 86400: - raise ValueError("Idle timeout must be an integer between 0 and 86400 seconds.") - if type(keep) is not bool: - raise ValueError("Keep loaded must be a boolean.") - if reserve is not None and (type(reserve) not in (int, float) or not math.isfinite(reserve) or not 0 <= reserve <= 1024): - raise ValueError("Headroom reserve must be a finite value between 0 and 1024 GB.") - if type(pressure) is not bool: - raise ValueError("Unload under pressure must be a boolean.") - if pressure: - if reserve is None or keep: - raise ValueError("Unload under pressure requires a headroom reserve and cannot be combined with keep loaded.") - result["unload_under_pressure"] = True - if context is not None: - if type(context) is not int or not CONTEXT_MIN <= context <= CONTEXT_MAX: - raise ValueError("Context tokens must be an integer between {} and {}.".format(CONTEXT_MIN, CONTEXT_MAX)) - if reserve is None: - raise ValueError("Context tokens require a headroom reserve.") - result["context_tokens"] = context - return result - - -def _kv_cache_bytes(local_path, context_tokens): - """KV cache bytes at the context from the local config.json, or None when its architecture is unknown.""" - try: - location = Path(local_path) / "config.json" - if location.stat().st_size > 1024 * 1024: - return None - config = json.loads(location.read_text(encoding="utf-8")) - except (OSError, ValueError): - return None - if not isinstance(config, dict): - return None - architecture = extract_architecture(config) or extract_architecture(config.get("text_config")) - return kv_cache_bytes(architecture, context_tokens) +DRAIN_TIMEOUT_SECONDS = 30 def available_memory_bytes(): @@ -118,6 +70,20 @@ def __init__(self, status, code, message): self.status, self.code = status, code +def public_model_name(local_path): + """Path-free name of a local model: its Hub repository for cache snapshots, else its directory.""" + local = Path(local_path) + if local.parent.name == "snapshots" and local.parent.parent.name.startswith("models--"): + return local.parent.parent.name[len("models--"):].replace("--", "/") + return local.name + + +def model_aliases(config): + """Request names accepted for an endpoint's one configured local model.""" + return {config["model"], config["local_path"], "default_model", Path(config["local_path"]).name, + public_model_name(config["local_path"])} + + def model_fingerprint(path): """File identity manifest, deliberately not a model-quality assessment.""" root = Path(path) @@ -142,13 +108,31 @@ def __init__(self, config): self.condition = threading.Condition() self.process = None self.worker_port = None + self.private_endpoint = None self.worker_argv = None self.model_state = "unloaded" self.active_requests = 0 + self.inference_telemetry = InferenceTelemetry() + defaults = config.get('request_defaults', {}) + if not isinstance(defaults, dict) or set(defaults) - {'system_prompt', 'temperature', 'top_p'}: + raise ValueError('Invalid request defaults.') + self.request_defaults = inference_defaults.validate(defaults.get('system_prompt'), defaults.get('temperature'), defaults.get('top_p')) + self.execution = ExecutionAdmission("serve:" + config.get("model", config["local_path"]), config.get("compute_state_dir"), + shared=lambda: self.memory_registry.shared_execution_enabled()) + self.worker_group = None + self.worker_identity = None + self.worker_birth_identity = None + self._persisted_worker = None + self._persisted_worker_start = None + self.execution_unresolved = False self.last_error = None + self.memory_guard_error = None + self.last_memory_failure = None self.closed = False + self.shutdown_requested = False self.log = None self.memory_policy = validate_memory_policy(config.get("memory_policy")) + reject_cache_outside_tasks(self.memory_policy, config.get("runtime")) self.memory_check = None self.resident_memory_check = None self.request_blocked_reason = None @@ -162,6 +146,15 @@ def __init__(self, config): self.owned_session = None self.clock = time.monotonic self.memory_probe = available_memory_bytes + self.memory_registry = MemoryRegistry(config.get('memory_state_dir')) + self.memory_token = secrets.token_hex(16) + self.memory_reservation = None + self.worker_memory = None + self.cache_control_active = False + self.workspace_bytes = 1_500_000_000 + self.growth_bytes = 0 + self.memory_materialized = False + self.memory_transition_blocked = False def _persist(self): state_path = self.config.get("state_path") @@ -170,12 +163,61 @@ def _persist(self): if path.is_symlink(): raise OSError("Refusing a symbolic-link worker state file.") state = {"gateway_pid": os.getpid(), "worker_pid": self.process.pid if self.process else None, - "worker_argv": self.worker_argv, "model_state": self.model_state} + "worker_argv": self.worker_argv, "model_state": self.model_state, + "last_memory_failure": self.last_memory_failure} + if self.process: + from mlx_agent.serve import _pid_start + if self._persisted_worker is not self.process or self._persisted_worker_start is None: + self._persisted_worker = self.process + self._persisted_worker_start = _pid_start(self.process.pid) + state["worker_started_at"] = self._persisted_worker_start + else: + self._persisted_worker = None + self._persisted_worker_start = None _atomic_in_directory(path.parent, path.name, json.dumps(state).encode(), 0o600) + def _record_memory_failure(self, source, reason, details=None): + from mlx_agent.memory_diagnostics import memory_decision + with self.condition: + worker = self.process + data = dict(details or {}) + allocation = (self.memory_reservation or {}).get('allocation') or {} + for field, key in (('registry_resident_bytes', 'resident_bytes'), + ('workspace_bytes', 'workspace_bytes'), ('growth_bytes', 'growth_bytes'), + ('pending_bytes', 'reserved_bytes'), ('headroom_bytes', 'headroom_bytes')): + if field not in data: + data[field] = allocation.get(key) + owner = allocation.get('owner') + if isinstance(owner, (list, tuple)) and len(owner) == 2 and isinstance(owner[1], str): + data['registry_owner_identity_sha256'] = hashlib.sha256(owner[1].encode()).hexdigest() + telemetry = self.worker_memory or {} + for field in ('cache_bytes', 'active_bytes'): + data[field] = telemetry.get(field) + bound = allocation.get('worker') if isinstance(allocation.get('worker'), dict) else {} + matches = worker is not None and bound.get('pid') == worker.pid + self.last_memory_failure = memory_decision(source, reason, data, + pid=worker.pid if worker else None, + pgid=self.worker_group if self.worker_group is not None else (bound.get('pgid') if matches else None), + identity=self.worker_identity if self.worker_identity is not None else (bound.get('identity') if matches else None)) + try: + self._persist() + except OSError: + self.last_memory_failure['persistence_error'] = 'initial_state_write_failed' + def _refresh(self): if self.process and self.process.poll() is not None and self.model_state == "loaded": + if self.worker_group is not None: + try: + self._stop_group() + except (OSError, ValueError, subprocess.SubprocessError) as error: + self.model_state = "failed" + self.last_error = str(error) + self._persist() + return self.process = None + if self.private_endpoint is not None: + self.private_endpoint.close() + self.private_endpoint = None if self.config.get("runtime") == "strata": from mlx_agent.process_tree import session_children self.strata_children.update(session_children(self.owned_session)) @@ -192,6 +234,7 @@ def _refresh(self): return self.model_state = "unloaded" self.memory_budget_pending = False + self._release_memory() self._persist() def status(self): @@ -199,18 +242,35 @@ def status(self): self._refresh() result = {"model_state": self.model_state, "active_requests": self.active_requests, "worker_pid": self.process.pid if self.process and self.process.poll() is None else None, + "inference_telemetry": self.inference_telemetry.snapshot(), + "request_defaults": inference_defaults.summary(self.request_defaults), "worker_port": self.worker_port if self.model_state == "loaded" else None, "last_error": self.last_error, "memory_policy": dict(self.memory_policy), - "memory_check": self.memory_check, "load_blocked_reason": self.load_blocked_reason, + "execution": {"active_requests": self.execution.users, "waiting_requests": self.execution.waiting}, + "memory_check": self.memory_check, "last_memory_failure": self.last_memory_failure, "load_blocked_reason": self.load_blocked_reason, + "memory_reservation": self.memory_reservation, "worker_memory": self.worker_memory, + "allocator_cache": self._allocator_cache_status(), "resident_memory_check": self.resident_memory_check, "request_blocked_reason": self.request_blocked_reason, - "last_unload_reason": self.last_unload_reason} + "last_unload_reason": self.last_unload_reason, + "api_key_sha256": self.config.get("api_key_sha256", self.config.get("access_key_sha256"))} + if self.config.get("private_worker"): + result["worker_transport"] = "inherited-unix-v1" if self.config.get("runtime") == "strata": result.update(memory_allocation=self.config.get("strata_memory_allocation"), strata_decoding=self.config.get("strata_decoding"), memory_budget_pending=self.memory_budget_pending) return result + def _allocator_cache_status(self): + return {'supported': False, 'available': False, 'pending': False, + 'control_path': None, 'policy_fields': [], 'reclaim_modes': [], 'active': False, + 'configured_policy': allocator_cache.from_memory(self.memory_policy), + 'applied_policy': None, 'last_reclaim': None, 'error': None} + + def reclaim_cache(self): + raise GatewayError(400, 'cache_control_unavailable', 'This runtime does not expose allocator cache controls.') + def _strata_speculation(self): if "strata_decoding" in self.config: return self.config["strata_decoding"] == "mtp" @@ -222,22 +282,31 @@ def configure(self, changes): with self.condition: try: policy = validate_memory_policy(dict(self.memory_policy, **changes)) + enforce_configure(policy, self.config.get("runtime"), changes) + except PolicyRejected as error: + raise GatewayError(400, error.code, str(error)) from error except (ValueError, TypeError) as error: raise GatewayError(400, "invalid_policy", str(error)) from error - if self.config.get("runtime") == "strata" and "context_tokens" in policy: - raise GatewayError(400, "invalid_policy", STRATA_CONTEXT) - if self.config.get("runtime") != "strata" and "model_memory_budget_gb" in policy: - raise GatewayError(400, "invalid_policy", "Model memory budgets currently require Strata.") config = dict(self.config, memory_policy=policy) budget_changed = policy.get("model_memory_budget_gb") != self.memory_policy.get("model_memory_budget_gb") - if budget_changed: + if budget_changed and self.config.get("runtime") == "strata": if self.model_state in ("loading", "unloading"): raise GatewayError(409, "model_busy", "Finish the current model transition before changing its budget.") - from mlx_agent.strata_runtime import StrataError, read_model, memory_allocation + from mlx_agent.strata_runtime import (StrataError, memory_allocation, memory_estimate, + memory_growth_allowance, read_model) budget = policy.get("model_memory_budget_gb") try: - allocation = None if budget is None else memory_allocation(read_model(config["local_path"]), budget, - config.get("strata_context_tokens", 131072), self._strata_speculation()) + model = read_model(config["local_path"]) + context = config.get("strata_context_tokens", 131072) + speculation = self._strata_speculation() + allocation = None if budget is None else memory_allocation(model, budget, context, speculation) + if allocation is not None: + capacity = 0 if allocation["mode"] == "resident" else allocation["expert_memory_gb"] + estimate = allocation["estimated_resident_bytes"] + else: + capacity = config.get("strata_expert_memory_gb") + estimate = memory_estimate(model, capacity, context, speculation) + growth = memory_growth_allowance(model, context, capacity, speculation) except StrataError as error: raise GatewayError(400, error.code, str(error)) from error argv, old = [], iter(config["worker_argv"]) @@ -250,7 +319,9 @@ def configure(self, changes): argv += ["--memory-budget-gb", str(budget)] elif config.get("strata_expert_memory_gb") is not None: argv += ["--expert-memory-gb", str(config["strata_expert_memory_gb"])] - config.update(worker_argv=argv, strata_memory_allocation=allocation) + config.update(worker_argv=argv, strata_memory_allocation=allocation, + strata_memory_estimate_bytes=estimate, strata_memory_growth_bytes=growth) + self._set_memory_headroom(max(policy['minimum_headroom_gb'] or 0,self.memory_policy['minimum_headroom_gb'] or 0)) if config.get("config_path"): path = Path(config["config_path"]) try: @@ -261,45 +332,96 @@ def configure(self, changes): raise GatewayError(503, "policy_not_saved", str(error)) from error self.config.update(config) self.memory_policy = policy - if budget_changed and self.model_state == "loaded": + self._set_memory_headroom(policy['minimum_headroom_gb'] or 0) + if budget_changed and self.config.get("runtime") == "strata" and self.model_state == "loaded": self.memory_budget_pending = True self.policy_revision += 1 return self.status() - def _check_memory(self): + def _match_serving_plan(self): + # serve imports the identity pass, so ServeError is imported when the pass runs. + from mlx_agent.serve import ServeError + try: + recheck_bound_identity(self.config) + except ServeError as error: + raise GatewayError(503, error.code, str(error)) from error + + def _check_memory(self, *, weight_bytes=None): with self.condition: - reserve = self.memory_policy["minimum_headroom_gb"] - context = self.memory_policy.get("context_tokens") self.load_blocked_reason = None - if reserve is None: - return - weights = sum(item.stat().st_size for item in Path(self.config["local_path"]).rglob("*") - if item.is_file() and item.suffix in (".safetensors", ".npz", ".bin", ".gguf")) - if weights and self.config.get("adapter_path") is not None: - weights += self.config["adapter_identity"]["adapters.safetensors"]["bytes"] - kv = 0 if context is None else _kv_cache_bytes(self.config["local_path"], context) - available = self.memory_probe() - required = math.ceil(weights * 1.10 + kv + 1.5e9 + reserve * 1e9) if weights and kv is not None else None - if self.config.get("runtime") == "strata": - from mlx_agent.strata_runtime import read_model, memory_estimate, memory_allocation - model = read_model(self.config["local_path"]) - context = self.config.get("strata_context_tokens", 131072) - budget = self.memory_policy.get("model_memory_budget_gb") - size = (memory_allocation(model, budget, context, self._strata_speculation())["estimated_resident_bytes"] - if budget is not None else memory_estimate(model, self.config.get("strata_expert_memory_gb"), - context, self._strata_speculation())) - required = math.ceil(size + reserve * 1e9) - with self.condition: - self.memory_check = {"available_bytes": available, "required_available_bytes": required, - "captured_at": time.time(), "estimated": True} - if type(available) is not int or available < 0 or required is None: - self.load_blocked_reason = ("The local config.json does not give the KV cache size for the policy context." - if kv is None else "Memory headroom or model weight size is unavailable.") - raise GatewayError(503, "memory_unknown", self.load_blocked_reason) - if available < required: - self.load_blocked_reason = "Insufficient memory headroom for estimated weights, {}runtime allowance and reserve.".format( - "KV cache, " if context is not None else "") - raise GatewayError(503, "insufficient_headroom", self.load_blocked_reason) + policy = dict(self.memory_policy) + config = dict(self.config) + outcome = reservation(policy, config, weight_bytes=weight_bytes) + if outcome is None: + self.load_blocked_reason = "Model or context memory estimate is unavailable." + self._record_memory_failure('cold_admission', 'memory_unknown') + raise GatewayError(503, "memory_unknown", self.load_blocked_reason) + self.workspace_bytes = outcome["workspace_bytes"] + self.growth_bytes = outcome["growth_bytes"] + from mlx_agent.memory_policy import model_key + registry_model_key = model_key(self.config) + try: + self.memory_reservation = self.memory_registry.reserve(self.memory_token, registry_model_key, + outcome["reserve_bytes"], outcome["workspace_bytes"], + lambda: math.ceil((self.memory_policy["minimum_headroom_gb"] or 0) * 1e9), self.memory_probe, + growth_bytes=outcome["growth_bytes"]) + self.memory_check = self.memory_reservation + except MemoryAdmissionError as error: + self.memory_check = error.details + self._record_memory_failure('cold_admission', error.code, dict(error.details, + workspace_bytes=outcome['workspace_bytes'], growth_bytes=outcome['growth_bytes'])) + self.load_blocked_reason = str(error) + raise GatewayError(503, error.code, str(error)) from error + + def _release_memory(self): + if self.memory_reservation is not None: + self.memory_registry.release(self.memory_token) + self.memory_reservation = None + self.worker_memory = None + self.memory_materialized = False + self.memory_transition_blocked = False + + def _set_memory_headroom(self, gigabytes): + if self.memory_reservation is not None: + try: + self.memory_reservation = self.memory_registry.set_headroom(self.memory_token, math.ceil(gigabytes * 1e9)) + except MemoryAdmissionError as error: + raise GatewayError(503, error.code, str(error)) from error + + def _launching_memory(self): + if self.memory_reservation is not None: + self.memory_reservation = self.memory_registry.launching(self.memory_token) + + def _bind_memory(self, process, identity): + if self.memory_reservation is not None: + self.memory_reservation = self.memory_registry.bind_worker( + self.memory_token, process.pid, identity, os.getpgid(process.pid)) + + def _materialized_memory(self): + # Readiness alone does not prove that an asynchronous model loader has + # allocated its weights. Keep cold allocations reserved until output. + if self.memory_reservation is not None and not self.memory_materialized and not self.memory_transition_blocked: + try: + self.memory_reservation = self.memory_registry.settle(self.memory_token, + workspace_bytes=self.workspace_bytes + self.growth_bytes) + except MemoryAdmissionError as error: + if error.code != "memory_registry_busy": + raise GatewayError(503, error.code, str(error)) from error + self.memory_transition_blocked = True + self.last_error = "Memory reservation remains pending: " + str(error) + return + self.memory_materialized = True + self.last_error = None + + def _reserve_workspace(self, extra_bytes=0): + try: + self.memory_check = self.memory_registry.reserve_workspace( + self.memory_token, self.workspace_bytes + extra_bytes, self.memory_probe) + self.memory_reservation = self.memory_check + except MemoryAdmissionError as error: + self.memory_check = error.details + self._record_memory_failure('workspace_admission', error.code, error.details) + raise GatewayError(503, error.code, str(error)) from error def _resident_check(self, policy, available, scope): known = type(available) is int and available >= 0 @@ -316,6 +438,16 @@ def _resident_check(self, policy, available, scope): return None def _check_resident_memory(self, policy): + try: + budget = self.memory_registry.snapshot().get('agent_budget') + except MemoryAdmissionError as error: + self._record_memory_failure('resident_guard', error.code, error.details) + raise GatewayError(503, error.code, str(error)) from error + if budget is not None and not budget.get('within_budget'): + self._record_memory_failure('resident_guard', 'agent_memory_budget_exceeded', + dict(budget.get('allocations', {}).get(self.memory_token, {}), agent_budget=budget)) + raise GatewayError(503, 'agent_memory_budget_exceeded', + 'The shared agent memory budget is unavailable or exhausted.') if not policy.get("unload_under_pressure"): return # The admission already holds a request lease, so an idle reaper cannot @@ -325,28 +457,37 @@ def _check_resident_memory(self, policy): error = self._resident_check(policy, available, "request") self.request_blocked_reason = str(error) if error else None if error: + self._record_memory_failure('resident_guard', error.code, + {'available_bytes': available, 'headroom_bytes': math.ceil(policy['minimum_headroom_gb'] * 1e9)}) raise error - def acquire(self): + def acquire(self, cancelled=lambda: False): with self.condition: if not self.condition.wait_for(lambda: self.model_state != "unloading" or self.closed, timeout=10): raise GatewayError(503, "model_unloading", "Model unload has not finished.") if self.closed: raise GatewayError(503, "endpoint_stopping", "Endpoint is stopping.") self._refresh() + if self.execution_unresolved: + raise GatewayError(503, "worker_unavailable", "The previous backend execution has not stopped.") if self.memory_budget_pending: raise GatewayError(503, "model_reconfiguring", "The model is applying a memory budget; retry when it is idle.") if self.active_requests >= MAX_REQUESTS: raise GatewayError(503, "endpoint_busy", "Too many inference requests.") self.active_requests += 1 + self.memory_transition_blocked = False self.activity_revision += 1 policy = dict(self.memory_policy) self.request_blocked_reason = None - starter = self.model_state not in ("loaded", "loading") - if starter: - self.model_state = "loading" - self.last_error = None + admitted = False try: + self.execution.acquire(execution_wait_seconds(policy), lambda: self.closed or cancelled()) + admitted = True + with self.condition: + starter = self.model_state not in ("loaded", "loading") + if starter: + self.model_state = "loading" + self.last_error = None if starter: self._start() else: @@ -356,41 +497,22 @@ def acquire(self): with self.condition: if self.closed or self.model_state != "loaded": raise GatewayError(503, "model_load_failed", self.last_error or "Model is not ready.") + self.execution.bind(self.process.pid) self._check_resident_memory(policy) with self.condition: if self.closed or self.model_state != "loaded": raise GatewayError(503, "endpoint_stopping", "Endpoint is stopping.") return self.worker_port - except BaseException: - self.release() + except BaseException as error: + self.release(compute=admitted) + if isinstance(error, MemoryAdmissionError): + raise GatewayError(503, error.code, str(error)) from error + if isinstance(error, ComputeBusy): + raise GatewayError(503, "compute_busy", str(error)) from error + if isinstance(error, InterruptedError): + raise GatewayError(503, "execution_cancelled", str(error)) from error raise - def _check_adapter(self): - argv = self.config["worker_argv"] - path = self.config.get("adapter_path") - if path is None and "--adapter-path" not in argv: - return - from mlx_agent.lora import adapter_identity - if (not isinstance(path, str) or "--adapter-path" not in argv - or argv.index("--adapter-path") + 1 >= len(argv) - or argv[argv.index("--adapter-path") + 1] != path - or not self.config.get("adapter_identity") - or adapter_identity(path) != self.config["adapter_identity"]): - raise GatewayError(503, "adapter_changed", "Adapter files changed or have no reviewed identity. Stop and review a fresh serve plan.") - - def _check_training_receipt(self): - binding = self.config.get("training_binding") - if binding is None: - return - try: - from mlx_agent.training_artifacts import read_trained_adapter - _, current = read_trained_adapter(binding["training_receipt"]) - if current == binding: - return - except (OSError, ValueError, TypeError, KeyError): - pass - raise GatewayError(503, "training_receipt_changed", "The training receipt or its pinned artifacts changed. Stop and review a fresh serve plan.") - def _start(self): try: if self.strata_children: @@ -398,47 +520,118 @@ def _start(self): self.strata_children = remaining(self.strata_children) if self.strata_children: raise GatewayError(503, "model_unload_failed", "A previous Strata engine is still releasing memory.") - if model_fingerprint(self.config["local_path"]) != self.config["fingerprint"]: - raise GatewayError(503, "model_changed", "Model files changed. Stop and review a fresh serve plan.") - self._check_training_receipt() - self._check_adapter() + self._match_serving_plan() self._check_memory() - with socket.socket() as reservation: - reservation.bind(("127.0.0.1", 0)) - port = reservation.getsockname()[1] + self._launching_memory() + private = self.config.get("private_worker") + if private: + from mlx_agent.private_serve import PrivateEndpoint + self.private_endpoint = PrivateEndpoint() + port = 0 + else: + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + port = reservation.getsockname()[1] argv = [str(port) if value == "{worker_port}" else value for value in self.config["worker_argv"]] + extra = {} + if private: + from mlx_agent.private_serve import worker_command + descriptor = self.private_endpoint.listener.fileno() + argv = worker_command(argv, self.config["local_path"], descriptor) + extra["pass_fds"] = (descriptor,) environment = dict(os.environ, HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", HF_DATASETS_OFFLINE="1") - log = open(self.config["log_path"], "ab", buffering=0) if self.config.get("log_path") else subprocess.DEVNULL - with self.condition: - if self.closed: - raise GatewayError(503, "endpoint_stopping", "Endpoint is stopping.") - # Inherit the gateway's session: serve stop signals the whole - # owned group, including a worker when the gateway is killed. - self.process = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=log, - stderr=subprocess.STDOUT, env=environment) - self.log = log - self.worker_port, self.worker_argv = port, argv - self._persist() - process = self.process - opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + splash = self.config.get("runtime") == "splash" + if splash: + # Splash execs its server over this worker, so it watches the gateway itself. + environment.pop("SPLASH_API_KEY", None) + environment["SPLASH_APP_PID"] = str(os.getpid()) + if private or self.config.get("api_key_sha256") is not None: + from mlx_agent.protected_worker import command, WORKER_DIGEST + self.worker_key = secrets.token_urlsafe(32) + if splash: + # Splash checks its own key on every route but /health, /ready and its chat page. + environment["SPLASH_API_KEY"] = self.worker_key + else: + environment[WORKER_DIGEST] = hashlib.sha256(self.worker_key.encode()).hexdigest() + if not private: + argv = command(argv, self.config.get("runtime") or "mlx_lm") + from mlx_agent.owned_worker import command as owned_command + ready_read, ready_write = os.pipe() + gate_read, gate_write = os.pipe() + try: + argv = owned_command(argv, ready_write, gate_read) + extra["pass_fds"] = (*extra.get("pass_fds", ()), ready_write, gate_read) + log = open(self.config["log_path"], "ab", buffering=0) if self.config.get("log_path") else subprocess.DEVNULL + with self.condition: + if self.closed: + if log != subprocess.DEVNULL: + log.close() + raise GatewayError(503, "endpoint_stopping", "Endpoint is stopping.") + self.log = log + self.process = subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, env=environment, start_new_session=True, **extra) + self.worker_group = self.process.pid + if private: + self.private_endpoint.listener.close() + self.worker_port, self.worker_argv = (None if private else port), argv + self._persist() + process = self.process + os.close(ready_write) + ready_write = None + os.close(gate_read) + gate_read = None + with selectors.DefaultSelector() as selector: + selector.register(ready_read, selectors.EVENT_READ) + if not selector.select(5) or os.read(ready_read, 1) != b'R': + raise GatewayError(503, "model_load_failed", "Model worker startup was not acknowledged.") + self.execution.bind(process.pid) + self.worker_identity = process_identity(process.pid) + if splash: + self.worker_birth_identity = process_birth_identity(process.pid) + if not self.worker_birth_identity or os.getpgid(process.pid) != self.worker_group: + raise OSError("The owned model worker identity is unavailable.") + os.write(gate_write, b'G') + finally: + for descriptor in (ready_read, ready_write, gate_read, gate_write): + if descriptor is not None: + os.close(descriptor) + from mlx_agent.inference_auth import loopback_opener + opener = loopback_opener() readiness_seconds = self.config.get("worker_readiness_seconds", 60) deadline = time.monotonic() + readiness_seconds while time.monotonic() < deadline: if process.poll() is not None or self.closed: raise GatewayError(503, "model_load_failed", "Model worker exited before readiness.") try: - with opener.open("http://127.0.0.1:{}/v1/models".format(port), timeout=1) as response: - if response.status == 200: + if private: + from mlx_agent.private_serve import PRIVATE_PROTOCOL + connection = self.connection(timeout=1) + try: + connection.request("GET", "/_mlx/private", headers={"Authorization": "Bearer " + self.worker_key}) + response = connection.getresponse() + ready = response.status == 200 and response.getheader("X-MLX-Agent-Transport") == PRIVATE_PROTOCOL + response.read(1024) + finally: + connection.close() + if ready: break + else: + request = urllib.request.Request("http://127.0.0.1:{}/v1/models".format(port), + headers={"Authorization": "Bearer " + self.worker_key} if self.config.get("api_key_sha256") is not None else {}) + with opener.open(request, timeout=1) as response: + if response.status == 200: + break except OSError: time.sleep(0.1) else: raise GatewayError(503, "model_load_failed", "Model worker did not become ready in {} seconds.".format(readiness_seconds)) - if model_fingerprint(self.config["local_path"]) != self.config["fingerprint"]: - raise GatewayError(503, "model_changed", "Model files changed while loading.") - self._check_training_receipt() - self._check_adapter() + if splash: + # Splash's launcher execs its server over the owned worker: bind the server that answered. + self.worker_identity = process_identity(process.pid) + self.execution.bind(process.pid, refresh=True) + self._bind_memory(process,process_identity(process.pid)) + self._match_serving_plan() if self.config.get("runtime") == "strata": from mlx_agent.process_tree import descendants self.strata_children.update(descendants(process.pid)) @@ -465,15 +658,55 @@ def _start(self): raise failure from error raise GatewayError(503, "model_load_failed", str(failure)) from failure - def release(self): + def _idle_execution(self, lease): + process = self.process + if process is None: + return + try: + if self.execution_unresolved: + raise ComputeBusy("The upstream execution did not complete.") + if process.poll() is not None: + raise ComputeBusy("The model worker exited.") + members = {pid: process_identity(pid) for pid in group_members(process.pid)} + if not all(members.values()): + raise ComputeBusy("The idle backend group cannot be inspected.") + lease.release_idle_process_group(process.pid, members) + except (ComputeBusy, OSError, ValueError, subprocess.SubprocessError): + self.execution_unresolved = True + self._stop_worker() + with self.condition: + self.model_state = "unloaded" + self._persist() + + def release(self, compute=True): + try: + if compute: + self.execution.release(self._idle_execution) + finally: + self._release_request() + + def _release_request(self): with self.condition: self.active_requests -= 1 self.activity_revision += 1 if self.active_requests == 0: self.last_activity = self.clock() + release = self.active_requests == 0 and self.model_state == "loaded" and releases_after_request(self.memory_policy) + if release: + self.model_state = "unloading" self.condition.notify_all() + if release: + self._finish_unload("request_complete") + + def connection(self, timeout=120): + if self.private_endpoint is not None: + return self.private_endpoint.connection(timeout) + return http.client.HTTPConnection("127.0.0.1", self.worker_port, timeout=timeout) def _stop_worker(self): + if self.worker_group is not None: + self._stop_group() + return with self.condition: process = self.process if self.config.get("runtime") == "strata": @@ -506,42 +739,146 @@ def _stop_worker(self): if self.log not in (None, subprocess.DEVNULL): self.log.close() self.log = None + if self.private_endpoint is not None: + self.private_endpoint.close() + self.private_endpoint = None + self._release_memory() + + def _stop_group(self): + with self.condition: + process, group = self.process, self.worker_group + if process is not None and process.poll() is None: + if self.config.get("runtime") == "splash": + try: + owned = (self.worker_birth_identity is not None + and process_birth_identity(process.pid) == self.worker_birth_identity + and group == process.pid and os.getpgid(process.pid) == group) + except ProcessLookupError: + owned = False + if not owned: + raise OSError("The model worker identity changed; shutdown is blocked.") + elif self.worker_identity is not None and process_identity(process.pid) != self.worker_identity: + raise OSError("The model worker identity changed; shutdown is blocked.") + try: + process.terminate() + except ProcessLookupError: + pass + try: + process.wait(timeout=65 if self.config.get("runtime") == "strata" else 3) + except subprocess.TimeoutExpired: + try: + os.killpg(group, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait(timeout=3) + if group_members(group): + try: + os.killpg(group, signal.SIGKILL) + except ProcessLookupError: + pass + deadline = time.monotonic() + 3 + while group_members(group) and time.monotonic() < deadline: + time.sleep(.05) + if group_members(group): + raise OSError("The owned model process group has not stopped.") + with self.condition: + self.process = None + self.worker_group = self.worker_identity = self.worker_birth_identity = None + self.execution_unresolved = False + self.strata_children = {} + if self.log not in (None, subprocess.DEVNULL): + self.log.close() + self.log = None + if self.private_endpoint is not None: + self.private_endpoint.close() + self.private_endpoint = None + self._release_memory() def unload_if_idle(self): with self.condition: self._refresh() policy = dict(self.memory_policy) budget_reload = self.memory_budget_pending - if (self.closed or self.model_state != "loaded" or self.active_requests - or (not budget_reload and (policy["keep_loaded"] or self.last_activity is None))): + busy = self.closed or self.model_state != "loaded" or self.active_requests or self.cache_control_active + idle_seconds = None if self.last_activity is None else self.clock() - self.last_activity + reason = release_reason(policy, busy=busy, idle_seconds=idle_seconds, + budget_reload=budget_reload) + if reason is None: return False - idle = budget_reload or bool(policy["idle_timeout_seconds"] and - self.clock() - self.last_activity >= policy["idle_timeout_seconds"]) - if idle: + if reason != "probe": self.model_state = "unloading" - elif not policy.get("unload_under_pressure"): - return False worker = self.process revisions = self.activity_revision, self.policy_revision - if not idle: + if reason == "probe": available = self.memory_probe() with self.condition: if (self.closed or self.model_state != "loaded" or self.active_requests or self.process is not worker or self.memory_policy != policy or revisions != (self.activity_revision, self.policy_revision)): return False - error = self._resident_check(policy, available, "idle_reclaim") - if error is None or error.code == "memory_unknown": + idle_seconds = None if self.last_activity is None else self.clock() - self.last_activity + reason = release_reason(policy, busy=False, idle_seconds=idle_seconds, + budget_reload=False, available=available) + if reason is None: return False self.model_state = "unloading" - self._finish_unload("memory_budget" if budget_reload else "idle" if idle else "memory_pressure") + try: + with ComputeLease("idle-unload:" + self.config.get("model", self.config["local_path"]), self.config.get("compute_state_dir")): + self._finish_unload(reason) + except ComputeBusy: + with self.condition: + self.model_state = "loaded" + self.condition.notify_all() + return False return True + def guard_agent_budget(self): + """Stop this owned worker on a measured breach; never signal external agents.""" + with self.condition: + worker = self.process + if worker is None or self.closed or self.model_state not in ('loading', 'loaded'): + return + try: + snapshot = self.memory_registry.snapshot() + budget = snapshot.get('agent_budget') + except MemoryAdmissionError as error: + if error.code == 'memory_registry_busy': + return # Admission is serialized; contention is not a measured breach. + budget = {'status': 'unavailable', 'error': str(error)} + if budget is None: + return + allocation = budget.get('allocations', {}).get(self.memory_token, {}) + ceiling = allocation.get('execution_bytes') + job_breach = ceiling is not None and allocation.get('observed_bytes', 0) > ceiling + if budget.get('status') == 'unavailable' or not budget.get('within_budget', False) or job_breach: + with self.condition: + if (self.process is not worker or self.closed + or self.model_state not in ('loading', 'loaded')): + return + # Claim this transition before a concurrent manual or idle unload. + self.model_state = 'unloading' + self.memory_guard_error = ( + 'job_memory_cap_exceeded' if job_breach else 'agent_memory_budget_exceeded', + 'Job memory cap exceeded; increase --memory-budget-gb.' if job_breach + else 'The shared agent memory admission was exceeded or unavailable.') + self._record_memory_failure('agent_guard', self.memory_guard_error[0], + dict(allocation, limit_bytes=ceiling, agent_budget=budget)) + self._halt() + with self.condition: + self.last_error = (('Job memory cap exceeded; increase --memory-budget-gb.' if job_breach + else 'Agent memory guard stopped the owned model worker.') + + (' ' + budget['error'] if budget.get('error') else '')) + self.model_state = 'failed' + # Only the worker stops; the next request passes memory admission again. + self.closed = self.shutdown_requested + self.condition.notify_all() + self._persist() + def unload(self): with self.condition: if self.closed: raise GatewayError(503, "endpoint_stopping", "Endpoint is stopping.") - if self.active_requests or self.model_state == "unloading": + if self.active_requests or self.cache_control_active or self.model_state == "unloading": raise GatewayError(409, "model_busy", "Finish active requests before unloading.") self.model_state = "unloading" self._finish_unload("manual") @@ -566,25 +903,36 @@ def _finish_unload(self, reason): def close(self): with self.condition: - self.closed = True - self.condition.notify_all() - self._stop_worker() + self.shutdown_requested = True + self._halt() + self.execution.close() with self.condition: self.model_state = "unloaded" self._persist() + def _halt(self): + """Refuse new work, cancel running work and stop the owned worker.""" + with self.condition: + self.closed = True + self.condition.notify_all() + self._stop_worker() + class GatewayServer(ThreadingHTTPServer): daemon_threads = True block_on_close = False def __init__(self, address, config): + if config.get("api_key_sha256") is not None: + from mlx_agent.inference_auth import validate_digest + validate_digest(config["api_key_sha256"]) self.controller = ModelWorker(config) self.config = config self.slots = threading.BoundedSemaphore(MAX_REQUESTS + 4) self.responses = collections.OrderedDict() self.responses_lock = threading.Lock() self.end_text = chat_completions.end_of_sequence(config["local_path"]) + self.tool_parser = chat_completions.vlm_tool_parser(config["local_path"]) if config.get("runtime") == "mlx-vlm" else None super().__init__(address, GatewayHandler) def remember(self, response): @@ -610,6 +958,7 @@ def serve_forever(self, poll_interval=0.5): def reclaim_idle(): while not stopped.wait(0.5): try: + self.controller.guard_agent_budget() self.controller.unload_if_idle() except OSError: # Persist/stop failures remain visible in controller state. @@ -654,20 +1003,38 @@ def log_message(self, *args): def _guard(self, control=False): port = self.server.server_port - if self.headers.get("Host") not in ("127.0.0.1:{}".format(port), "localhost:{}".format(port)): + hosts = self.headers.get_all("Host", []) + if len(hosts) != 1 or hosts[0] not in ("127.0.0.1:{}".format(port), "localhost:{}".format(port)): raise GatewayError(403, "invalid_host", "Use the loopback endpoint address.") - origin = self.headers.get("Origin") - if origin and origin not in ("http://127.0.0.1:{}".format(port), "http://localhost:{}".format(port)): + origins = self.headers.get_all("Origin") + if origins is not None and (len(origins) != 1 or origins[0] not in ("http://127.0.0.1:{}".format(port), "http://localhost:{}".format(port))): raise GatewayError(403, "invalid_origin", "Cross-origin access is refused.") if control and not hmac.compare_digest(self.headers.get("Authorization", "").encode(), ("Bearer " + self.server.config["control_token"]).encode()): raise GatewayError(403, "control_denied", "Endpoint control authorization required.") + protected = self.server.config.get("api_key_sha256") is not None or self.server.config.get("access_key_file") is not None + if not control and protected and not (self.command == "GET" and self.path == "/health"): + from mlx_agent.serving_access import read_access_key + from mlx_agent.inference_auth import validate_digest, authorized_headers + try: + from mlx_agent.private_serve import identity + if self.server.config.get("private_worker") and self.server.config["private_worker"] != identity(): + raise ValueError("Protected worker configuration changed.") + digest = validate_digest(self.server.config.get("api_key_sha256", self.server.config.get("access_key_sha256"))) + if self.server.config.get("access_key_file") is not None: + read_access_key(self.server.config["access_key_file"], digest) + except (OSError, ValueError, KeyError): + raise GatewayError(503, "access_key_unavailable", "The reviewed serving key is unavailable or changed.") from None + if not authorized_headers(self.headers, digest): + raise GatewayError(401, "access_denied", "Inference authorization required.") def _json(self, status, value): encoded = json.dumps(value).encode() self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(encoded))) + if status == 401: + self.send_header("WWW-Authenticate", "Bearer") self.send_header("Connection", "close") self.end_headers() self.close_connection = True @@ -691,6 +1058,16 @@ def _worker_failure(response): message = "Model worker returned HTTP {}".format(response.status) return GatewayError(502, "worker_error", message + (": {}".format(reason) if isinstance(reason, str) else ".")) + def _client_gone(self): + try: + with selectors.DefaultSelector() as selector: + selector.register(self.connection, selectors.EVENT_READ) + if not selector.select(0): + return False + return not self.connection.recv(1, socket.MSG_PEEK) + except OSError: + return True + def _worker_replied(self, worker): """Wait without a deadline for the worker's first reply byte; False once the client disconnects.""" with selectors.DefaultSelector() as selector: @@ -707,6 +1084,20 @@ def _worker_replied(self, worker): return False selector.unregister(self.connection) + def _memory_output(self, payload): + measurement = getattr(self, '_measurement', None) + if measurement is not None: + measurement.observe_json(payload) + controller = self.server.controller + if controller.memory_materialized or controller.memory_transition_blocked or controller.memory_reservation is None: + return + try: + value = json.loads(payload) + except (ValueError,TypeError): + return + if isinstance(value,dict): + controller._materialized_memory() + def _relay(self, response, translate): """Answer a non-streamed request from the worker's translated chat completion.""" if response.status != 200: @@ -715,12 +1106,17 @@ def _relay(self, response, translate): try: if len(payload) > MAX_BODY: raise WorkerResponseError("Model worker response exceeds 16 MiB.") - value = translate(json.loads(payload)) + original = json.loads(payload) + if getattr(self, '_measurement', None) is not None: + self._measurement.observe(original) + value = translate(original) except WorkerResponseError as error: raise GatewayError(502, "invalid_worker_response", str(error)) except (ValueError, TypeError, KeyError, IndexError, AttributeError): raise GatewayError(502, "invalid_worker_response", "Model worker returned an invalid response.") + self.server.controller._materialized_memory() self._json(200, value) + self._inference_success = True return value def _stream(self, response, translator): @@ -734,6 +1130,7 @@ def _stream(self, response, translator): self.end_headers() self.close_connection = True self.wfile.write(b"".join(translator.start())) + finished = False try: while line := response.readline(MAX_BODY): if line.startswith(b":"): @@ -746,8 +1143,13 @@ def _stream(self, response, translator): data = line[len(b"data: "):].strip() if data == b"[DONE]": self.wfile.write(b"".join(translator.finish())) + finished = True break - self.wfile.write(b"".join(translator.chunk(json.loads(data)))) + if getattr(self, '_measurement', None) is not None: + self._measurement.observe_json(data) + events = translator.chunk(json.loads(data)) + self.server.controller._materialized_memory() + self.wfile.write(b"".join(events)) self.wfile.flush() else: raise WorkerResponseError("Model worker stream ended early.") @@ -756,6 +1158,7 @@ def _stream(self, response, translator): except (ValueError, TypeError, AttributeError): self.wfile.write(b"".join(translator.fail("Model worker returned an invalid streamed response."))) self.wfile.flush() + self._inference_success = finished def do_GET(self): try: @@ -776,31 +1179,49 @@ def do_GET(self): except GatewayError as error: self._error(error) + def _dispatch_control(self, body): + """Shared unload, cache, and policy routes for chat and task endpoints.""" + if self.path == "/_mlx/unload": + self._json(200, self.server.controller.unload()) + elif self.path == "/_mlx/cache": + if body: + raise GatewayError(400, "invalid_body", "Cache reclaim requires an empty object.") + self._json(200, self.server.controller.reclaim_cache()) + elif self.path == "/_mlx/policy": + self._json(200, self.server.controller.configure(body)) + else: + return False + return True + def do_POST(self): + self._measurement = None + self._inference_success = False connection = None leased = False response_started = False + response = upstream = None + submitted = False try: - self._guard(control=self.path in ("/_mlx/unload", "/_mlx/policy")) + self._guard(control=self.path in ("/_mlx/unload", "/_mlx/policy", "/_mlx/cache")) if self.headers.get("Transfer-Encoding"): raise GatewayError(400, "invalid_body", "Use a bounded Content-Length request.") try: length = int(self.headers.get("Content-Length", "0")) except ValueError: raise GatewayError(400, "invalid_body", "Invalid Content-Length.") - if not 0 <= length <= MAX_BODY: - raise GatewayError(413, "body_too_large", "Request exceeds 16 MiB.") + limit = MAX_BODY + if self.server.config.get("private_worker"): + from mlx_agent.private_serve import MAX_BODY as PRIVATE_MAX_BODY + limit = PRIVATE_MAX_BODY + if not 0 <= length <= limit: + raise GatewayError(413, "body_too_large", "Request exceeds {} bytes.".format(limit)) try: body = json.loads(self.rfile.read(length)) if length else {} except (ValueError, UnicodeError): raise GatewayError(400, "invalid_body", "Expected a JSON object.") if not isinstance(body, dict): raise GatewayError(400, "invalid_body", "Expected a JSON object.") - if self.path == "/_mlx/unload": - self._json(200, self.server.controller.unload()) - return - if self.path == "/_mlx/policy": - self._json(200, self.server.controller.configure(body)) + if self._dispatch_control(body): return translated = self.path in ("/v1/messages", "/v1/responses") allow_images = self.server.config.get("runtime") == "mlx-vlm" @@ -816,13 +1237,8 @@ def do_POST(self): raise GatewayError(400, "invalid_request", str(error)) elif self.path not in ("/v1/chat/completions", "/v1/completions"): raise GatewayError(404, "not_found", "Unknown inference endpoint.") - aliases = {self.server.config["model"], self.server.config["local_path"], "default_model"} - local = Path(self.server.config["local_path"]) - aliases.add(local.name) - if local.parent.name == "snapshots" and local.parent.parent.name.startswith("models--"): - aliases.add(local.parent.parent.name[len("models--"):].replace("--", "/")) requested = body.get("model", "default_model") - if not isinstance(requested, str) or requested not in aliases: + if not isinstance(requested, str) or requested not in model_aliases(self.server.config): raise GatewayError(400, "model_not_allowed", "This endpoint serves only its configured local model.") if any(body.get(key) not in (None, "default_model") for key in ("adapter_path", "adapter", "draft_model", "draft_adapter")): raise GatewayError(400, "model_not_allowed", "Request-selected adapters and draft models are refused.") @@ -830,22 +1246,35 @@ def do_POST(self): if not isinstance(tokens, int) or isinstance(tokens, bool) or tokens <= 0: raise GatewayError(400, "invalid_body", "max_tokens must be a positive integer.") body["max_tokens"] = min(tokens, self.server.config["max_tokens"]) - body["model"] = self.server.config["local_path"] runtime = self.server.config.get("runtime") + # Splash answers only to its served name. + body["model"] = self.server.config["splash_served_model" if runtime == "splash" else "local_path"] # Existing receipts predate the runtime field; recognize only the # exact native console entrypoint for those configurations. legacy_mlx = runtime is None and Path(self.server.config["worker_argv"][0]).name == "mlx_lm.server" if runtime == "mlx_lm" or legacy_mlx: chat_completions.decode_tool_arguments(body) - port = self.server.controller.acquire() + elif runtime == "mlx-vlm" and self.server.tool_parser and body.get("tools"): + body.setdefault("tool_parser", self.server.tool_parser) + body = inference_defaults.apply(body, self.server.controller.request_defaults) + self._measurement = self.server.controller.inference_telemetry.begin() + port = self.server.controller.acquire(cancelled=self._client_gone) leased = True - connection = http.client.HTTPConnection("127.0.0.1", port, timeout=120) + connection = self.server.controller.connection(timeout=120) connection.request("POST", "/v1/chat/completions" if translated else self.path, json.dumps(body), - {"Content-Type": "application/json"}) + dict({"Content-Type": "application/json"}, **({"Authorization": "Bearer " + self.server.controller.worker_key} + if self.server.config.get("private_worker") or self.server.config.get("api_key_sha256") is not None else {}))) + submitted = True + upstream = connection.sock + upstream.settimeout(None) # MLX-LM writes nothing until an unstreamed answer is complete or a queued request starts. - if not self._worker_replied(connection.sock): + if not self._worker_replied(upstream): return response = connection.getresponse() + if self.server.config.get("private_worker"): + from mlx_agent.private_serve import PRIVATE_PROTOCOL + if response.getheader("X-MLX-Agent-Transport") != PRIVATE_PROTOCOL: + raise GatewayError(503, "private_protocol_missing", "The private model worker protocol is unavailable.") def trimmed(value): chat_completions.trim_end(value, self.server.end_text) @@ -877,27 +1306,66 @@ def trimmed(value): self.close_connection = True if response.status == 200 and body.get("stream") and self.path == "/v1/chat/completions": stream = chat_completions.ChunkStream() + finished = False while line := response.readline(MAX_BODY): + if line.strip() == b'data: [DONE]': + finished = True + if line.startswith(b'data: ') and line.strip() != b'data: [DONE]': + self._memory_output(line[len(b'data: '):]) self.wfile.write(stream.line(line)) self.wfile.flush() + self._inference_success = finished return if response.status == 200 and not body.get("stream"): payload = response.read(MAX_BODY + 1) + if payload: + self._memory_output(payload) self.wfile.write(chat_completions.complete_body(payload, self.server.end_text) if len(payload) <= MAX_BODY else payload) while chunk := response.read1(65536): + if body.get('stream'): + self._measurement.feed(chunk) self.wfile.write(chunk) self.wfile.flush() + self._inference_success = response.status == 200 and (not body.get('stream') or self._measurement.stream_done) except GatewayError as error: - self._error(error) + if not self._client_gone(): + self._error(error) except (OSError, http.client.HTTPException): - if not response_started: + if not response_started and not self._client_gone(): self._error(GatewayError(503, "worker_unavailable", "Model worker connection failed.")) finally: - if connection: - connection.close() - if leased: - self.server.controller.release() + if self._measurement is not None: + self._measurement.finish(success=self._inference_success) + try: + if leased and submitted and (response is None or not response.isclosed()): + try: + deadline = time.monotonic() + DRAIN_TIMEOUT_SECONDS + if upstream is not None: + upstream.settimeout(DRAIN_TIMEOUT_SECONDS) + if response is None: + response = connection.getresponse() + while not response.isclosed(): + if upstream is not None: + upstream.settimeout(max(.001, deadline - time.monotonic())) + if time.monotonic() >= deadline: + raise TimeoutError("Model reply did not drain.") + if not response.read1(65536): + break + except (OSError, http.client.HTTPException): + self.server.controller.execution_unresolved = True + try: + self.server.controller._stop_worker() + finally: + with self.server.controller.condition: + self.server.controller.model_state = "failed" if self.server.controller.process else "unloaded" + self.server.controller._persist() + finally: + if connection: + connection.close() + if leased: + self.server.controller.release() + def make_server(config, port): diff --git a/packages/codex/mlx-agent/src/mlx_agent/media_settings.py b/packages/codex/mlx-agent/src/mlx_agent/media_settings.py new file mode 100644 index 0000000..7d3ee0d --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/media_settings.py @@ -0,0 +1,52 @@ +"""Read-only, model-bound settings shared by media planners and clients.""" + +import hashlib +import json +import os +import stat +from pathlib import Path + +from .task_contracts import TaskError + + +def supports_adaptive_reuse(config, kind): + if kind == "mesh_generation": + return config.get("model_type") == "triposg" + if kind == "video_generation": + return (config.get("model_type") == "t2v" and config.get("model_version") == "2.1" + and not config.get("dual_model", False)) + return False + + +def model_settings(model_path): + """Inspect only a bounded config file; never import or load a model runtime.""" + try: + requested = Path(model_path) + if not requested.is_absolute(): + raise ValueError("The model path must be absolute.") + model = requested.resolve(strict=True) + config_path = (model / "config.json").resolve(strict=True) + descriptor = os.open(config_path, os.O_RDONLY | os.O_NONBLOCK | getattr(os, "O_NOFOLLOW", 0)) + with os.fdopen(descriptor, "rb") as stream: + if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): + raise ValueError("The model config must be a regular file.") + data = stream.read(1024 * 1024 + 1) + if len(data) > 1024 * 1024: + raise ValueError("The model config exceeds 1 MiB.") + config = json.loads(data) + if not isinstance(config, dict): + raise ValueError("The model config must be an object.") + except (OSError, ValueError, RuntimeError) as error: + raise TaskError("model_unreadable", "Cannot inspect the local model config.", + "Select a local model with a readable config.json.") from error + binding = {"path": str(model), "config_sha256": hashlib.sha256(data).hexdigest()} + descriptors = {} + for kind, reason in (("mesh_generation", "Adaptive reuse requires TripoSG."), + ("video_generation", "Adaptive reuse requires single-model Wan2.1 text-to-video.")): + supported = supports_adaptive_reuse(config, kind) + value = {"modes": ["off", "adaptive"] if supported else ["off"], "default": "off", + "approximate": True, "cache_memory_mib": {"minimum": 8, "maximum": 4096, "default": 256}} + if not supported: + value["unavailable_reason"] = reason + descriptors[kind] = value + return binding, descriptors diff --git a/packages/codex/mlx-agent/src/mlx_agent/memory_budget.py b/packages/codex/mlx-agent/src/mlx_agent/memory_budget.py new file mode 100644 index 0000000..ce8312b --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/memory_budget.py @@ -0,0 +1,220 @@ +"""Private, host-wide agent memory policy and process-family accounting.""" +import ctypes +import errno +import json +import os +import stat +import subprocess +import sys +from functools import lru_cache +from pathlib import Path + +SCHEMA = 'agent-memory-budget/1' + + +class _RusageInfoV0(ctypes.Structure): + # Public Darwin ABI from sys/resource.h; flavor 0 is available since 10.9. + _fields_ = [('uuid', ctypes.c_ubyte * 16)] + [ + (name, ctypes.c_uint64) for name in + ('user_time', 'system_time', 'idle_wakeups', 'interrupt_wakeups', + 'pageins', 'wired_size', 'resident_size', 'phys_footprint', + 'start_time', 'exit_time')] + + +@lru_cache(maxsize=1) +def _rusage_function(): + library = ctypes.CDLL('/usr/lib/libproc.dylib', use_errno=True) + function = library.proc_pid_rusage + function.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.POINTER(_RusageInfoV0)] + function.restype = ctypes.c_int + return function + + +def _usage(pid): + usage = _RusageInfoV0() + if _rusage_function()(pid, 0, ctypes.byref(usage)) != 0: + if ctypes.get_errno() == errno.ESRCH: + raise ProcessLookupError(pid) + return None # An unreadable tracked process must block admission. + if usage.exit_time: + raise ProcessLookupError(pid) # The process exited after the table was sampled. + return usage + + +def _physical_bytes(pid): + usage = _usage(pid) + return None if usage is None else usage.phys_footprint + + +def identified_pids(policy, entries, external_pids=()): + """The PIDs whose start and command ``account`` compares: external bindings and managed workers.""" + pids = {binding['pid'] for binding in policy['external']} if policy is not None else set() + pids.update(external_pids or ()) + pids.update(entry['worker']['pid'] for entry in entries.values() if entry['worker'] is not None) + return pids + + +def process_snapshot(identities=None): + """Live processes and their memory; identity for the PIDs asked, or for every process when None.""" + if identities is not None and sys.platform == 'darwin': + from .process_table import identities as observe, rows as table + rows = {} + for pid, (parent, group) in table().items(): + try: + usage = _usage(pid) + except ProcessLookupError: + continue # Short-lived processes can exit after the table was read. + rows[pid] = {'parent': parent, 'group': group, + 'rss': None if usage is None else usage.resident_size, + 'physical_bytes': None if usage is None else usage.phys_footprint} + for pid, identity in observe(pid for pid in identities if pid in rows).items(): + rows[pid]['identity'] = identity + # A process that exits before its identity is read is no longer running. + return {pid: row for pid, row in rows.items() if pid not in identities or 'identity' in row} + result = subprocess.run(['/bin/ps', '-axo', 'pid=,ppid=,pgid=,rss=,stat=,lstart=,command='], + capture_output=True, text=True, timeout=5, check=True) + rows = {} + for line in result.stdout.splitlines(): + fields = line.split(None, 5) + if len(fields) == 6 and not fields[4].startswith('Z'): + pid, parent, group, rss = map(int, fields[:4]) + rows[pid] = {'parent': parent, 'group': group, 'rss': rss * 1024, + 'identity': fields[5]} + if sys.platform == 'darwin': + for pid in list(rows): + try: + rows[pid]['physical_bytes'] = _physical_bytes(pid) + except ProcessLookupError: + del rows[pid] # Short-lived children can exit after ps returned. + return rows + + +def same_identity(left, right): + return isinstance(left, str) and isinstance(right, str) and left.split() == right.split() + + +def read_policy(root): + path = Path(root) / 'budget.json' + try: + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + except FileNotFoundError: + return None + with os.fdopen(descriptor, 'rb') as stream: + info = os.fstat(stream.fileno()) + if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() + or info.st_mode & 0o077 or info.st_nlink != 1 or info.st_size > 65536): + raise ValueError('Agent memory policy must be a private owned regular file.') + value = json.loads(stream.read(65537)) + validate_policy(value) + return value + + +def validate_policy(value): + if (not isinstance(value, dict) or set(value) != {'schema', 'limit_bytes', 'reserve_bytes', 'external'} + or value['schema'] != SCHEMA or type(value['limit_bytes']) is not int + or not 0 < value['limit_bytes'] <= 2**60 or type(value['reserve_bytes']) is not int + or not 0 <= value['reserve_bytes'] < value['limit_bytes'] + or not isinstance(value['external'], list) or len(value['external']) > 256): + raise ValueError('Invalid agent memory budget.') + for row in value['external']: + if (not isinstance(row, dict) or set(row) != {'pid', 'identity', 'group'} + or type(row['pid']) is not int or row['pid'] <= 0 + or type(row['group']) is not int or row['group'] <= 0 + or not isinstance(row['identity'], str) or not row['identity']): + raise ValueError('Invalid external agent process identity.') + + +def family(rows, roots, groups=()): + found = {pid for pid, row in rows.items() if pid in roots or row['group'] in groups} + while True: + children = {pid for pid, row in rows.items() if row['parent'] in found} + if children <= found: + return found + found.update(children) + + +def account(policy, entries, rows, owner, replacement=None): + """Count physical process observations once; pending allocations are additional.""" + from .residency import MemoryAdmissionError + + def rss(pids): + values = [] + for pid in pids: + row = rows[pid] + resident = row.get('rss') + physical = row.get('physical_bytes', resident) + if any(type(value) is not int or value < 0 for value in (resident, physical)): + raise MemoryAdmissionError('memory_unknown', + f'Agent process memory is unavailable for PID {pid}.') + # RSS misses Metal allocations; footprint also includes compressed memory. + values.append(max(resident, physical)) + return sum(values) + + external = set() + for binding in policy['external']: + observed = rows.get(binding['pid']) + if observed is not None and same_identity(binding['identity'], observed['identity']): + external.update(family(rows, {binding['pid']})) + elif observed is None: + # A reparented child in the original group remains charged. + external.update(family(rows, set(), {binding['group']})) + counted = set(external) + external_bytes = rss(external) + resident = pending = overhead = 0 + allocations = {} + owners = {owner[0]} + for key, entry in entries.items(): + owners.add(entry['owner'][0]) + new_amount = replacement[1] if replacement is not None and replacement[0] == key else None + if entry['phase'] != 'resident': + amount = entry['reserved_bytes'] if new_amount is None else new_amount + # Cold/launching reservations already include worker allocations. + worker = entry['worker'] + if worker is not None: + pids = family(rows, {worker['pid']}, {worker['pgid']}) + amount = max(amount, rss(pids - counted)) + counted.update(pids) + pending += amount + allocations[key] = {'resident_bytes': 0, 'pending_bytes': amount, + 'observed_bytes': rss(pids) if worker is not None else 0, + 'execution_bytes': entry.get('execution_bytes')} + continue + worker = entry['worker'] + pids = set() + if worker is not None: + observed = rows.get(worker['pid']) + if observed is not None and not same_identity(worker['identity'], observed['identity']): + raise MemoryAdmissionError('memory_unknown', 'A managed worker identity changed.') + pids = family(rows, {worker['pid']}, {worker['pgid']}) + uncounted = pids - counted + # Overlapping process roots cannot be charged twice. The model estimate + # is retained when the original process is absent or not yet observable. + estimate = 0 if pids and not uncounted else entry['resident_bytes'] + charged = max(estimate, rss(uncounted)) + resident += charged + counted.update(pids) + if new_amount is None and 'execution_bytes' in entry: + # Actual allocations consume their reservation rather than adding to it. + workspace = max(0, entry['execution_bytes'] - charged) + else: + # A settled reservation already holds its growth allowance; measured + # growth beyond the resident estimate consumes it rather than adding to it. + grown = min(entry['growth_bytes'], max(0, charged - entry['resident_bytes'])) + workspace = max(0, (entry['reserved_bytes'] if new_amount is None else new_amount) - grown) + pending += workspace + allocations[key] = {'resident_bytes': charged, 'pending_bytes': workspace, + 'observed_bytes': rss(pids), 'execution_bytes': entry.get('execution_bytes')} + if replacement is not None and replacement[0] not in entries: + pending += replacement[1] + # An owner missing from the process table has exited and holds no memory; + # its reservations stay charged through their workers and estimates above. + owners &= rows.keys() + for pid in owners - counted: + overhead += rss({pid}) + total = external_bytes + resident + pending + overhead + admission = policy['limit_bytes'] - policy['reserve_bytes'] + observed = rss(counted | owners) + return {'schema': SCHEMA, 'limit_bytes': policy['limit_bytes'], 'reserve_bytes': policy['reserve_bytes'], + 'admission_bytes': admission, 'external_bytes': external_bytes, 'resident_bytes': resident, + 'pending_bytes': pending, 'overhead_bytes': overhead, 'accounted_bytes': total, + 'within_budget': total <= admission, 'observed_bytes': observed, 'allocations': allocations} diff --git a/packages/codex/mlx-agent/src/mlx_agent/memory_diagnostics.py b/packages/codex/mlx-agent/src/mlx_agent/memory_diagnostics.py new file mode 100644 index 0000000..713542b --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/memory_diagnostics.py @@ -0,0 +1,44 @@ +"""Bounded memory decision data for status and private state.""" +import hashlib +import os +import time + +FIELDS = ('available_bytes', 'required_available_bytes', 'headroom_bytes', + 'requested_headroom_bytes', 'required_bytes', 'other_reserved_bytes', + 'other_resident_bytes', 'requested_bytes', 'registry_resident_bytes', + 'workspace_bytes', 'growth_bytes', 'pending_bytes', 'cache_bytes', 'active_bytes', + 'observed_bytes', 'charged_resident_bytes', 'route_limit_bytes', + 'shared_limit_bytes', 'shared_admission_bytes', 'shared_accounted_bytes', + 'shared_external_bytes', 'shared_overhead_bytes', 'shared_observed_bytes', + 'shared_resident_bytes', 'shared_pending_bytes', 'accounted_bytes') +SOURCES = ('cold_admission', 'workspace_admission', 'task_admission', 'resident_guard', 'agent_guard') + + +def memory_decision(source, reason, details=None, *, pid=None, pgid=None, identity=None): + if source not in SOURCES or not isinstance(reason, str) or not reason.isidentifier() or len(reason) > 64: + raise ValueError('Invalid memory decision identity.') + details = details if isinstance(details, dict) else {} + budget = details.get('agent_budget') if isinstance(details.get('agent_budget'), dict) else {} + owner_hash = details.get('registry_owner_identity_sha256') + if not isinstance(owner_hash, str) or len(owner_hash) != 64 or any(c not in '0123456789abcdef' for c in owner_hash): + owner_hash = None + result = {'schema': 'memory-decision/1', 'captured_at': time.time(), 'source': source, + 'reason': reason, 'gateway_pid': os.getpid(), 'persistence_error': None, + 'registry_owner_identity_sha256': owner_hash, 'worker_pid': pid if type(pid) is int and pid > 0 else None, + 'worker_pgid': pgid if type(pgid) is int and pgid > 0 else None, + 'worker_identity_sha256': hashlib.sha256(identity.encode()).hexdigest() if isinstance(identity, str) else None} + aliases = {'route_limit_bytes': details.get('route_limit_bytes', details.get('limit_bytes')), + 'charged_resident_bytes': details.get('charged_resident_bytes', details.get('resident_bytes')), + 'shared_limit_bytes': budget.get('limit_bytes'), + 'shared_admission_bytes': budget.get('admission_bytes'), + 'shared_accounted_bytes': budget.get('accounted_bytes'), + 'accounted_bytes': budget.get('accounted_bytes'), + 'shared_external_bytes': budget.get('external_bytes'), + 'shared_overhead_bytes': budget.get('overhead_bytes'), + 'shared_observed_bytes': budget.get('observed_bytes'), + 'shared_resident_bytes': budget.get('resident_bytes'), + 'shared_pending_bytes': budget.get('pending_bytes')} + for field in FIELDS: + value = aliases.get(field, details.get(field)) + result[field] = value if type(value) is int and 0 <= value <= 2**60 else None + return result diff --git a/packages/codex/mlx-agent/src/mlx_agent/memory_policy.py b/packages/codex/mlx-agent/src/mlx_agent/memory_policy.py new file mode 100644 index 0000000..4055aac --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/memory_policy.py @@ -0,0 +1,316 @@ +"""One memory policy: reviewed limits in, the residency outcome for one endpoint out. + +Callers use this module. They do not translate field names or restate which +runtimes may carry a budget, a KV context, or an allocator cache. Splash and +Strata sizes are read from the serving plan; those modules still compute them. +""" +import json +import hashlib +import math +from pathlib import Path + +from .allocator_cache import FIELDS as CACHE_FIELDS +from .allocator_cache import from_memory, requested +from .contextfit import CONTEXT_MAX, CONTEXT_MIN, extract_architecture, kv_cache_bytes +from .serving_plan import memory_basis + +STRATA_CONTEXT = "Strata JIT admission already includes the KV cache at --strata-context-tokens." +TASK_CONTEXT = "Task endpoints do not use text KV context settings." + +_DEFAULTS = {"idle_timeout_seconds": 0, "keep_loaded": False, "minimum_headroom_gb": None} + +def model_key(config): + """Stable registry key for the planned model and worker identity.""" + return hashlib.sha256(json.dumps([str(Path(config['local_path']).resolve()), + config.get('fingerprint'), config.get('runtime'), config['worker_argv']], + sort_keys=True).encode()).hexdigest() + + +_EXTRA = CACHE_FIELDS | { + "context_tokens", "unload_under_pressure", "model_memory_budget_gb", + "release_after_request", "execution_wait_seconds", +} + + +class PolicyRejected(ValueError): + """A policy the runtime cannot carry. code is the serving error code.""" + + def __init__(self, code, message, remediation): + super().__init__(message) + self.code = code + self.remediation = remediation + + +def validate(policy=None): + """Return a normalized policy. None is the idle-off, keep-off default.""" + if policy is None: + return dict(_DEFAULTS) + if not isinstance(policy, dict) or set(policy) - set(_DEFAULTS) - _EXTRA: + raise ValueError("Unknown memory policy fields.") + result = dict(_DEFAULTS, **policy) + cache = from_memory(result) + if cache["cache_reclaim"] == "pressure" and result["minimum_headroom_gb"] is None: + raise ValueError("Pressure cache reclaim requires a headroom reserve.") + wait = result.get("execution_wait_seconds", 0) + if type(wait) is not int or not 0 <= wait <= 3600: + raise ValueError("Execution wait must be an integer between 0 and 3600 seconds.") + release = result.pop("release_after_request", False) + if type(release) is not bool or (release and result["keep_loaded"]): + raise ValueError("Release after each request cannot be combined with keep loaded.") + if "release_after_request" in policy: + result["release_after_request"] = release + context = result.pop("context_tokens", None) + pressure = result.pop("unload_under_pressure", False) + budget = result.pop("model_memory_budget_gb", None) + if budget is not None: + if type(budget) not in (int, float) or not math.isfinite(budget) or not 1 <= budget <= 1024: + raise ValueError("Model memory budget must be a finite value from 1 to 1024 GB.") + result["model_memory_budget_gb"] = budget + if result["minimum_headroom_gb"] is None: + result["minimum_headroom_gb"] = 2 + idle, keep, reserve = (result[key] for key in _DEFAULTS) + if type(idle) is not int or not 0 <= idle <= 86400: + raise ValueError("Idle timeout must be an integer between 0 and 86400 seconds.") + if type(keep) is not bool: + raise ValueError("Keep loaded must be a boolean.") + if reserve is not None and (type(reserve) not in (int, float) or not math.isfinite(reserve) or not 0 <= reserve <= 1024): + raise ValueError("Headroom reserve must be a finite value between 0 and 1024 GB.") + if type(pressure) is not bool: + raise ValueError("Unload under pressure must be a boolean.") + if pressure: + if reserve is None or keep: + raise ValueError("Unload under pressure requires a headroom reserve and cannot be combined with keep loaded.") + result["unload_under_pressure"] = True + if context is not None: + if type(context) is not int or not CONTEXT_MIN <= context <= CONTEXT_MAX: + raise ValueError("Context tokens must be an integer between {} and {}.".format(CONTEXT_MIN, CONTEXT_MAX)) + if reserve is None: + raise ValueError("Context tokens require a headroom reserve.") + result["context_tokens"] = context + return result + + +def from_cli(arguments): + """Translate CLI names into a policy dict. Does not validate.""" + policy = {"idle_timeout_seconds": arguments.idle_timeout or 0, "keep_loaded": bool(arguments.keep_loaded), + "minimum_headroom_gb": arguments.min_headroom_gb} + for key in ("allocator_cache_limit_mib", "cache_reclaim"): + if getattr(arguments, key, None) is not None: + policy[key] = getattr(arguments, key) + if getattr(arguments, "clear_allocator_cache_limit", False): + policy["allocator_cache_limit_mib"] = None + if getattr(arguments, "execution_wait_seconds", None) is not None: + policy["execution_wait_seconds"] = arguments.execution_wait_seconds + if getattr(arguments, "release_after_request", None) is not None: + policy["release_after_request"] = arguments.release_after_request + if arguments.memory_budget_gb is not None: + policy["model_memory_budget_gb"] = arguments.memory_budget_gb + if getattr(arguments, "clear_memory_budget", False): + if arguments.memory_budget_gb is not None: + raise ValueError("Choose --memory-budget-gb or --clear-memory-budget.") + policy["model_memory_budget_gb"] = None + if arguments.context_tokens is not None: + policy["context_tokens"] = arguments.context_tokens + if arguments.unload_under_pressure is not None: + policy["unload_under_pressure"] = arguments.unload_under_pressure + return policy + + +def cli_supplied(arguments): + """True when serve start should attach a policy. Same fields from_cli reads.""" + if (getattr(arguments, "release_after_request", None) is not None + or getattr(arguments, "idle_timeout", None) is not None + or arguments.keep_loaded + or getattr(arguments, "min_headroom_gb", None) is not None + or getattr(arguments, "context_tokens", None) is not None + or arguments.unload_under_pressure + or getattr(arguments, "memory_budget_gb", None) is not None + or getattr(arguments, "execution_wait_seconds", None) is not None + or getattr(arguments, "allocator_cache_limit_mib", None) is not None + or getattr(arguments, "cache_reclaim", None) is not None + or getattr(arguments, "clear_allocator_cache_limit", False) + or getattr(arguments, "clear_memory_budget", False)): + return True + return False + + +def _residency_chosen(arguments): + return (getattr(arguments, "idle_timeout", None) is not None + or bool(arguments.keep_loaded) + or getattr(arguments, "min_headroom_gb", None) is not None + or getattr(arguments, "release_after_request", None) is not None + or bool(arguments.unload_under_pressure) + or getattr(arguments, "context_tokens", None) is not None + or getattr(arguments, "memory_budget_gb", None) is not None) + + +def for_start(arguments, runtime): + """Policy for serve start, or None when the caller set no memory flag. + + A task endpoint that only sets execution wait or allocator cache keeps the + task default of releasing weights after each job. + """ + if not cli_supplied(arguments): + return None + policy = from_cli(arguments) + if runtime == "tasks" and not _residency_chosen(arguments) and "release_after_request" not in policy: + policy["release_after_request"] = True + return policy + + +def policy_from_profile(settings): + """Profile names to policy names, for validation. The profile stores CLI names.""" + policy = {"minimum_headroom_gb": settings["min_headroom_gb"], "idle_timeout_seconds": settings["idle_timeout"], + "keep_loaded": settings["keep_loaded"], "unload_under_pressure": settings["unload_under_pressure"]} + if "memory_budget_gb" in settings: + policy["model_memory_budget_gb"] = settings["memory_budget_gb"] + for key in ("execution_wait_seconds", "release_after_request", *CACHE_FIELDS): + if key in settings: + policy[key] = settings[key] + return policy + + +def _reject_cache(policy, runtime): + if runtime != "tasks" and requested(policy): + raise PolicyRejected("cache_control_unavailable", + "Allocator cache controls require a resident task backend.", + "Select a supported task model; inspect allocator_cache in endpoint status.") + + +def enforce_launch(policy, runtime, jit): + """Gates for a non-task start plan. Task plans do not call this.""" + _reject_cache(policy, runtime) + if not jit: + raise PolicyRejected("jit_required", "Memory policy requires a JIT endpoint.", "Use --jit.") + if runtime != "strata" and "model_memory_budget_gb" in policy: + raise PolicyRejected("invalid_arguments", "Model memory budgets currently require Strata.", + "Select a prepared Strata profile.") + if runtime == "strata" and "context_tokens" in policy: + raise PolicyRejected("invalid_arguments", STRATA_CONTEXT, "Remove --context-tokens.") + + +def reject_task_context(changes): + if changes.get("context_tokens") is not None: + raise PolicyRejected("invalid_policy", TASK_CONTEXT, "Review the memory policy.") + + +def enforce_configure(policy, runtime, changes): + """Gates when a live endpoint replaces its policy.""" + if runtime == "tasks": + reject_task_context(changes) + if runtime == "strata" and "context_tokens" in policy: + raise PolicyRejected("invalid_policy", STRATA_CONTEXT, "Remove --context-tokens.") + if runtime not in ("strata", "tasks") and "model_memory_budget_gb" in policy: + raise PolicyRejected("invalid_policy", "Model memory budgets require Strata or a task endpoint.", + "Select a prepared Strata profile or a task model.") + _reject_cache(policy, runtime) + + +def reject_cache_outside_tasks(policy, runtime): + """Worker construction. Same rule as configure, raised as ValueError for the existing caller.""" + try: + _reject_cache(policy, runtime) + except PolicyRejected as error: + raise ValueError(str(error)) from error + + +def execution_wait_seconds(policy): + """How long one endpoint may wait for execution.""" + return policy.get("execution_wait_seconds", 0) + + +def releases_after_request(policy): + """Whether weights are released when the endpoint has no active request.""" + return bool(policy.get("release_after_request", False)) + + +_UNMEASURED = object() + + +def release_reason(policy, *, busy, idle_seconds, budget_reload, available=_UNMEASURED): + """Why resident weights should be released, or None to keep them. + + Omit ``available`` before a headroom probe. ``probe`` means the caller + should measure headroom and ask again. A measured ``None`` is unknown + headroom and does not release weights. + """ + if busy: + return None + if budget_reload: + return "memory_budget" + if policy["keep_loaded"] or idle_seconds is None: + return None + if releases_after_request(policy) or ( + policy["idle_timeout_seconds"] and idle_seconds >= policy["idle_timeout_seconds"]): + return "idle" + if not policy.get("unload_under_pressure"): + return None + if available is _UNMEASURED: + return "probe" + reserve = policy["minimum_headroom_gb"] + if available is None or reserve is None or type(available) is not int or available < 0: + return None + if available < math.ceil(reserve * 1e9): + return "memory_pressure" + return None + + +def _kv_cache_bytes(local_path, context_tokens): + """KV cache bytes at the context from the local config.json, or None when its architecture is unknown.""" + try: + location = Path(local_path) / "config.json" + if location.stat().st_size > 1024 * 1024: + return None + config = json.loads(location.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + if not isinstance(config, dict): + return None + architecture = extract_architecture(config) or extract_architecture(config.get("text_config")) + return kv_cache_bytes(architecture, context_tokens) + + +def _weight_bytes(local_path): + return sum(item.stat().st_size for item in Path(local_path).rglob("*") + if item.is_file() and item.suffix in (".safetensors", ".npz", ".bin", ".gguf")) + + +def reservation(policy, config, *, weight_bytes=None): + """Bytes to reserve for one endpoint, from the policy and the serving plan's sizes. + + Returns None when the estimate is unavailable. Splash weight bytes and Strata + estimate, allocation, and growth are the values already stored on the plan. + """ + context = policy.get("context_tokens") + basis = memory_basis(config) + runtime_bytes = 1_500_000_000 + weights = 0 + kv = 0 + if basis.kind == "splash": + weights = basis.weights + elif basis.kind != "strata": + weights = _weight_bytes(config["local_path"]) if weight_bytes is None else weight_bytes + if basis.kind != "strata" and weights and config.get("adapter_path") is not None: + weights += config["adapter_identity"]["adapters.safetensors"]["bytes"] + if basis.kind != "strata": + kv = 0 if context is None else _kv_cache_bytes(config["local_path"], context) + dynamic_bytes = runtime_bytes + (kv or 0) + size = math.ceil(weights * 1.10 + kv + 1.5e9) if weights and kv is not None else None + if basis.kind == "splash" and basis.cap_gb is not None: + size = math.ceil(basis.cap_gb * 1e9) + if basis.kind == "strata": + runtime_bytes = 5_000_000_000 + if policy.get("model_memory_budget_gb") is not None: + size = basis.allocation_bytes + else: + size = basis.estimate_bytes + dynamic_bytes = basis.growth_bytes + if size is None or dynamic_bytes is None: + size = None + if size is None: + return None + size = math.ceil(size) + workspace = min(size, runtime_bytes) + growth = min(size - workspace, max(0, math.ceil(dynamic_bytes) - workspace)) + return {"size": size, "workspace_bytes": workspace, "growth_bytes": growth, + "reserve_bytes": size - workspace - growth} diff --git a/packages/codex/mlx-agent/src/mlx_agent/mesh.py b/packages/codex/mlx-agent/src/mlx_agent/mesh.py index bbc0649..4f1270c 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/mesh.py +++ b/packages/codex/mlx-agent/src/mlx_agent/mesh.py @@ -8,6 +8,7 @@ from .backends import backend_python, is_installed, load_manifests, load_registries, lookup from .inference_runner import InferenceError, RunnerContract, invoke +from .media_settings import supports_adaptive_reuse MESH_SCHEMA = "mesh/1" MESH_RUNNER = Path(__file__).with_name("mesh_runner.py") @@ -40,9 +41,13 @@ def _choices(values): def plan_mesh(model_path, image, out, steps=None, seed=42, resolution=None, guidance=None, max_faces=500_000, - manifests=None, registries=None, root=None): - """The backend run for one image; unset steps, resolution and guidance take the model's own defaults.""" + manifests=None, registries=None, root=None, denoiser_cache='off', cache_memory_mib=256, views=(), + guide=None): + """The backend run for one image, plus TRELLIS.2's extra ``views`` and ``guide`` mesh; unset steps, resolution + and guidance take the model's own defaults.""" model, image, target = (Path(value).expanduser().absolute() for value in (model_path, image, out)) + views = [Path(value).expanduser().absolute() for value in views] + guide = None if guide is None else Path(guide).expanduser().absolute() try: config = json.loads((model / "config.json").read_text()) except (OSError, ValueError) as error: @@ -55,10 +60,19 @@ def plan_mesh(model_path, image, out, steps=None, seed=42, resolution=None, guid guidance = defaults["guidance"] if guidance is None else guidance if not image.is_file() or image.suffix.lower() not in (".png", ".jpg", ".jpeg", ".webp"): raise MeshError("invalid_arguments", "--image must be an existing PNG, JPEG or WebP file.", "Select an input image.") + if (views or guide is not None) and config.get("model_type") != "trellis2": + raise MeshError("invalid_arguments", "--view and --guide require a TRELLIS.2 model.", "Drop them for this model.") + if any(not view.is_file() or view.suffix.lower() not in (".png", ".jpg", ".jpeg", ".webp") for view in views): + raise MeshError("invalid_arguments", "--view must be an existing PNG, JPEG or WebP file.", "Select the view images.") + if guide is not None and (not guide.is_file() or guide.suffix.lower() != ".glb"): + raise MeshError("invalid_arguments", "--guide must be an existing .glb file.", "Export the guide mesh as GLB.") if target.suffix.lower() != ".glb" or target.exists() or target.is_symlink() or not target.parent.is_dir(): raise MeshError("invalid_arguments", "--out must be a new .glb path in an existing directory.", "Choose a new output path.") if type(steps) is not int or not 1 <= steps <= 100 or type(seed) is not int or not 0 <= seed < 2**32: raise MeshError("invalid_arguments", "Steps must be 1..100 and seed 0..4294967295.", "Use --steps 50 --seed 42.") + if len(views) >= steps: + raise MeshError("invalid_arguments", "Each image conditions one sampler step in turn; use fewer views than steps.", + "Raise --steps or drop views.") if type(resolution) is not int or resolution not in resolutions: raise MeshError("invalid_arguments", "Resolution must be {0}.".format(_choices(resolutions)), "Use --resolution {0}.".format(defaults["resolution"])) @@ -66,6 +80,12 @@ def plan_mesh(model_path, image, out, steps=None, seed=42, resolution=None, guid raise MeshError("invalid_arguments", "Max faces must be 1000..10000000.", "Use --max-faces 500000.") if type(guidance) not in (int, float) or not math.isfinite(guidance) or not 1 <= guidance <= 20: raise MeshError("invalid_arguments", "Guidance must be finite and between 1 and 20.", "Use --guidance 7.") + if denoiser_cache not in ('off','adaptive'): + raise MeshError('invalid_arguments', 'Denoiser cache must be off or adaptive.', 'Use --denoiser-cache adaptive.') + if type(cache_memory_mib) is not int or not 8 <= cache_memory_mib <= 4096: + raise MeshError('invalid_arguments', 'Cache memory must be 8..4096 MiB.', 'Use --cache-memory-mib 256.') + if denoiser_cache == 'adaptive' and not supports_adaptive_reuse(config, 'mesh_generation'): + raise MeshError('invalid_arguments', 'Adaptive mesh denoiser caching requires TripoSG.', 'Use --denoiser-cache off for this model.') manifests = load_manifests() if manifests is None else manifests registries = load_registries(manifests, root) if registries is None else registries hits = [hit for hit in lookup(config.get("model_type"), manifests, registries) if hit["category"] == "mesh_generation"] @@ -78,6 +98,12 @@ def plan_mesh(model_path, image, out, steps=None, seed=42, resolution=None, guid "--model", str(model), "--image", str(image), "--out", str(target), "--steps", str(steps), "--seed", str(seed), "--resolution", str(resolution), "--guidance", str(guidance), "--max-faces", str(max_faces)] + if denoiser_cache == 'adaptive': + argv += ['--denoiser-cache',denoiser_cache,'--cache-memory-mib',str(cache_memory_mib)] + for view in views: + argv += ["--view", str(view)] + if guide is not None: + argv += ["--guide", str(guide)] return {"backend": manifest["id"], "model": str(model), "out": str(target), "argv": argv} @@ -88,10 +114,12 @@ def plan_mesh(model_path, image, out, steps=None, seed=42, resolution=None, guid ) -def run_mesh(plan, manifests=None, root=None, timeout=3600, runner=subprocess.run): - result = invoke(plan, CONTRACT, manifests, root, timeout, runner) - output = Path(plan["out"]) +def validate_glb(path): + """Check the owned output's GLB container before publishing its artifact.""" + output = Path(path) try: + if output.is_symlink(): + raise ValueError("A mesh output cannot be a symbolic link") with output.open("rb") as stream: header = stream.read(12) magic, version, length = struct.unpack(" limit or any(ord(c) < 32 and c not in "\n\t" for c in text): raise MusicError("invalid_arguments", "Invalid {0}.".format(name), "Provide a caption and lyrics; use [instrumental] for instrumental music.") if isinstance(duration, bool) or not isinstance(duration, (float, int)) or not math.isfinite(duration) or not 0 < duration <= 360: raise MusicError("invalid_arguments", "Duration must be greater than 0 and at most 360 seconds.", "Use --duration 15.") - if type(steps) is not int or not 1 <= steps <= 30 or type(seed) is not int or not 0 <= seed <= 2**32 - 1: - raise MusicError("invalid_arguments", "Steps or seed is out of range.", "Use 1..30 steps and a 32-bit unsigned seed.") - return {"caption": caption, "lyrics": lyrics, "duration": duration, "steps": steps, "seed": seed} + if type(steps) is not int or not 1 <= steps <= MAX_STEPS or type(seed) is not int or not 0 <= seed <= 2**32 - 1: + raise MusicError("invalid_arguments", "Steps or seed is out of range.", "Use 1..{0} steps and a 32-bit unsigned seed.".format(MAX_STEPS)) + if bpm is not None and (type(bpm) is not int or not 30 <= bpm <= 300): + raise MusicError("invalid_arguments", "BPM must be a whole number from 30 to 300.", "Use --bpm 120.") + if time_signature is not None and (type(time_signature) is not int or time_signature not in TIME_SIGNATURES): + raise MusicError("invalid_arguments", "Time signature must be 2, 3, 4 or 6 beats per bar.", "Use --time-signature 4.") + if reference is not None: + path = Path(reference).expanduser() if isinstance(reference, str) else None + if path is None or not path.is_absolute() or not path.is_file() or path.suffix.lower() not in REFERENCE_FORMATS: + raise MusicError("invalid_arguments", "The reference must be an existing absolute audio file.", + "Pass --reference as a {0} file.".format(", ".join(REFERENCE_FORMATS))) + settings = {"bpm": bpm, "time_signature": time_signature, "reference": reference} + return dict({"caption": caption, "lyrics": lyrics, "duration": duration, "steps": steps, "seed": seed}, + **{key: value for key, value in settings.items() if value is not None}) -def plan_music(model_path, caption, lyrics, out, duration=15.0, steps=30, seed=42, - manifests=None, registries=None, root=None): +def _acestep_planner(model): + """The planner beside an ACE-Step checkpoint, after refusing a checkpoint missing what it loads.""" + missing = [name for name in ACESTEP_SIBLINGS if not (model.parent / name / "config.json").is_file()] + if not ((model / "model.safetensors").is_file() or (model / "model.safetensors.index.json").is_file()): + missing.append(model.name + "/model.safetensors") + if not (model / "silence_latent.pt").is_file(): + missing.append(model.name + "/silence_latent.pt") + if missing: + raise MusicError("model_unreadable", "The ACE-Step checkpoint is missing {0}.".format(", ".join(missing)), + "Keep the DiT folder beside vae and Qwen3-Embedding-0.6B in the ACE-Step checkpoints folder.") + planners = sorted(path.name for path in model.parent.glob("acestep-5Hz-lm-*") if (path / "config.json").is_file()) + return ACESTEP_PLANNER if ACESTEP_PLANNER in planners else (planners[0] if planners else None) + + +def plan_music(model_path, caption, lyrics, out, duration=15.0, steps=30, seed=42, bpm=None, time_signature=None, + reference=None, manifests=None, registries=None, root=None): model = Path(model_path).expanduser() try: config = json.loads((model / "config.json").read_text(encoding="utf-8")) @@ -37,7 +72,7 @@ def plan_music(model_path, caption, lyrics, out, duration=15.0, steps=30, seed=4 raise ValueError("An absolute local model directory is required") except (OSError, ValueError) as error: raise MusicError("model_unreadable", str(error), "Pass an existing converted music model directory.") from error - validate_parameters(caption, lyrics, duration, steps, seed) + validate_parameters(caption, lyrics, duration, steps, seed, bpm, time_signature, reference) target = Path(out).expanduser() if not target.is_absolute() or target.suffix.lower() != ".wav" or target.exists() or target.is_symlink() or not target.parent.is_dir(): raise MusicError("invalid_arguments", "Output must be a new absolute WAV path.", "Choose a new .wav file in an existing directory.") @@ -52,13 +87,33 @@ def plan_music(model_path, caption, lyrics, out, duration=15.0, steps=30, seed=4 except ValueError as error: raise MusicError("model_unreadable", str(error), "Restore the checkpoint's tokenizer files before generating music.") from error manifest = manifests[sorted(hits, key=lambda hit: hit["backend"])[0]["backend"]] + acestep = manifest["id"] == "ace-step" + if not acestep and (bpm, time_signature, reference) != (None, None, None): + raise MusicError("invalid_arguments", "BPM, time signature and reference apply to ACE-Step models only.", + "Drop --bpm, --time-signature and --reference for this model.") + turbo = acestep and config.get("is_turbo") is True + limit = ACESTEP_TURBO_STEPS if turbo else STEP_LIMITS.get(manifest["id"], MAX_STEPS) + if steps > limit: + raise MusicError("invalid_arguments", "This model takes 1..{0} steps.".format(limit), + "Use --steps 8." if turbo else "Use --steps {0} or fewer.".format(limit)) + planner = _acestep_planner(model) if acestep else None if not is_installed(manifest, root): - raise MusicError("backend_not_installed", "The audio backend is not installed.", "Install mlx-audio first.") - return {"backend": manifest["id"], "model": str(model), "out": str(target), + raise MusicError("backend_not_installed", "The {0} backend is not installed.".format(manifest["id"]), + "Install it first: mlx-agent backend install {0}.".format(manifest["id"])) + plan = {"backend": manifest["id"], "model": str(model), "out": str(target), "duration": duration, "steps": steps, "seed": seed, - "argv": [str(backend_python(manifest, root)), str(MUSIC_RUNNER), "--model", str(model), - "--caption=" + caption, "--lyrics=" + lyrics, "--out", str(target), + "argv": [str(backend_python(manifest, root)), str(ACESTEP_RUNNER if acestep else MUSIC_RUNNER), + "--model", str(model), "--caption=" + caption, "--lyrics=" + lyrics, "--out", str(target), "--duration", str(duration), "--steps", str(steps), "--seed", str(seed)]} + if acestep: + # Turbo checkpoints are distilled for shift 3 and ignore guidance; the others use ACE-Step's defaults. + plan.update(bpm=bpm, time_signature=time_signature, reference=reference, planner=planner, + shift=3.0 if turbo else 1.0, guidance=7.0) + plan["argv"] += ["--shift", str(plan["shift"]), "--guidance", str(plan["guidance"])] + for flag, value in (("--bpm", bpm), ("--time-signature", time_signature), ("--reference", reference), ("--planner", planner)): + if value is not None: + plan["argv"] += [flag, str(value)] + return plan def _wrote_output(value, plan): @@ -66,18 +121,25 @@ def _wrote_output(value, plan): return value.get("path") == plan["out"] and target.is_file() and not target.is_symlink() +def _unknown_checkpoint(plan, detail): + return ("ACE-Step does not know the checkpoint folder {0}.".format(detail), + "Keep the checkpoint under its published name, such as acestep-v15-turbo or acestep-v15-xl-sft.") + + CONTRACT = RunnerContract( verb="music", error=MusicError, accept=_wrote_output, action="generate the music", remediation="Check local model completeness and the audio backend.", activity="Music generation", timeout_remediation="Use a shorter duration or a larger timeout.", + refusals={"unknown_checkpoint": _unknown_checkpoint}, # Generation never resolves or downloads missing weights or tokenizer files. environment={"HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1"}, ) -def run_music(plan, manifests=None, root=None, timeout=3600, runner=subprocess.run): +def run_music(plan, manifests=None, root=None, timeout=DEFAULT_TIMEOUT_SECONDS, runner=subprocess.run): result = invoke(plan, CONTRACT, manifests, root, timeout, runner) keys = ("path", "sample_rate", "audio_seconds", "seconds", "load_seconds", "real_time_factor", "peak_memory_gb") + settings = {key: plan[key] for key in ("bpm", "time_signature", "reference", "planner", "shift", "guidance") if key in plan} return dict({"schema": "music/1", "backend": plan["backend"], "model": plan["model"], "duration": plan["duration"], "steps": plan["steps"], "seed": plan["seed"]}, - **{key: result.get(key) for key in keys}) + **settings, **{key: result.get(key) for key in keys}) diff --git a/packages/codex/mlx-agent/src/mlx_agent/music_runner.py b/packages/codex/mlx-agent/src/mlx_agent/music_runner.py index 8f3d6c8..0def5ef 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/music_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/music_runner.py @@ -1,12 +1,18 @@ """Run inside the isolated music backend; write a new WAV and measured metrics.""" import argparse +from functools import lru_cache import json from pathlib import Path import time from types import MethodType import wave +if __package__: + from .runner_model_cache import load_model +else: + from runner_model_cache import load_model + def tokenizer_directory(model_path): """Resolve the real tokenizer in raw and exported MiniMax checkpoint layouts.""" @@ -27,12 +33,22 @@ def configure_tokenizer(model, model_path): if model.model_type != "minimax_music3": return directory = tokenizer_directory(model_path) + existing = getattr(getattr(model, "_text_ids", None), "__func__", None) + if getattr(existing, "_mlx_agent_tokenizer_directory", None) == directory: + return from mlx_audio.music.models.minimax_music3.minimax_music3 import _encode_official_text_pair from mlx_audio.music.models.minimax_music3.prompt import assemble_prompt + config = model.config + + @lru_cache(maxsize=8) + def encode(caption, lyrics): + return _encode_official_text_pair(assemble_prompt(caption, lyrics), config, directory) + def text_ids(instance, caption, lyrics): - return _encode_official_text_pair(assemble_prompt(caption, lyrics), instance.config, directory) + return encode(caption, lyrics) + text_ids._mlx_agent_tokenizer_directory = directory model._text_ids = MethodType(text_ids, model) @@ -49,8 +65,13 @@ def main(argv=None): from mlx_audio.music import load started = time.perf_counter() - model = load(args.model) + model = load_model(load, args.model) configure_tokenizer(model, args.model) + if __package__: + from .music_speed import configure_depth_cache + else: + from music_speed import configure_depth_cache + configure_depth_cache(model) load_seconds = time.perf_counter() - started mx.reset_peak_memory() started = time.perf_counter() diff --git a/packages/codex/mlx-agent/src/mlx_agent/music_speed.py b/packages/codex/mlx-agent/src/mlx_agent/music_speed.py new file mode 100644 index 0000000..a7bd6d6 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/music_speed.py @@ -0,0 +1,71 @@ +"""Frame-local causal prefix reuse for the pinned MiniMax music backend.""" + +import mlx.core as mx +import mlx.nn as nn + + +class _DepthCache(nn.Module): + """Append one codebook position; reset for the next frame's two-position prefix.""" + + def __init__(self, decoder): + super().__init__() + self.decoder = decoder + object.__setattr__(self, "_prefix", None) + + @property + def projection(self): + return self.decoder.projection + + @property + def audio_embeddings(self): + return self.decoder.audio_embeddings + + @property + def audio_heads(self): + return self.decoder.audio_heads + + def __call__(self, embeddings): + batch, length, _ = embeddings.shape + previous = self._prefix + if (length == 2 or previous is None or length != previous[0] + 1 + or batch != previous[1] or embeddings.dtype != previous[2]): + offset, past, outputs = 0, [None] * len(self.decoder.layers), None + else: + offset, past, outputs = previous[0], previous[3], previous[4] + hidden = embeddings[:, offset:] + self.decoder.pos_embedding(mx.arange(offset, length)) + keys_values = [] + for layer, cached in zip(self.decoder.layers, past): + normalized = layer.input_layernorm(hidden) + attention = layer.attn + heads, dim, count = attention.heads, attention.head_dim, hidden.shape[1] + q, k, v = (project(normalized).reshape(batch, count, heads, dim).transpose(0, 2, 1, 3) + for project in (attention.to_q, attention.to_k, attention.to_v)) + if cached is not None: + q, k, v = (mx.concatenate([old, new], axis=2) for old, new in zip(cached, (q, k, v))) + keys_values.append((q, k, v)) + # Preserve prefix-shaped attention: its GPU rounding is closer to the + # original than single-query SDPA. Projections/FFN only visit new rows. + attended = mx.fast.scaled_dot_product_attention(q, k, v, scale=dim ** -0.5, mask="causal") + attended = attended[:, :, -count:] + hidden = hidden + attention.to_out(attended.transpose(0, 2, 1, 3).reshape(batch, count, -1)) + normalized = layer.post_attention_layernorm(hidden) + hidden = hidden + layer.down_proj(nn.silu(layer.gate_proj(normalized)) * layer.up_proj(normalized)) + hidden = self.decoder.norm(hidden) + if outputs is not None: + hidden = mx.concatenate([outputs, hidden], axis=1) + object.__setattr__(self, "_prefix", (length, batch, embeddings.dtype, keys_values, hidden)) + return hidden + + +def configure_depth_cache(model): + """Wrap a supported decoder once; never change installed backend code or weights.""" + if model.model_type != "minimax_music3": + return False + decoder = model.rvq_depth_decoder + if isinstance(decoder, _DepthCache): + return True + from mlx_audio.music.models.minimax_music3.depth import RVQDepthDecoder + if type(decoder) is not RVQDepthDecoder: + return False + model.rvq_depth_decoder = _DepthCache(decoder) + return True diff --git a/packages/codex/mlx-agent/src/mlx_agent/owned_worker.py b/packages/codex/mlx-agent/src/mlx_agent/owned_worker.py new file mode 100644 index 0000000..07cf861 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/owned_worker.py @@ -0,0 +1,75 @@ +"""Gate native startup behind host ownership and contain the backend process group.""" +import os +from pathlib import Path +import runpy +import shutil +import signal +import sys +import threading +import time +import traceback + + +def command(argv, ready, gate): + executable = shutil.which(argv[0]) + if executable is None: + raise ValueError('The model worker executable is unavailable.') + if Path(executable).name.startswith('python'): + python, arguments = executable, list(argv[1:]) + while arguments and arguments[0] in ('-I', '-B', '-u'): + arguments.pop(0) + else: + with open(executable, 'rb') as stream: + shebang = stream.readline(4096).decode().strip() + python = shebang[2:] if shebang.startswith('#!/') else '' + if not Path(python).is_file() or not Path(python).name.startswith('python'): + raise ValueError('Model workers require an absolute Python interpreter.') + arguments = [executable, *argv[1:]] + if not arguments or (arguments[0].startswith('-') and arguments[0] not in ('-c', '-m')): + raise ValueError('Model workers require a Python entry point.') + return [python, '-I', '-B', str(Path(__file__).resolve()), str(ready), str(gate), str(os.getpid()), *arguments] + + +def main(): + ready, gate, parent = map(int, sys.argv[1:4]) + arguments = sys.argv[4:] + if os.getpid() != os.getpgrp() or os.getsid(0) != os.getpid(): + raise ValueError('Model workers require a private process group.') + if os.getppid() != parent: + return + + def watch_parent(): + while os.getppid() == parent: + time.sleep(.25) + os.killpg(os.getpgrp(), signal.SIGKILL) + + threading.Thread(target=watch_parent, daemon=True).start() + os.write(ready, b'R') + os.close(ready) + try: + if os.read(gate, 1) != b'G': + return + finally: + os.close(gate) + try: + if arguments[0] == '-c': + sys.argv = ['-c', *arguments[2:]] + exec(compile(arguments[1], '', 'exec'), {'__name__': '__main__'}) + elif arguments[0] == '-m': + sys.argv = arguments[1:] + runpy.run_module(arguments[1], run_name='__main__', alter_sys=True) + else: + sys.argv = arguments + sys.path.insert(0, str(Path(arguments[0]).resolve().parent)) + runpy.run_path(arguments[0], run_name='__main__') + except BaseException: + traceback.print_exc() + sys.stderr.flush() + raise + finally: + # A frontend that exits must not leave an engine consuming compute. + os.killpg(os.getpgrp(), signal.SIGKILL) + + +if __name__ == '__main__': + main() diff --git a/packages/codex/mlx-agent/src/mlx_agent/private_serve.py b/packages/codex/mlx-agent/src/mlx_agent/private_serve.py new file mode 100644 index 0000000..5d50e03 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/private_serve.py @@ -0,0 +1,313 @@ +"""Supervised MLX-LM inference over an inherited Unix listener, never TCP.""" +from __future__ import annotations + +import argparse +import errno +import hashlib +import inspect +import io +import http.client +import json +import os +from pathlib import Path +import shutil +import socket +import sys +import tempfile +from http.server import ThreadingHTTPServer +from socketserver import BaseServer + +PRIVATE_PROTOCOL = "inherited-unix-v1" +MAX_BODY = 1024 * 1024 + + +class UnixHTTPConnection(http.client.HTTPConnection): + def __init__(self, path, timeout=120): + super().__init__("127.0.0.1", timeout=timeout) + self.path = path + + def connect(self): + self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.sock.settimeout(self.timeout) + try: + self.sock.connect(self.path) + except BaseException: + self.sock.close() + self.sock = None + raise + + +def worker_command(native, model, descriptor): + python = runtime_python(native[0]) + return [python, str(Path(__file__).resolve()), "--runtime-child", "--model", model, + "--socket-fd", str(descriptor), "--"] + native[1:] + + +class PrivateEndpoint: + """One supervisor-owned listener; no new TCP port or credential in argv.""" + def __init__(self): + # Keep sockaddr_un below Darwin's length limit even with a long TMPDIR. + self.directory = tempfile.TemporaryDirectory(prefix="mlx-worker-", dir="/tmp") + self.path = str(Path(self.directory.name) / "worker.sock") + self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + try: + self.listener.bind(self.path) + os.chmod(self.path, 0o600) + self.listener.listen(16) + except BaseException: + self.close() + raise + + def connection(self, timeout=120): + return UnixHTTPConnection(self.path, timeout) + + def close(self): + self.listener.close() + self.directory.cleanup() + + +def identity(): + return {"protocol": PRIVATE_PROTOCOL, + "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest()} + + +def private_server_class(descriptor): + listener = socket.socket(fileno=descriptor) + try: + if listener.family != socket.AF_UNIX or listener.type != socket.SOCK_STREAM or not listener.getsockname(): + raise ValueError("A bound Unix stream socket inherited from the supervisor is required.") + try: + if not listener.getsockopt(socket.SOL_SOCKET, socket.SO_ACCEPTCONN): + raise ValueError("The inherited Unix socket is not listening.") + except OSError as error: + # Darwin does not expose SO_ACCEPTCONN on Unix sockets. A bound + # Unix stream still cannot become a TCP listener; accept fails if + # the supervisor supplied a bound but non-listening descriptor. + if error.errno != errno.ENOPROTOOPT: + raise + except (OSError, ValueError): + listener.close() + raise ValueError("A listening Unix socket inherited from the supervisor is required.") from None + + class PrivateServer(ThreadingHTTPServer): + daemon_threads = True + block_on_close = False + + def __init__(self, address, handler): + # Upstream may set address_family after resolving its dummy address. + # BaseServer creates no socket; adopt only the validated Unix FD. + BaseServer.__init__(self, listener.getsockname(), handler) + self.socket = listener + self.server_name, self.server_port = "private", 0 + + def get_request(self): + connection, _ = self.socket.accept() + return connection, ("private", 0) + + return PrivateServer + + +def guarded_handler(upstream, model, max_tokens=8192, aliases=()): + class PrivateHandler(upstream): + def setup(self): + self.request.settimeout(120) + super().setup() + + def log_message(self, *args): + pass + + def _set_cors_headers(self): + pass + + def end_headers(self): + self.send_header("X-MLX-Agent-Transport", PRIVATE_PROTOCOL) + super().end_headers() + + def _reply(self, status, value): + raw = json.dumps(value).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.send_header("Connection", "close") + self.end_headers() + self.close_connection = True + self.wfile.write(raw) + + def _guard(self): + hosts = self.headers.get_all("Host", []) + if len(hosts) != 1 or hosts[0] not in ("127.0.0.1", "localhost") or self.headers.get_all("Origin") is not None: + self._reply(403, {"error": "Private supervisor requests only."}) + return False + return True + + def do_GET(self): + if not self._guard(): + return + if self.path == "/_mlx/private": + self._reply(200, {"protocol": PRIVATE_PROTOCOL}) + elif self.path == "/v1/models": + self._reply(200, {"data": [{"id": model}]}) + else: + self._reply(404, {"error": "Unknown private endpoint."}) + + def do_OPTIONS(self): + self._reply(405, {"error": "Browser preflights are not supported."}) + + def do_POST(self): + if not self._guard(): + return + if self.path != "/v1/chat/completions": + self._reply(404, {"error": "Only configured-model chat inference is supported."}) + return + if (self.headers.get_all("Content-Type", []) != ["application/json"]): + self._reply(415, {"error": "Use application/json."}) + return + lengths = self.headers.get_all("Content-Length", []) + if len(lengths) != 1 or self.headers.get_all("Transfer-Encoding") is not None or not lengths[0].isascii() or not lengths[0].isdigit(): + self._reply(400, {"error": "Use one bounded Content-Length."}) + return + if len(lengths[0]) > 8: + self._reply(413, {"error": "Request exceeds the private worker limit."}) + return + length = int(lengths[0]) + if not 0 < length <= MAX_BODY: + self._reply(413, {"error": "Request exceeds the private worker limit."}) + return + try: + raw = self.rfile.read(length) + body = json.loads(raw) + if len(raw) != length or not isinstance(body, dict): + raise ValueError() + if body.get("model", "default_model") not in ("default_model", model, *aliases): + raise ValueError() + if any(body.get(key) is not None for key in ("adapter_path", "adapter", "draft_model", "draft_adapter", "trust_remote_code")): + raise ValueError() + messages = body.get("messages") + if not isinstance(messages, list) or any(not isinstance(m, dict) or not isinstance(m.get("content"), str) + or m.get("role") not in ("system", "user", "assistant", "tool") for m in messages): + raise ValueError() + tokens = body.get("max_tokens", max_tokens) + if type(tokens) is not int or tokens <= 0 or type(body.get("stream", False)) is not bool: + raise ValueError() + completion_tokens = body.get("max_completion_tokens", tokens) + if type(completion_tokens) is not int or completion_tokens <= 0: + raise ValueError() + except (ValueError, UnicodeError, TypeError): + self._reply(400, {"error": "Invalid fixed-model text chat request."}) + return + body["model"] = model + body["max_tokens"] = min(tokens, completion_tokens, max_tokens) + body.pop("max_completion_tokens", None) + encoded = json.dumps(body).encode() + original = self.rfile + self.rfile = io.BytesIO(encoded) + del self.headers["Content-Length"] + self.headers["Content-Length"] = str(len(encoded)) + try: + super().do_POST() + finally: + self.rfile = original + + return PrivateHandler + + +def runtime_python(executable): + """Resolve only the Python interpreter named by a venv-owned MLX entrypoint.""" + sibling = Path(sys.executable).parent / "mlx_lm.server" + resolved = str(sibling) if executable == "mlx_lm.server" and sibling.is_file() else shutil.which(executable) + if resolved is None: + raise ValueError("mlx_lm.server is not installed.") + entry = Path(resolved).resolve() + if entry.name != "mlx_lm.server" or not (entry.parent.parent / "pyvenv.cfg").is_file(): + raise ValueError("mlx_lm.server must belong to an explicit Python virtual environment.") + with entry.open("rb") as source: + first = source.readline(4096).decode().strip() + for name in ("python", "python3"): + python = entry.parent / name + if python.is_file() and first == "#!" + str(python): + return str(python) + raise ValueError("The MLX entrypoint does not identify its virtual environment interpreter.") + + +def run_runtime(model, descriptor, forwarded): + digest = os.environ.pop('MLX_AGENT_WORKER_KEY_SHA256', None) + if digest is not None: + if __package__: + from .inference_auth import protect_worker + else: + from inference_auth import protect_worker + protect_worker(digest) + # Adopt the listener before importing a runtime that could load weights. + server_class = private_server_class(descriptor) + os.environ.update(HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", HF_DATASETS_OFFLINE="1") + from mlx_lm import server + original_run = server.run + parameters = inspect.signature(original_run).parameters + if "server_class" not in parameters or "handler_class" not in parameters: + raise ValueError("This MLX-LM version cannot serve an inherited private listener.") + local = Path(model).expanduser() + if not local.is_dir(): + from huggingface_hub import try_to_load_from_cache + cached = try_to_load_from_cache(model, "config.json") + if not isinstance(cached, str): + raise ValueError("Prepare the model in the local cache before managed serving.") + local = Path(cached).parent + local = local.resolve() + maximum = 8192 + if "--max-tokens" in forwarded: + maximum = int(forwarded[forwarded.index("--max-tokens") + 1]) + if not 1 <= maximum <= 65536: + raise ValueError("Invalid private worker token limit.") + handler = guarded_handler(server.APIHandler, str(local), maximum, aliases=(model,)) + + def private_run(*args, **kwargs): + if len(args) > 3: + raise ValueError("Unsupported MLX-LM server initialization.") + return original_run(*args, **dict(kwargs, server_class=server_class, handler_class=handler)) + + previous = sys.argv + server.run = private_run + try: + # Locked arguments come last: forwarded serving options cannot select a + # different model, host, or public listener. + sys.argv = [previous[0]] + forwarded + ["--model", str(local), "--host", "127.0.0.1", "--port", "0", "--log-level", "ERROR"] + server.main() + finally: + server.run = original_run + sys.argv = previous + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--describe", action="store_true") + parser.add_argument("--model") + parser.add_argument("--socket-fd", type=int) + parser.add_argument("--runtime-executable", default="mlx_lm.server") + parser.add_argument("--runtime-child", action="store_true", help=argparse.SUPPRESS) + args, forwarded = parser.parse_known_args(argv) + if args.describe: + if forwarded or args.model is not None or args.socket_fd is not None: + parser.error("--describe does not start a worker or accept model arguments") + print(json.dumps(identity())) + return 0 + if not args.model or args.socket_fd is None or args.socket_fd < 3: + parser.error("a model and supervisor-owned --socket-fd >= 3 are required") + if forwarded[:1] == ["--"]: + forwarded = forwarded[1:] + if not args.runtime_child: + python = runtime_python(args.runtime_executable) + os.set_inheritable(args.socket_fd, True) + command = [python, str(Path(__file__).resolve()), "--runtime-child", "--model", args.model, + "--socket-fd", str(args.socket_fd), "--"] + forwarded + os.execv(python, command) + run_runtime(args.model, args.socket_fd, forwarded) + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except (OSError, ValueError, ImportError): + # Runtime errors may include private paths or request content. + print("Private MLX worker unavailable; verify the installed runtime and local model.", file=sys.stderr) + raise SystemExit(1) diff --git a/packages/codex/mlx-agent/src/mlx_agent/process_table.py b/packages/codex/mlx-agent/src/mlx_agent/process_table.py new file mode 100644 index 0000000..3812c61 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/process_table.py @@ -0,0 +1,110 @@ +"""The live process table read in-process: libproc on macOS, /proc elsewhere. + +Rows exclude zombies, which no longer hold compute or memory. Start times and command lines +still come from ps, for only the PIDs that need them, so recorded identities keep one format. +""" +import ctypes +import errno +import os +import subprocess +import sys +from functools import lru_cache + +_SHORT_INFO = 13 # PROC_PIDT_SHORTBSDINFO is readable for every user's processes. +_ZOMBIE = 5 # SZOMB + + +class _ShortInfo(ctypes.Structure): + # Public Darwin ABI: struct proc_bsdshortinfo in sys/proc_info.h. + _fields_ = [('pid', ctypes.c_uint32), ('ppid', ctypes.c_uint32), ('pgid', ctypes.c_uint32), + ('status', ctypes.c_uint32), ('comm', ctypes.c_char * 16), ('flags', ctypes.c_uint32), + ('uid', ctypes.c_uint32), ('gid', ctypes.c_uint32), ('ruid', ctypes.c_uint32), + ('rgid', ctypes.c_uint32), ('svuid', ctypes.c_uint32), ('svgid', ctypes.c_uint32), + ('rfu', ctypes.c_uint32)] + + +@lru_cache(maxsize=1) +def _libproc(): + library = ctypes.CDLL('/usr/lib/libproc.dylib', use_errno=True) + library.proc_listallpids.argtypes = [ctypes.c_void_p, ctypes.c_int] + library.proc_listpgrppids.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_int] + library.proc_pidinfo.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_int] + for function in (library.proc_listallpids, library.proc_listpgrppids, library.proc_pidinfo): + function.restype = ctypes.c_int + return library + + +def _darwin_pids(group=None): + capacity = 4096 + while True: + buffer = (ctypes.c_int * capacity)() + library = _libproc() + ctypes.set_errno(0) + found = (library.proc_listallpids(buffer, ctypes.sizeof(buffer)) if group is None + else library.proc_listpgrppids(group, buffer, ctypes.sizeof(buffer))) + code = ctypes.get_errno() + if found < 0 or found == 0 and code: + raise OSError(code, 'The process table is unavailable.') + if found < capacity: # A full buffer may have dropped PIDs. + return [pid for pid in buffer[:found] if pid > 0] + capacity *= 2 + + +def _darwin_row(pid): + info = _ShortInfo() + if _libproc().proc_pidinfo(pid, _SHORT_INFO, 0, ctypes.byref(info), ctypes.sizeof(info)) == ctypes.sizeof(info): + return None if info.status == _ZOMBIE else (info.ppid, info.pgid) + code = ctypes.get_errno() + if code == errno.ESRCH: # Exited, or a zombie awaiting its parent. + return None + raise OSError(code, 'Process {0} cannot be inspected.'.format(pid)) + + +def _proc_pids(): + try: + return [int(name) for name in os.listdir('/proc') if name.isdigit()] + except OSError as error: + raise OSError(error.errno, 'The process table is unavailable.') from error + + +def _proc_row(pid): + try: + with open('/proc/{0}/stat'.format(pid), 'rb') as stream: + # State, parent and group follow the parenthesised command name, which may contain ')'. + fields = stream.read().rsplit(b')', 1)[1].split() + except (FileNotFoundError, ProcessLookupError): + return None + return None if fields[0] in (b'Z', b'X') else (int(fields[1]), int(fields[2])) + + +def rows(pids=None): + """{pid: (parent, group)} for live processes; all of them, or the PIDs asked.""" + darwin = sys.platform == 'darwin' + if pids is None: + pids = _darwin_pids() if darwin else _proc_pids() + read = _darwin_row if darwin else _proc_row + return {pid: row for pid in pids if (row := read(pid)) is not None} + + +def group(pgid): + """Live members of one process group.""" + candidates = rows(_darwin_pids(pgid)) if sys.platform == 'darwin' else rows() + return sorted(pid for pid, (_, member_group) in candidates.items() if member_group == pgid) + + +def identities(pids): + """{pid: 'start command'} for the live PIDs asked, in the form ``compute.process_identity`` returns.""" + pids = sorted(set(pids)) + if not pids: + return {} + run = subprocess.run(['/bin/ps', '-ww', '-o', 'pid=,lstart=,command=', '-p', ','.join(map(str, pids))], + capture_output=True, text=True, timeout=5) + # ps exits 1 when a listed PID is gone and still prints the live ones. + if run.returncode not in (0, 1) or run.returncode == 1 and run.stderr.strip(): + raise OSError('The process table is unavailable.') + result = {} + for line in run.stdout.splitlines(): + fields = line.split(None, 1) + if len(fields) == 2: + result[int(fields[0])] = fields[1].strip() + return result diff --git a/packages/codex/mlx-agent/src/mlx_agent/process_tree.py b/packages/codex/mlx-agent/src/mlx_agent/process_tree.py index a70b39e..5233b3f 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/process_tree.py +++ b/packages/codex/mlx-agent/src/mlx_agent/process_tree.py @@ -16,6 +16,15 @@ def _snapshot(): return result +def group_snapshot(pgid): + """``_snapshot`` rows for one process group, without reading every process's command line.""" + from .process_table import group, identities, rows + members = rows(group(pgid)) + observed = identities(members) + return {pid: (parent, member_group, observed[pid]) for pid, (parent, member_group) in members.items() + if pid in observed} + + def descendants(pid): if type(pid) is not int or pid <= 0: raise ValueError("An owned process requires a positive PID.") diff --git a/packages/codex/mlx-agent/src/mlx_agent/protected_service.py b/packages/codex/mlx-agent/src/mlx_agent/protected_service.py new file mode 100644 index 0000000..8a78d15 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/protected_service.py @@ -0,0 +1,68 @@ +"""Foreground authenticated MLX service for an existing service manager.""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +import secrets +import signal +import tempfile +import threading + +PROTOCOL = "protected-service-v1" + + +def identity(): + root = Path(__file__).parent + digest = hashlib.sha256() + for name in ("cli.py", "identity_pass.py", "protected_service.py", "private_serve.py", "serving_access.py", + "jit_serve.py", "serve.py", "serving_plan.py", "inference_auth.py", "protected_worker.py", "worker_transport.py"): + digest.update(name.encode()) + digest.update((root / name).read_bytes()) + return {"protocol": PROTOCOL, "source_sha256": digest.hexdigest()} + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--describe", action="store_true") + parser.add_argument("--model") + parser.add_argument("--api-key-file") + parser.add_argument("--port", type=int) + parser.add_argument("--max-tokens", type=int, default=8192) + parser.add_argument("--runtime-executable", default="mlx_lm.server") + args = parser.parse_args(argv) + if args.describe: + if args.model or args.api_key_file or args.port is not None: + parser.error("--describe accepts no service inputs") + print(json.dumps(identity())) + return 0 + if not args.model or not args.api_key_file or args.port is None: + parser.error("--model, --api-key-file and --port are required") + if not Path(args.model).is_dir(): + parser.error("--model must be an existing local model directory") + from .identity_pass import recheck_bound_identity + from .serve import load_recipes, plan_start + from .jit_serve import make_server + with tempfile.TemporaryDirectory(prefix="mlx-service-", dir="/tmp") as directory: + # The secure state writer refuses symlink components, including macOS /tmp. + directory = str(Path(directory).resolve()) + plan = plan_start(None, "mlx_lm", load_recipes(), path=args.model, jit=True, + receipts_dir=directory, port=args.port, max_tokens=args.max_tokens, + api_key_file=args.api_key_file, runtime_executable=args.runtime_executable) + from .worker_transport import gateway_config + config = gateway_config(plan, control_token=secrets.token_hex(32), + state_path=str(Path(directory) / "state.json")) + recheck_bound_identity(plan) + server = make_server(config, args.port) + previous = {sig: signal.getsignal(sig) for sig in (signal.SIGINT, signal.SIGTERM)} + try: + for sig in previous: + signal.signal(sig, lambda *_: threading.Thread(target=server.shutdown, daemon=True).start()) + server.serve_forever() + finally: + server.controller.close() + server.server_close() + for sig, handler in previous.items(): + signal.signal(sig, handler) + return 0 diff --git a/packages/codex/mlx-agent/src/mlx_agent/protected_worker.py b/packages/codex/mlx-agent/src/mlx_agent/protected_worker.py new file mode 100644 index 0000000..a7cdb7c --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/protected_worker.py @@ -0,0 +1,53 @@ +"""Run an owned HTTP model worker with mandatory private upstream authentication.""" +import os +from pathlib import Path +import runpy +import shutil +import sys + +if __package__ in (None, ''): + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from mlx_agent.inference_auth import protect_worker + +WORKER_DIGEST = 'MLX_AGENT_WORKER_KEY_SHA256' + + +def command(argv, runtime): + executable = shutil.which(argv[0]) + if executable is None: + raise ValueError('The authenticated model worker executable is unavailable.') + if Path(executable).name.startswith('python'): + arguments = list(argv[1:]) + while arguments and arguments[0] in ('-I', '-B', '-u'): + arguments.pop(0) + if not arguments or arguments[0].startswith('-'): + raise ValueError('Authenticated workers require a Python server entry point.') + entry, arguments = arguments[0], arguments[1:] + python = executable + else: + entry, arguments = executable, list(argv[1:]) + with open(entry, 'rb') as stream: + shebang = stream.readline(4096).decode('utf-8').strip() + python = shebang[2:] if shebang.startswith('#!/') else '' + if not Path(python).is_file() or not Path(python).name.startswith('python'): + raise ValueError('Authenticated workers require a Python runtime with an absolute interpreter.') + if runtime not in ('mlx_lm', 'mlx-vlm', 'strata'): + raise ValueError('This HTTP runtime does not support protected serving.') + return [python, '-I', '-B', str(Path(__file__).resolve()), runtime, entry, *arguments] + + +def main(): + runtime, entry, *arguments = sys.argv[1:] + digest = os.environ.pop(WORKER_DIGEST) # missing configuration must never start an open server + if runtime == 'strata': + os.environ.pop('STRATA_API_KEY', None) # this process uses the mandatory upstream verifier instead + if runtime == 'mlx-vlm': + os.environ.pop('MLX_VLM_SERVER_API_KEY', None) + protect_worker(digest, asgi=runtime == 'mlx-vlm') + sys.argv = [entry, *arguments] + runpy.run_path(entry, run_name='__main__') + + +if __name__ == '__main__': + main() diff --git a/packages/codex/mlx-agent/src/mlx_agent/queue_bridge.py b/packages/codex/mlx-agent/src/mlx_agent/queue_bridge.py index 1aaec50..65c79c9 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/queue_bridge.py +++ b/packages/codex/mlx-agent/src/mlx_agent/queue_bridge.py @@ -52,8 +52,21 @@ def unwrap(envelope): error.get("remediation", "Inspect the agent output and retry."), ) +def _preparation_arguments(values): + result = [] + for name in ("backend", "model_type", "subfolder", "source_path", "projector", "fetch_receipt", "downloads_dir", "attempt_id"): + if values.get(name) is not None: + result += ["--" + name.replace("_", "-"), values[name]] + for name in ("require_projector", "require_completion"): + if values.get(name): + result.append("--" + name.replace("_", "-")) + for value in values.get("dependency_fetch_receipts") or []: + result += ["--dependency-fetch-receipt", value] + return result + + def start(agent_path, gguf_path, preview_hash, q_bits=4, out=None, - timeout=DEFAULT_TIMEOUT, runner=None): + timeout=DEFAULT_TIMEOUT, runner=None, **preparation): """Start a reviewed GGUF conversion. The hash must come from a preview.""" argv = [ "convert", "start", "--gguf", gguf_path, "--q-bits", str(q_bits), @@ -61,10 +74,10 @@ def start(agent_path, gguf_path, preview_hash, q_bits=4, out=None, ] if out: argv.extend(["--out", out]) - return unwrap(run(agent_path, argv, timeout=timeout, runner=runner)) + return unwrap(run(agent_path, argv + _preparation_arguments(preparation), timeout=timeout, runner=runner)) def start_repo(agent_path, repo, preview_hash, q_bits=4, out=None, hf_cache=None, - timeout=DEFAULT_TIMEOUT, runner=None): + timeout=DEFAULT_TIMEOUT, runner=None, **preparation): """Start a reviewed HF-cache conversion. The hash must come from a preview.""" argv = [ "convert", "start", "--repo", repo, "--q-bits", str(q_bits), @@ -74,13 +87,13 @@ def start_repo(agent_path, repo, preview_hash, q_bits=4, out=None, hf_cache=None argv.extend(["--out", out]) if hf_cache: argv.extend(["--hf-cache", hf_cache]) - return unwrap(run(agent_path, argv, timeout=timeout, runner=runner)) + return unwrap(run(agent_path, argv + _preparation_arguments(preparation), timeout=timeout, runner=runner)) def jobs(agent_path, timeout=DEFAULT_TIMEOUT, runner=None): """Cross-check conversion receipts against live processes.""" return unwrap(run(agent_path, ["convert", "status"], timeout=timeout, runner=runner)) -def read_convert_receipts(entries, max_bytes=MAX_LOG_BYTES): +def read_convert_receipts(entries, max_bytes=MAX_LOG_BYTES, include_path=False): """Read bounded receipt JSON from paths advertised by convert status.""" receipts = [] for entry in entries or []: @@ -135,5 +148,7 @@ def read_convert_receipts(entries, max_bytes=MAX_LOG_BYTES): "A conversion receipt is not a JSON object.", "Inspect or remove the malformed receipt in the mlx-agent state directory.", ) + if include_path: + receipt["_receipt_path"] = str(location) receipts.append(receipt) return receipts diff --git a/packages/codex/mlx-agent/src/mlx_agent/queue_cli.py b/packages/codex/mlx-agent/src/mlx_agent/queue_cli.py index 236ad74..f7a6d30 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/queue_cli.py +++ b/packages/codex/mlx-agent/src/mlx_agent/queue_cli.py @@ -13,7 +13,7 @@ from mlx_agent.compute import compute_root from mlx_agent.convert import load_receipts, status_convert -from mlx_agent.convert_queue import ConvertQueue, QueueStore, QueueOperationError, QueuePersistenceError, _validated_items +from mlx_agent.convert_queue import ConvertQueue, QueueStore, QueueOperationError, QueuePersistenceError, _validated_items, PREPARATION_FIELDS from mlx_agent import queue_bridge from mlx_agent.transactions import _assert_safe_directory, _assert_safe_target, _open_directory @@ -21,7 +21,7 @@ _FIELDS = { "snapshot": set(), "run": set(), "clear": set(), "cancel": {"id"}, "retry": {"id"}, "move": {"id", "direction"}, - "enqueue": {"kind", "preview_hash", "q_bits", "out", "path", "repo", "hf_cache", "label"}, + "enqueue": {"kind", "preview_hash", "q_bits", "out", "path", "repo", "hf_cache", "label"} | PREPARATION_FIELDS, "adopt-preview": {"source"}, "adopt": {"source", "preview_hash"}, } @@ -127,7 +127,7 @@ def execute(request, path=None, receipts_dir=None): location.unlink() raise return {**plan, "status": "adopted", "backup": str(backup), - "conversion_queue": {"schema_version": "1.1", "items": items}} + "conversion_queue": {"schema_version": "1.2", "items": items}} if location.exists() and location.stat().st_size > MAXIMUM_BYTES: raise ValueError("Queue state exceeds the supported size.") queue = ConvertQueue(location) @@ -154,7 +154,7 @@ def execute(request, path=None, receipts_dir=None): queue.cancel(item["id"]) result = queue.try_start_next(str(Path(__file__).resolve().parents[2])) or {"status": "waiting"} return {**result, "queue_path": str(location), - "conversion_queue": {"schema_version": "1.1", "items": queue.snapshot()}} + "conversion_queue": {"schema_version": "1.2", "items": queue.snapshot()}} def _write_backup(backup, original): diff --git a/packages/codex/mlx-agent/src/mlx_agent/residency.py b/packages/codex/mlx-agent/src/mlx_agent/residency.py new file mode 100644 index 0000000..243456c --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/residency.py @@ -0,0 +1,432 @@ +"""Atomic host memory reservations for independently owned model workers.""" +from contextlib import contextmanager +import fcntl +import json +import os +from pathlib import Path +import stat +from subprocess import SubprocessError +import time + +from .compute import compute_root, process_alive, process_identity, group_members +from .transactions import _atomic_in_directory, _walk_directory + +SCHEMA = 'model-residency/1' +MAX_BYTES = 1024 * 1024 + + +class MemoryAdmissionError(ValueError): + def __init__(self, code, message, details=None): + super().__init__(message) + self.code, self.details = code, details or {} + + +def _bytes(value): + return type(value) is int and 0 <= value <= 2**60 + + +class MemoryRegistry: + """Reserve future allocations; OS headroom already includes resident arrays.""" + def __init__(self, root=None, owner=None, inspector=process_identity, + alive=process_alive, group_probe=group_members, lock_timeout=5, process_probe=None): + self.root = Path(root) if root is not None else compute_root() + self.owner = owner + self.inspector, self.alive, self.group_probe = inspector, alive, group_probe + self.lock_timeout = lock_timeout + self.process_probe = process_probe + + def _owner(self): + if self.owner is None: + identity = self.inspector(os.getpid()) + if not identity: + raise MemoryAdmissionError('memory_owner_unknown', 'Cannot establish memory reservation ownership.') + self.owner = os.getpid(), identity + return list(self.owner) + + @staticmethod + def _validate(value): + if (not isinstance(value, dict) or set(value) != {'schema','entries'} + or value['schema'] != SCHEMA or not isinstance(value['entries'], dict) + or len(value['entries']) > 256): + raise ValueError('Invalid residency registry.') + fields = {'owner','worker','phase','model_key','resident_bytes','workspace_bytes','growth_bytes', + 'reserved_bytes','headroom_bytes','telemetry'} + for key, row in value['entries'].items(): + if (not isinstance(key,str) or not 1 <= len(key) <= 128 or not isinstance(row,dict) + or set(row) - {'execution_bytes'} != fields + or ('execution_bytes' in row and not _bytes(row['execution_bytes'])) + or row['phase'] not in ('reserved','launching','resident') + or not isinstance(row['model_key'],str) or len(row['model_key']) != 64 + or any(not _bytes(row[name]) for name in ('resident_bytes','workspace_bytes','growth_bytes','reserved_bytes','headroom_bytes'))): + raise ValueError('Invalid residency entry.') + owner = row['owner'] + if (not isinstance(owner,list) or len(owner) != 2 or type(owner[0]) is not int + or owner[0] <= 0 or not isinstance(owner[1],str) or not owner[1]): + raise ValueError('Invalid reservation owner.') + worker = row['worker'] + if worker is not None and (not isinstance(worker,dict) or set(worker) != {'pid','identity','pgid'} + or any(type(worker[n]) is not int or worker[n] <= 0 for n in ('pid','pgid')) + or not isinstance(worker['identity'],str) or not worker['identity']): + raise ValueError('Invalid worker owner.') + if row['telemetry'] is not None: + from .worker_telemetry import validate + validate(row['telemetry']) + return value + + def _live(self, pid, identity): + if not self.alive(pid): + return False + observed = self.inspector(pid) + return not observed or observed == identity + + def _prune(self, rows): + for key, row in list(rows.items()): + owner = row['owner'] + if self.owner is not None and owner == list(self.owner): + continue + try: + if self._live(*owner): + continue + worker = row['worker'] + if worker is None: + if row['phase'] != 'reserved': + continue # Launch may have occurred before its PID was persisted. + elif self._live(worker['pid'],worker['identity']) or self.group_probe(worker['pgid']): + continue + except (OSError, ValueError, SubprocessError): + continue # Unknown ownership never authorizes reclaiming memory. + del rows[key] + + @contextmanager + def _locked(self): + descriptor = None + directory_fd = None + try: + _, directory_fd = _walk_directory(self.root, create=True) + info = os.fstat(directory_fd) + if info.st_uid != os.getuid() or info.st_mode & 0o077: + raise ValueError('Memory state requires a private owned directory.') + try: + descriptor = os.open('memory.lock',os.O_CREAT|os.O_EXCL|os.O_RDWR|os.O_NOFOLLOW,0o600,dir_fd=directory_fd) + except FileExistsError: + descriptor = os.open('memory.lock',os.O_RDWR|os.O_NOFOLLOW,dir_fd=directory_fd) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_nlink != 1: + raise ValueError('Invalid memory lock.') + deadline = time.monotonic() + self.lock_timeout + while True: + try: + fcntl.flock(descriptor,fcntl.LOCK_EX|fcntl.LOCK_NB) + break + except BlockingIOError: + if time.monotonic() >= deadline: + raise MemoryAdmissionError('memory_registry_busy','Another memory admission is still in progress.') + time.sleep(.01) + current = os.stat('memory.lock',dir_fd=directory_fd,follow_symlinks=False) + if (current.st_dev,current.st_ino) != (info.st_dev,info.st_ino): + raise ValueError('Memory lock identity changed.') + try: + source = os.open('memory.json',os.O_RDONLY|os.O_NOFOLLOW,dir_fd=directory_fd) + except FileNotFoundError: + value = {'schema':SCHEMA,'entries':{}} + else: + with os.fdopen(source,'rb') as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_nlink != 1 or info.st_size > MAX_BYTES: + raise ValueError('Invalid memory registry file.') + value = self._validate(json.loads(stream.read(MAX_BYTES+1))) + original = json.dumps(value,allow_nan=False,separators=(',',':')).encode() + self._prune(value['entries']) + yield value['entries'] + encoded = json.dumps(value,allow_nan=False,separators=(',',':')).encode() + if len(encoded) > MAX_BYTES: + raise ValueError('Memory registry exceeded its limit.') + if encoded != original: + _atomic_in_directory(self.root,'memory.json',encoded,0o600) + except MemoryAdmissionError: + raise + except (OSError,ValueError,TypeError,KeyError,RecursionError) as error: + raise MemoryAdmissionError('memory_registry_invalid',str(error)) from error + finally: + if descriptor is not None:os.close(descriptor) + if directory_fd is not None:os.close(directory_fd) + + @staticmethod + def _summary(rows): + return {'schema':SCHEMA,'entries':len(rows), + 'resident_bytes':sum(r['resident_bytes'] for r in rows.values()), + 'reserved_bytes':sum(r['reserved_bytes'] for r in rows.values()), + 'headroom_bytes':max((r['headroom_bytes'] for r in rows.values()),default=0)} + + def _own(self, rows, key): + row = rows[key] + if row['owner'] != self._owner(): + raise MemoryAdmissionError('memory_owner_changed','The reservation belongs to another process.') + return row + + def _admit(self, rows, key, amount, headroom, probe): + """Inspect fresh headroom while all competing admissions hold this lock.""" + others = [r for k,r in rows.items() if k != key] + pending = sum(r['reserved_bytes'] for r in others) + available = probe() + requested = headroom() if callable(headroom) else headroom + if not _bytes(requested): + raise MemoryAdmissionError('memory_unknown','Invalid headroom reserve.') + floor = max([requested]+[r['headroom_bytes'] for r in others]) + details = {'available_bytes':available,'required_available_bytes':amount+pending+floor, + 'other_reserved_bytes':pending,'headroom_bytes':floor,'requested_headroom_bytes':requested, + 'captured_at':time.time(),'estimated':True, 'requested_bytes':amount, + 'other_resident_bytes':sum(r['resident_bytes'] for r in others)} + try: + budget = self._agent_budget(rows, (key, amount)) + except MemoryAdmissionError as error: + error.details = dict(details, **error.details) + raise + if budget is not None: + details['agent_budget'] = budget + if not budget['within_budget']: + raise MemoryAdmissionError('agent_memory_budget_exceeded', + 'The request exceeds the shared agent memory budget; unload an idle model first.', details) + if not _bytes(available): + raise MemoryAdmissionError('memory_unknown','OS memory headroom is unavailable.',details) + if available < details['required_available_bytes']: + raise MemoryAdmissionError('insufficient_headroom','Insufficient memory for pending model allocations and application headroom.',details) + return details + + def reserve(self, key, model_key, resident_bytes, workspace_bytes, headroom_bytes, probe, growth_bytes=0): + """Reserve a cold load before it can allocate weights or workspace.""" + if (any(not _bytes(v) for v in (resident_bytes,workspace_bytes,growth_bytes)) + or not (_bytes(headroom_bytes) or callable(headroom_bytes))): + raise MemoryAdmissionError('memory_unknown','Model memory estimate is unavailable.') + with self._locked() as rows: + if key in rows:self._own(rows,key) + details = self._admit(rows,key,resident_bytes+workspace_bytes+growth_bytes,headroom_bytes,probe) + if key not in rows and len(rows) >= 256: + raise MemoryAdmissionError('memory_registry_full','Too many model reservations.') + rows[key] = {'owner':self._owner(),'worker':None,'phase':'reserved','model_key':model_key, + 'resident_bytes':resident_bytes,'workspace_bytes':workspace_bytes,'growth_bytes':growth_bytes, + 'reserved_bytes':resident_bytes+workspace_bytes+growth_bytes,'headroom_bytes':details['requested_headroom_bytes'],'telemetry':None} + self._validate({'schema':SCHEMA,'entries':rows}) + return dict(details,registry=self._summary(rows),allocation=dict(rows[key])) + + def launching(self,key): + with self._locked() as rows: + row=self._own(rows,key) + row['phase']='launching' + return dict(registry=self._summary(rows),allocation=dict(row)) + + def bind_worker(self,key,pid,identity,pgid): + with self._locked() as rows: + self._own(rows,key)['worker']={'pid':pid,'identity':identity,'pgid':pgid} + self._validate({'schema':SCHEMA,'entries':rows}) + return dict(registry=self._summary(rows),allocation=dict(rows[key])) + + def settle(self,key,resident_bytes=None,workspace_bytes=0,telemetry=None): + """Account for materialized arrays without charging them to headroom again.""" + if not _bytes(workspace_bytes) or resident_bytes is not None and not _bytes(resident_bytes): + raise MemoryAdmissionError('memory_unknown','Invalid resident allocation.') + if telemetry is not None: + from .worker_telemetry import validate + validate(telemetry) + with self._locked() as rows: + row=self._own(rows,key) + row.pop('execution_bytes', None) + row['phase']='resident' + row['reserved_bytes']=workspace_bytes + if resident_bytes is not None:row['resident_bytes']=resident_bytes + if telemetry is not None:row['telemetry']=telemetry + return dict(registry=self._summary(rows),allocation=dict(row)) + + def reserve_workspace(self,key,amount,probe): + """Reserve the next job's workspace without replacing its warm worker.""" + if not _bytes(amount):raise MemoryAdmissionError('memory_unknown','Invalid workspace estimate.') + with self._locked() as rows: + row=self._own(rows,key) + details=self._admit(rows,key,amount,row['headroom_bytes'],probe) + row['reserved_bytes']=amount + return dict(details,registry=self._summary(rows),allocation=dict(row)) + + def release(self,key): + with self._locked() as rows: + if key in rows: + self._own(rows,key) + del rows[key] + return self._summary(rows) + + def set_headroom(self,key,amount): + if not _bytes(amount):raise MemoryAdmissionError('memory_unknown','Invalid headroom reserve.') + with self._locked() as rows: + row=self._own(rows,key) + row['headroom_bytes']=amount + return dict(registry=self._summary(rows),allocation=dict(row)) + + def _agent_budget(self, rows, replacement=None): + from .memory_budget import read_policy, process_snapshot, account, identified_pids + policy = read_policy(self.root) + if policy is None: + return None + try: + processes = self.process_probe() if self.process_probe else process_snapshot(identified_pids(policy, rows)) + except (OSError, ValueError, SubprocessError) as error: + raise MemoryAdmissionError('memory_unknown', 'Agent process memory is unavailable.') from error + return account(policy, rows, processes, self._owner(), replacement) + + def configure_budget(self, limit_bytes, reserve_bytes=0, external_pids=None): + from .memory_budget import SCHEMA as BUDGET_SCHEMA, validate_policy, process_snapshot, read_policy, identified_pids + with self._locked() as rows: + previous = read_policy(self.root) + processes = (self.process_probe() if self.process_probe + else process_snapshot(identified_pids(previous, rows, external_pids))) + external = list(previous['external']) if previous is not None and external_pids is None else [] + for pid in sorted(set(external_pids or ())): + if type(pid) is not int or pid <= 0 or pid not in processes: + raise MemoryAdmissionError('memory_unknown', 'An external agent process cannot be inspected.') + row = processes[pid] + external.append({'pid': pid, 'identity': row['identity'], 'group': row['group']}) + policy = {'schema': BUDGET_SCHEMA, 'limit_bytes': limit_bytes, + 'reserve_bytes': reserve_bytes, 'external': external} + validate_policy(policy) + from .memory_budget import account + summary = account(policy, rows, processes, self._owner()) + _atomic_in_directory(self.root, 'budget.json', json.dumps(policy).encode(), 0o600) + return summary + + def reserve_execution(self, key, limit_bytes=None, probe=None): + """Reserve a total job ceiling atomically, including already resident memory.""" + if limit_bytes is not None and (not _bytes(limit_bytes) or limit_bytes == 0): + raise MemoryAdmissionError('memory_unknown', 'Invalid job memory cap.') + with self._locked() as rows: + row = self._own(rows, key) + try: + budget = self._agent_budget(rows, (key, 0)) + except MemoryAdmissionError as error: + error.details = dict(error.details, route_limit_bytes=limit_bytes, + registry_resident_bytes=row['resident_bytes'], pending_bytes=row['reserved_bytes'], + workspace_bytes=row['workspace_bytes'], growth_bytes=row['growth_bytes'], + headroom_bytes=row['headroom_bytes']) + raise + resident = row['resident_bytes'] if row['phase'] == 'resident' else 0 + minimum = row['resident_bytes'] + row['workspace_bytes'] + row['growth_bytes'] + if row['phase'] == 'resident': + minimum = max(minimum, resident + row['reserved_bytes'] + row['growth_bytes']) + if budget is not None: + current = budget['allocations'][key] + resident = current['resident_bytes'] + minimum = max(minimum, resident + row['reserved_bytes'] + row['growth_bytes'] + if row['phase'] == 'resident' else current['pending_bytes']) + free = budget['admission_bytes'] - budget['accounted_bytes'] + capacity = resident + current['pending_bytes'] + free + else: + capacity = limit_bytes + details = {'required_bytes': minimum, 'limit_bytes': limit_bytes, + 'resident_bytes': resident, 'pending_bytes': row['reserved_bytes'], + 'workspace_bytes': row['workspace_bytes'], 'growth_bytes': row['growth_bytes'], + 'agent_budget': budget} + if limit_bytes is not None: + if limit_bytes < minimum: + raise MemoryAdmissionError('job_memory_cap_exceeded', + 'The model and workspace exceed this route memory budget; increase --memory-budget-gb.', + details) + if capacity is not None and limit_bytes > capacity: + raise MemoryAdmissionError('agent_memory_budget_exceeded', + 'The route memory budget does not fit the shared admission; retry after another job finishes.', details) + capacity = limit_bytes + if capacity is None: + return None + if capacity < minimum: + raise MemoryAdmissionError('agent_memory_budget_exceeded', + 'Unload an idle model before starting this model job.', details) + amount = capacity - resident if row['phase'] == 'resident' else capacity + if probe is not None: + available = probe() + others = [r for k, r in rows.items() if k != key] + required = amount + sum(r['reserved_bytes'] for r in others) + max( + [row['headroom_bytes']] + [r['headroom_bytes'] for r in others]) + details.update(available_bytes=available, required_available_bytes=required, + headroom_bytes=max([row['headroom_bytes']] + [r['headroom_bytes'] for r in others])) + if not _bytes(available): + raise MemoryAdmissionError('memory_unknown', 'OS memory headroom is unavailable.', details) + if available < required: + raise MemoryAdmissionError('insufficient_headroom', + 'The job memory ceiling does not fit available system headroom.', details) + row['execution_bytes'] = capacity + row['reserved_bytes'] = amount + return capacity + + def shared_execution_enabled(self): + """Sharing is opt-in through the existing host memory budget.""" + from .memory_budget import read_policy + with self._locked(): + return read_policy(self.root) is not None + + def inspect(self): + """Inspect existing state without creating, pruning or rewriting it.""" + result = {'state': 'unknown', 'entries': {}, 'agent_budget': None, 'errors': []} + directory = lock = None + try: + try: + _, directory = _walk_directory(self.root) + except ValueError as error: + if str(error).startswith('path component does not exist:'): + result['state'] = 'uninitialized' + return result + raise + info = os.fstat(directory) + if info.st_uid != os.getuid() or info.st_mode & 0o077: + raise ValueError('Memory state requires a private owned directory.') + try: + lock = os.open('memory.lock', os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) + except FileNotFoundError: + if any(os.path.lexists(self.root / name) for name in ('memory.json', 'budget.json')): + raise ValueError('Memory registry lock is missing.') + result['state'] = 'uninitialized' + return result + info = os.fstat(lock) + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_nlink != 1: + raise ValueError('Invalid memory lock.') + fcntl.flock(lock, fcntl.LOCK_SH | fcntl.LOCK_NB) + current = os.stat('memory.lock', dir_fd=directory, follow_symlinks=False) + if (current.st_dev, current.st_ino) != (info.st_dev, info.st_ino): + raise ValueError('Memory lock identity changed.') + try: + fd = os.open('memory.json', os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) + except FileNotFoundError: + value = {'schema': SCHEMA, 'entries': {}} + else: + with os.fdopen(fd, 'rb') as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_nlink != 1 or info.st_size > MAX_BYTES: + raise ValueError('Invalid memory registry file.') + value = self._validate(json.loads(stream.read(MAX_BYTES + 1))) + rows = value['entries'] + for row in rows.values(): + owner = row['owner'] + if not self.alive(owner[0]) or self.inspector(owner[0]) != owner[1]: + raise ValueError('Memory reservation ownership is uncertain.') + worker = row['worker'] + if worker is not None and (not self.alive(worker['pid']) or self.inspector(worker['pid']) != worker['identity']): + raise ValueError('Memory worker ownership is uncertain.') + result['entries'] = rows + result['agent_budget'] = self._agent_budget(rows) + result['state'] = 'ok' + except (OSError, ValueError, TypeError, KeyError, SubprocessError) as error: + result['errors'].append(str(error)) + finally: + if lock is not None: + os.close(lock) + if directory is not None: + os.close(directory) + return result + + def snapshot(self): + with self._locked() as rows: + result = self._summary(rows) + try: + budget = self._agent_budget(rows) + except MemoryAdmissionError as error: + if error.code != 'memory_unknown': + raise + budget = {'status': 'unavailable', 'error': str(error), 'within_budget': False} + if budget is not None: + result['agent_budget'] = budget + return result diff --git a/packages/codex/mlx-agent/src/mlx_agent/resident_runner.py b/packages/codex/mlx-agent/src/mlx_agent/resident_runner.py new file mode 100644 index 0000000..92cda3b --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resident_runner.py @@ -0,0 +1,209 @@ +"""Bounded, cancellable calls to one isolated backend retaining one local model.""" +import json +import os +import re +from pathlib import Path +import selectors +import subprocess +import time +import threading + +from .resident_worker import MAX_MESSAGE, RUNNERS +from .compute import process_identity +from .task_runtime import _stop + + +class ResidentRunner: + def __init__(self, executable, model, environment=None, log_path=None, port=0): + self.executable, self.model = str(executable), str(model) + self.environment, self.log_path, self.port = environment, log_path, port + self.process, self.response, self.log = None, None, None + self.loaded = False + self.telemetry = None + self.cache_state = None + self.identity = None + self.lock = threading.RLock() + + def _receive(self, argv, timeout, cancelled): + deadline = time.monotonic() + timeout + chunks = bytearray() + with selectors.DefaultSelector() as selector: + selector.register(self.response, selectors.EVENT_READ) + while True: + if cancelled(): + raise InterruptedError("Inference cancelled.") + remaining = deadline - time.monotonic() + if remaining <= 0: + raise subprocess.TimeoutExpired(argv, timeout) + if not selector.select(min(.1, remaining)): + continue + chunk = os.read(self.response, 65536) + if not chunk: + raise OSError("Resident inference worker exited without a result.") + chunks.extend(chunk) + if len(chunks) > MAX_MESSAGE: + raise ValueError("Runner response exceeded its limit.") + if chunks.endswith(b"\n"): + return json.loads(chunks) + + def _start(self, timeout=15, cancelled=lambda: False): + read_fd, write_fd = os.pipe() + self.response = read_fd + try: + if self.log_path: + descriptor = os.open(self.log_path, os.O_CREAT | os.O_APPEND | os.O_WRONLY | getattr(os, "O_NOFOLLOW", 0), 0o600) + self.log = os.fdopen(descriptor, "ab", buffering=0) + self.process = subprocess.Popen([self.executable, str(Path(__file__).with_name("resident_worker.py")), + "--response-fd", str(write_fd), "--model", self.model, "--port", str(self.port)], stdin=subprocess.PIPE, + stdout=self.log or subprocess.DEVNULL, stderr=subprocess.STDOUT, + env=self.environment, pass_fds=(write_fd,), start_new_session=True, umask=0o077) + os.close(write_fd) + write_fd = None + ready = self._receive(self.process.args, timeout, cancelled) + if ready != {"ready": self.process.pid}: + raise ValueError("The resident worker readiness identity did not match its launcher.") + # Framework Python launchers can exec after Popen returns. Bind only + # once the actual worker acknowledges that it reached its request loop. + self.identity = process_identity(self.process.pid) + if not self.identity: + raise OSError("The ready inference worker identity is unavailable.") + except BaseException: + if self.process is not None: + # No request has been sent: only this unreaped direct child can + # exist, and it has not imported a model or spawned inference. + self.process.terminate() + try: + self.process.wait(timeout=3) + except subprocess.TimeoutExpired: + self.process.kill() + self.process.wait(timeout=3) + self._clear() + raise + finally: + if write_fd is not None: + os.close(write_fd) + + def run(self, argv, timeout=3600, cancelled=lambda: False, cache_policy=None, memory_limit_bytes=None, **options): + with self.lock: + return self._run(argv, timeout, cancelled, cache_policy, memory_limit_bytes, **options) + + def _run(self, argv, timeout, cancelled, cache_policy, memory_limit_bytes=None, **options): + script = Path(argv[1]) if len(argv) > 1 else Path("") + if (argv[0] != self.executable or script.parent.resolve() != Path(__file__).parent.resolve() + or script.stem not in RUNNERS or script.suffix != ".py" + or "--model" not in argv or argv[argv.index("--model") + 1] != self.model): + raise ValueError("Resident requests must use the selected local model and an engine inference runner.") + if self.process is not None and self.process.poll() is not None: + self.close() + started = time.monotonic() + try: + if cancelled(): + raise InterruptedError("Inference cancelled.") + if self.process is None: + self._start(timeout=min(timeout, 15), cancelled=cancelled) + message = {"runner": script.stem, "arguments": argv[2:]} + if cache_policy is not None: + message['cache_policy'] = cache_policy + if memory_limit_bytes is not None: + if type(memory_limit_bytes) is not int or not 0 < memory_limit_bytes <= 2**60: + raise ValueError('Invalid worker memory limit.') + message['memory_limit_bytes'] = memory_limit_bytes + raw = json.dumps(message).encode() + b"\n" + if len(raw) > MAX_MESSAGE: + raise ValueError("Runner request exceeded its limit.") + self.process.stdin.write(raw) + self.process.stdin.flush() + remaining = timeout - (time.monotonic() - started) + result = self._receive(argv, max(0, remaining), cancelled) + from .worker_telemetry import validate + self.telemetry = validate(result['memory']) + from .allocator_cache import validate_state + self.cache_state = validate_state(result['cache']) if 'cache' in result else None + self.loaded = result["loaded"] is True + return subprocess.CompletedProcess(argv, result["returncode"], result["stdout"], result["stderr"]) + except BaseException: + self.close() + raise + + def idle_members(self): + """Inspect the completed worker and its standard Python resource tracker.""" + from .process_tree import group_snapshot + if not self.loaded or self.process is None or self.process.poll() is not None: + raise ValueError('Idle inspection requires a loaded worker.') + pid = self.process.pid + expected = {pid: self.identity} + # Framework launchers may exec a different binary before worker readiness. + command = self.identity.split(None, 5)[-1] + worker_executable, marker, _ = command.partition( + ' ' + str(Path(__file__).with_name('resident_worker.py')) + ' --response-fd ') + if not marker: + raise ValueError('The ready worker interpreter cannot be identified.') + environment = self.environment if self.environment is not None else os.environ + # multiprocessing forwards the worker's inherited warning options. + # Match that exact suffix, rather than accepting arbitrary Python flags. + warnings = dict.fromkeys(environment.get('PYTHONWARNINGS', '').split(',')) + warning_flags = ''.join(' -W' + option for option in warnings if option) + for member, (parent, group, identity) in group_snapshot(pid).items(): + if group != pid or member == pid: + continue + command = identity.split(None, 5)[-1] + executable, marker, descriptor = command.partition( + ' -c from multiprocessing.resource_tracker import main;main(') + if warning_flags: + executable = executable.removesuffix(warning_flags) + if (parent != pid or not marker or not re.fullmatch(r'[0-9]+\)', descriptor) + or Path(executable).resolve() != Path(worker_executable).resolve()): + raise ValueError('Unexpected child prevents resident worker idle handoff.') + expected[member] = identity + return expected + + def control_cache(self, policy, reclaim=None): + with self.lock: + if not self.loaded or self.process is None: + raise ValueError('Cache controls require a loaded worker.') + message = {'control': 'cache', 'policy': policy, 'reclaim': reclaim} + try: + self.process.stdin.write(json.dumps(message).encode() + b'\n') + self.process.stdin.flush() + result = self._receive(self.process.args, 10, lambda: False) + from .worker_telemetry import validate + from .allocator_cache import validate_state + self.telemetry = validate(result['memory']) + self.cache_state = validate_state(result['cache']) + if result['loaded'] is not True: + raise ValueError('Cache control changed model residency.') + return result['returncode'] == 0 + except BaseException: + self.close() + raise + + def close(self): + with self.lock: + self._close() + + def _close(self): + process = self.process + if process is not None: + known = {process.pid: self.identity} if self.identity else {} + if not _stop(process, self.identity, known, grace=3): + raise OSError("The owned inference process group has not stopped safely.") + try: + process.wait(timeout=3) + except subprocess.TimeoutExpired as error: + raise OSError("The owned inference worker exit has not been confirmed.") from error + self._clear() + + def _clear(self): + if self.process is not None and self.process.stdin: + self.process.stdin.close() + self.process = None + self.identity = None + if self.response is not None: + os.close(self.response) + self.response = None + if self.log: + self.log.close() + self.log = None + self.loaded = False + self.telemetry = None + self.cache_state = None diff --git a/packages/codex/mlx-agent/src/mlx_agent/resident_worker.py b/packages/codex/mlx-agent/src/mlx_agent/resident_worker.py new file mode 100644 index 0000000..09b9f2a --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resident_worker.py @@ -0,0 +1,104 @@ +"""Private, serial runner protocol inside the selected backend environment.""" +import argparse +from contextlib import redirect_stderr, redirect_stdout +import importlib +import io +import json +import os +from pathlib import Path +import sys +import signal +import threading + +if __package__ in (None, ""): + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from mlx_agent import runner_model_cache, worker_telemetry +from mlx_agent.allocator_cache import AllocatorCache, CacheUnavailable + +RUNNERS = frozenset(("decide_runner", "music_runner", "transcribe_runner", "speak_runner", + "generate_runner", "describe_runner", "video_runner", "mesh_runner", "embed_runner")) +MAX_MESSAGE = 16 * 1024 * 1024 + + +class BoundedText(io.StringIO): + def write(self, text): + if self.tell() + len(text) > MAX_MESSAGE // 4: + raise ValueError("Runner output exceeded its limit.") + return super().write(text) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--response-fd", type=int, required=True) + parser.add_argument("--model", required=True) + parser.add_argument("--port", type=int, default=0) + args = parser.parse_args() + parent = os.getppid() + + def watch_parent(): + while os.getppid() == parent: + threading.Event().wait(.5) + os.killpg(os.getpgrp(), signal.SIGKILL) + + threading.Thread(target=watch_parent, daemon=True).start() + runner_model_cache._enabled = True + cache = AllocatorCache() + runner_model_cache._allocator_cache = cache + with os.fdopen(args.response_fd, "wb", buffering=0) as response: + response.write(json.dumps({"ready": os.getpid()}).encode() + b"\n") + while True: + raw = sys.stdin.buffer.readline(MAX_MESSAGE + 1) + if not raw: + return 0 + if len(raw) > MAX_MESSAGE or not raw.endswith(b"\n"): + return 2 + output, errors = BoundedText(), BoundedText() + code = 1 + try: + request = json.loads(raw) + if request.get('control') == 'cache': + if set(request) != {'control', 'policy', 'reclaim'} or request['reclaim'] not in (None, 'manual', 'pressure', 'policy'): + raise ValueError('Invalid allocator cache control.') + if not runner_model_cache.loaded(): + raise ValueError('Cache controls require a loaded worker.') + cache.configure(request['policy']) + cache.apply_limit(enforce=request['reclaim'] is None) + if request['reclaim']: + cache.reclaim(request['reclaim']) + code = 0 + else: + if (not {'runner', 'arguments'} <= set(request) + or set(request) - {'runner', 'arguments', 'cache_policy', 'memory_limit_bytes'} + or request['runner'] not in RUNNERS): + raise ValueError("Unknown inference runner.") + limit = request.get('memory_limit_bytes') + if limit is not None: + if type(limit) is not int or not 0 < limit <= 2**60: + raise ValueError('Invalid worker memory limit.') + core = importlib.import_module('mlx.core') + core.set_memory_limit(limit) + cache.configure(request.get('cache_policy', {})) + with redirect_stdout(output), redirect_stderr(errors): + module = importlib.import_module("mlx_agent." + request["runner"]) + code = module.main(request["arguments"]) + if code == 0: + try: + idle = cache.desired['cache_reclaim'] == 'idle' + cache.apply_limit(enforce=not idle) + if idle: + cache.reclaim('idle') + except CacheUnavailable: + pass # Preserve the successful result and expose maintenance failure. + except (Exception, SystemExit) as error: + errors.write(str(error)[-2000:]) + message = json.dumps({"returncode": code, "stdout": output.getvalue(), "stderr": errors.getvalue(), + "loaded": runner_model_cache.loaded(), + "memory": worker_telemetry.capture(runner_model_cache.statistics()), "cache": cache.snapshot()}, allow_nan=False).encode() + b"\n" + if len(message) > MAX_MESSAGE: + return 2 + response.write(message) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step-build.lock b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step-build.lock new file mode 100644 index 0000000..f652e21 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step-build.lock @@ -0,0 +1,18 @@ +hatchling==1.33.0 \ + --hash=sha256:415290b84f464d2884303fca8974d38e7b85579069fab02a15db0828fbb1446d \ + --hash=sha256:4c422bd4d554fcff5de5b73e9596f85e41e9f97f7e553d8f7595ecb31a627bef +packaging==26.3 \ + --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ + --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c +pathspec==1.1.1 \ + --hash=sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a \ + --hash=sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189 +pluggy==1.7.0 \ + --hash=sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec \ + --hash=sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8 +tomlkit==0.15.2 \ + --hash=sha256:05562412163a3037b94497385fb7f9204c637bc605af7a48199e41cf2272f437 \ + --hash=sha256:83e32755ba1d20d9340bd069ee97e9f6232ba2346b63ffcba425de01f7e327a6 +trove-classifiers==2026.9.21.13 \ + --hash=sha256:0a9ebc8d4e2f3e8a22848c5258033035bec17a3012ac3fea16dbaa764489eb71 \ + --hash=sha256:8b1ff4f9c191b1040b71c37f1e445ab99732911e3cd91de52838453a854d7a17 diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step.json b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step.json new file mode 100644 index 0000000..9c3da8a --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step.json @@ -0,0 +1,19 @@ +{ + "schema": "backend/1", + "id": "ace-step", + "version": "1.5.0", + "builtin": false, + "package": "acestep", + "convert": "acestep.models.mlx.dit_convert", + "lock": "ace-step.lock", + "categories": { + "music_generation": "models" + }, + "remap_files": {}, + "registry": { + "music_generation": { + "model_types": ["acestep"], + "remapping": {} + } + } +} diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step.lock b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step.lock new file mode 100644 index 0000000..306be79 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/ace-step.lock @@ -0,0 +1,2608 @@ +ace-step @ https://github.com/ace-step/ACE-Step-1.5/archive/ca1e85fe9430179831e6bc6be790c332190a3866.tar.gz \ + --hash=sha256:b464c11f00af00e1e089a09f58a03962f803c080f116fd0517dbe5ec839706b3 +accelerate==1.15.0 \ + --hash=sha256:5654f8c5eaa0d4fa68b33e287a97765da6849bf6d51dcac874e73fbbddfb6134 \ + --hash=sha256:97eacca0b73e45cb867dbf8c5d5d4dc32219544300e0c8992c7334dc2ef33cec +aiohappyeyeballs==2.7.1 \ + --hash=sha256:065665c041c42a5938ed220bdcd7230f22527fbec085e1853d2402c8a3615d9d \ + --hash=sha256:9243213661e29250eb41368e5daa826fc017156c3b8a11440826b2e3ed376472 +aiohttp==3.14.5 \ + --hash=sha256:0133c3c3b54a0bf1e71fa5c1ad95c93f07fd54e24ef1fe182f5122e1573d2bf1 \ + --hash=sha256:038c2c7e8caa26b6c8423779b5eaf1893904048a512c19b32fe841ffa5592b50 \ + --hash=sha256:0684952aeae1f5dbfe02d46039338513b94009baecd15d8e4098a357c4c4a2a6 \ + --hash=sha256:0790ec66fa4013e83c53b9025a45d454723da1a2fce28b3208c9b32d08af162f \ + --hash=sha256:083673c7a94c3ea035caaa5ca04288bdb44887abfe1f5ba23294e6a4b03efd2d \ + --hash=sha256:09e0eb18c7e0c8777e2f9149de63799195b9b3ca1b5c81ba6f32f2c6b8628210 \ + --hash=sha256:09ec102b4b8c9a920275733bbc11fdbb615efe6f9231a06007c0218d336fb77a \ + --hash=sha256:0a8ea271867e360ac985ae607f4a23ad9a38414b9aca1d49ec98839ae660e49f \ + --hash=sha256:0e6f16f5e49c4b8267988c05ab07760d7064cea57d077c3d068d04b0fbb992cb \ + --hash=sha256:1061b364556e8172e8d46b0b183adeeb73e8c42d30ebc745591e1bd89acad52e \ + --hash=sha256:1220353657ad49493551f089ce02f1a348fd57ffd585bfec77f2f3c4fe3a7346 \ + --hash=sha256:137351bf20bbed9a65e839f4a4452ac377389bdb2f2857d2acffef38f5e9f2d1 \ + --hash=sha256:149fb56caf7acb67073126f675d0958d9c4b3125fcd3f6d4877df98aa8a97ce9 \ + --hash=sha256:14f04769cfefe4734016a856a83af36133cd17779cef9ae817f812b8ba9d6d51 \ + --hash=sha256:15a310d3c71398e3d7bfc93a1a73fbe664315cd9e9016b8efc1cff85eeab7155 \ + --hash=sha256:1612fa5857b37bf32e5c1eaeefb96e3b01e9c70679eec81f0934e8a600080863 \ + --hash=sha256:16c8abd5bca220a47efe667d26f8460124c81810787e79ee87b242677563d9dd \ + --hash=sha256:19e2ba471507c34f8252402ab50f5ab512398b9ea8c8f1cb26beb3f75793ba30 \ + --hash=sha256:1aead151c3abbac6b32942e452020cb66d7efc099d253cc6c20f748e926c858b \ + --hash=sha256:1b438b73c38111818d0c9d6a5c2bfed8584c8e503a49ef085d70e874ec846738 \ + --hash=sha256:1b5416552740edf07234cc9437d0706f2acb67b93c198670b1a68e1b2b587dec \ + --hash=sha256:1d2d981b53dd09a319e3570ef8cc3bbc3ef86f5a7abef0f6b2bff3867db3a9e7 \ + --hash=sha256:1eb8167961ec4dfcc8cb9dd50bd0ee72519f7ef496be95203e49e27b01618382 \ + --hash=sha256:1ffa3a523a36d8628f98c06492ae16a31a23d14c0b4ec721757b477319f656d6 \ + --hash=sha256:20064a177a070d789ee64a50b01a9161d3468e989baacfc6c714aa685c4b332f \ + --hash=sha256:20726f9782d5c2744c1c66255842d1d163bb3edcf768b8de25216bf47f7b6ccf \ + --hash=sha256:20f085697d7e911f1f73c43ed03fafbed1e7121797e2eb5428efa80398060584 \ + --hash=sha256:225c579c23b68b343cccea27a7e06e3bd8ec23a09c30b427eb3f1e4ca6239b20 \ + --hash=sha256:24409db442e2fb6e766bc7f3943851a8381dec3098140e43bb2e843b79e31b12 \ + --hash=sha256:248d779ad720b49d4fb355720e60c9e5f444f95887bc16974fea48fc56c41789 \ + --hash=sha256:2528cb4c6b92008c76ac9ac6298624069bb2db91ff4929905512d1d84485f658 \ + --hash=sha256:276a4fc00b1d9ae492b802763a789c5b86328b989c5ea169f2faa447d6a11c7c \ + --hash=sha256:27c2322e03f66101acb09869ce1cf1efc04994ee95e1735b69827bf8c8b9d781 \ + --hash=sha256:293d3ae7c6a0ed176a42e59a1b5fde825ead65c835360f734148e96729f928d2 \ + --hash=sha256:2cc38a4f2b516bef1714e690df87a0e043faf1a7693c82d860091684453d5111 \ + --hash=sha256:3093b72c215bda16ce961a6d073f6e71d46e022962a9d5d457c5d4d421c78b57 \ + --hash=sha256:32e8fa6644e541fcd7e02430588c7fc93b602c1778ea0bc345505db76b61cfb4 \ + --hash=sha256:330900acd0dc4cb8b27f9c127fbaad770964845338493e7906ae3822e82dbf8d \ + --hash=sha256:33f706574e32c6e694f352a856e05caf18f7f2c871b3e87b41c55ea452b409ab \ + --hash=sha256:3ae800a20947e2c2e53088047d021e6bf7d51560cc49f6a0737a1f79d2e3a13c \ + --hash=sha256:3be7dd397d64ca3e1869626fa9318aaebb54b7bf93bc72d7a205448d83e4f748 \ + --hash=sha256:3e0eb43bed3c6801a6cee315195377789e90b2a72c2277a475b578535312488d \ + --hash=sha256:3e51a27980c3788e6e6b3325d694fdd4898087fa8a86b2763af77b39353da41e \ + --hash=sha256:3edbece0379b8b4aaa67619b8aa2399bb66fce372cd5911098a434ea77220aa0 \ + --hash=sha256:3f2dcc00191fd563e9075181a14ec31d7dd63223ced7582cc70a15a499de0c79 \ + --hash=sha256:42b5e616946dbaf505e2bff18c9af2cd4ef9e7ef300ee58a6e951a5b7cf147ae \ + --hash=sha256:42f320d4a5b00b9af0bddcfec5407dc6f2d9816f006b2f79ebbaa31f16895df3 \ + --hash=sha256:43351bdb5e4c3cb7d1772368e988534e869a74db7778079a83782c11c69535c7 \ + --hash=sha256:43e1b7994a8b038125f722bff07492ef501110722c2727c408995d9fb864c421 \ + --hash=sha256:4887d130a7bbfed3a85493bb5a25e5b5b558d40c1d986dd16970d2bb26d63793 \ + --hash=sha256:4f07fe3ac408d8b3f768be471dc3f56d43843c47d97c66120534467a15ead197 \ + --hash=sha256:50343c1757b4b6f6708eeaf24534b32f19dfb99fb1b762c00420867a62fc81e0 \ + --hash=sha256:50983e3be33d8c0942ab88cec3905b10602f64c469b20153c48c5d4e558dd016 \ + --hash=sha256:50a195903119008fe9cc68710535eb37f556ffffd6a7759afe70a2c145587045 \ + --hash=sha256:5558a7f5a05af9ecf744af91e5baefc436f93c9333e656c27ec253f9a6bbe178 \ + --hash=sha256:56572c42e3ecd636de8d2c3dd54cf5fc939cb5c32eb56297f176a0d366fac622 \ + --hash=sha256:56d9828f204331a5ca8850fcfe2bcce95a149f1f223f60cc7216e5524978e480 \ + --hash=sha256:579f97d5120f2971876d2ddca2968135f6944d00c44c3a6590ad7d86ca9b403f \ + --hash=sha256:5af42135fdfebdadbc2bcd9c0842a48ccf0d62794c36a260b21dc4b94d1e0119 \ + --hash=sha256:5ba14a839fbe87cf7c12a6b5661c05f324a296eb8363141edb3944ba63d4c9d3 \ + --hash=sha256:5c76f1802bab718a68ac3cce447160605c734551f95c67ae90fa1132b215cb29 \ + --hash=sha256:5e8f97c0488ffda3082766ac0f2c8150a9a58c4d05788330e479cfd449b37939 \ + --hash=sha256:5f3e96071686755d9cd3600c3880183eb94b012178e92746d68101800f0ed8a3 \ + --hash=sha256:5fb6a6e919bfb703227bc1ce6579281b84b1a2ba57deb9794dfdbec7dcd1e40c \ + --hash=sha256:602c1e9b718a3275c580149f947e7fac65044c0a20e599553fb12e9700da9eca \ + --hash=sha256:657291433bf4dd3142f3abac495764cd47d0c7c92087751e6666c6447e65fcef \ + --hash=sha256:6774814fd5c338e72ee0da5cbb9432816df450e69c019f72b5d29bdec2a1792d \ + --hash=sha256:6da32b5ff3fd78d244e37300463434c7145162bfd2b6e9e915ab164da37f7343 \ + --hash=sha256:6e1d8637cf73eebc92eba2e11d4cfff98a3b562f2505bd75bba766d908926e8d \ + --hash=sha256:6e4251c0ba4624a68a2c11471a1ac54c3306876c21f0ae86de085cc9241c8905 \ + --hash=sha256:6f275c11d1aa6d4c458e05a68be084efe3c55a113d99e3f46a318098e52948fc \ + --hash=sha256:6f967dde489ca6a8c02d093ab245d2cbf50ccb5c36adf0188b17b0ca39d24b67 \ + --hash=sha256:6fdcd6af7e2e51d1ba1b4bea16e97b074bcb7b5dd0246a9d8201341bb28085a0 \ + --hash=sha256:70cb4008ac2ed1e0ca9e824deb4b53d3aa0d939109698ebf1e723a84337bd794 \ + --hash=sha256:7457580535e019e1247ea35d6a02bf081ad30c26d0cbc210c93f6c3ab67a0835 \ + --hash=sha256:74b0a9c8270f9b0a11410e124ff8d4f18bfc1f1837440ec84da5ae7b50927b5d \ + --hash=sha256:74efb69332b85675b1eabd760a8cfc2e2cf42c60607c66f88014c1bdfb40942d \ + --hash=sha256:755933b107ea7a6a9ac916f635a70595a5b1a32fac10a8ff0b9f2ab88555550c \ + --hash=sha256:7779cd97e61ebe583ec2f1c5616cdd038aa08a4453b1848c67842176d054948e \ + --hash=sha256:788ecaa9c10533b786ce5ba70c4f2df78ad41819fd00a6c99d92b66f9a32e1da \ + --hash=sha256:7bd8ac754ebd6733a3e2a0dd1674c4d8ab086196803fd8dcd776f07b4e2607d9 \ + --hash=sha256:81c2b3dfd56c62bee6108e4852d5970b4cf9086390b6983f52b666e878c1f115 \ + --hash=sha256:823c910f046f23f4c713b8d99a2242dc65f591cb45ee86418fa11762a3c2963c \ + --hash=sha256:82c7583cd3dfdc7dcc927835b4f6c7faae7ecc1ba3ca5879321621ae2e6f8e84 \ + --hash=sha256:8966ecac808dd5f473c9c4cefd10cd3ffda71c18a4d3493b7c7d2ae1803bf2cc \ + --hash=sha256:8df7d481654ac96fe1ba9a02a9f67770fdd367823e0d5ef01b922725c4bd2cfa \ + --hash=sha256:8e317e0fb6b16212c881d2205a7d87414c29acd69320b3aa6dce9d9c7b86fe4f \ + --hash=sha256:932ce7e694bbc29b2bf6f64f2343c27d148d4997c771d01bdade4639b6749ff4 \ + --hash=sha256:939042d5cda21d41a6f512e7cc8b8e33a2aebff863352251da495fbd91b673b5 \ + --hash=sha256:94684b879ac1d71e4238850c99b62dc1b28d9086b156a2555f082010b85a865c \ + --hash=sha256:96a2e584f0b9ed8f1fa33211397dcf67bb7069866402cb405d191c2f0defb9a3 \ + --hash=sha256:9ad7e6aa38c20da1be697874349c4c273c8a03b7887169665081706398d0439a \ + --hash=sha256:9b42db919715e91eb76acf3bc492a9a7ccd8bd9adc6745c1412b689735269f14 \ + --hash=sha256:9bab2045550c4fe0f7baf89574db1b455c195750702ba96fef1f16972b146617 \ + --hash=sha256:9bf1d5dcc15204d9ec8b8ea4c18fd66e6b80e5de1f4ecbafb3a2f2740f8039d4 \ + --hash=sha256:9c061aa954daaf57d2a4b8374f9fca621ef0e1b603584431c220c22458c59b6d \ + --hash=sha256:9c428eb2bd8817588d16a0ab898aa4eb5d141f896aa2b394cc79a4cf61d9a8e2 \ + --hash=sha256:9cc882cf8619109583c906b4d4a85d6a111a98afa34b7a450d1e08118d016820 \ + --hash=sha256:9ce66feae6ac65327379460380549bf1b8df8e17c4e25df2a2bcf168272e3bed \ + --hash=sha256:a23fe35d776bc03cb495938b9594450d047e3bc08c5255315a82323e9cb7d2dd \ + --hash=sha256:a2c473a355f9239efcb72c92d5abfd8fcdb0cc78c8e9af607e72ca12dbb36593 \ + --hash=sha256:a63afd1f757de949028387e65a7127b61ad0f775432dbb0e62816ae619fe69ac \ + --hash=sha256:a6d02b4c38de03d9c7617813433e6a0fb6b522797974177d69d9dad431900833 \ + --hash=sha256:a7d470cf7b206e6359fc77b1b860632fde400d5a2ed59cd0181b93a686bc81ee \ + --hash=sha256:a95529a92a446db351675f4aab518feaf5e99842f63f5dd17160c2b74f382db3 \ + --hash=sha256:a9918e58faf62ba2c7147927d06057aec78f42475aff5048047ec47e7265a600 \ + --hash=sha256:a9d3983bd6ab7aa1cfd573544ae98df9b6cb6912a5185a198263e024a636861d \ + --hash=sha256:ab52d8f1fc1b64821c1fbad64a647ed6203627004059a6d1ed4f0858a1499703 \ + --hash=sha256:abfda5cb094a829f7bc25216a32f7db2e85cc65bd59910f8e7b40b3d9b224764 \ + --hash=sha256:adbeee7d6fd4cf5fe0aece2fb3edc4243615d3180430ba8149d01a90670cac99 \ + --hash=sha256:ae53924aa853a7a2ca20ed4142c7c6b56338e4d4cd999e2980075b9efc2e257a \ + --hash=sha256:b032a0023eb41d768ce77d83210ab2a3c389bc0b09313273c7e1eca48c10a755 \ + --hash=sha256:b1b8ece1e71132d2afba4dbc0c3d62c766e25165990b25db1196c04969eb3d84 \ + --hash=sha256:b2966998927d7bed9db12c0a4647b0c7b179755878fc9c357fe1ffd3e3b0c1a5 \ + --hash=sha256:b3cc509327c7b27f6f4727a8830f4004f6df7766e179f2f4b8e54e65c0bec5d3 \ + --hash=sha256:b7806e804889231b0e06469fd4a5c06313d1c0a3377322b6d9237fa5e0fe4167 \ + --hash=sha256:bea559ad70218d230663e4210875735076a9bfea5994cef34a55a25faeaf2544 \ + --hash=sha256:bf163cc701f3d4ac43ba7d97771bf5fd955220ef5500ef3ee847bc0ecfbf4ec1 \ + --hash=sha256:c147451b4a58e7050f7f7394e6c467867c84161560001f9ad4fb2d1446743946 \ + --hash=sha256:c172db893e516e1358e65a95ee20b7ce7173963eefe318b6ab2a2220688b999e \ + --hash=sha256:c1d60eafd9c7e8e74abd03a5b00df44e7febfe6d9b89b559c0a6551eef0699d4 \ + --hash=sha256:c2c30484dd1417ef98b51021ffa2cc0d7f3c78918adaaaab7e70817335ab3e02 \ + --hash=sha256:c32e26310cc10e547f53cd13d39a369034f69dcb7d749d5cb0e5f67bc196b6ba \ + --hash=sha256:c5ed596aedb9c42afd3fe0aae3117725378ac73d2cc5ddc735056fbdb96c5d02 \ + --hash=sha256:c8859a013ae0de1074660992139a1a440df3e6b219b86cf0d3f11c2692bb4fe3 \ + --hash=sha256:c8c4478bef6d57fcfda15dae461ea3c9f06aa7b257c58df3f2300174ccbb185a \ + --hash=sha256:cb11a971a3aea10f9b8373be628f1df932964fc6c6b174516d318a48c3ac4412 \ + --hash=sha256:cb131d775a1573c1aee66656bd78b023577bbdb6cb8349a07773bd4f73e68a6e \ + --hash=sha256:cd88b01f3d37b7a2a34f91d98f14720206f1ea3d540843fab2d649dd5fb91fec \ + --hash=sha256:d05e94cdfe0d15d0206f970722d2554780ce562787b21b218b275447f8751319 \ + --hash=sha256:d079c0a0135c36e7beb6f1c88087c8f108dc5891cdd0b5eafa778421bda70ed2 \ + --hash=sha256:d3112585250b199296c26ca6e0131640b6a8d01bab8b232d2eb3763ed469de11 \ + --hash=sha256:d418ce2af40c6bb685b3f663e9e8de27cb0a22431d8e88a167348d7f01878073 \ + --hash=sha256:d51db97c96384fbfcaf8f4c65922183a68b94f891c3c10c862ef5f6df2adbb1f \ + --hash=sha256:d94e44be379e569758fee8a9a58431cfc3c2598c708b92b1cfe96c66b4c94aef \ + --hash=sha256:dab9ac5a67c8d1f070c00fa8fccb7cbd1b8dcc1a8d6b42f37540df9b3d4cc603 \ + --hash=sha256:dbf53ae2601b7fd5a93c3944deea3a78d40f495226d582c35ef7a433425ce2b2 \ + --hash=sha256:dca3fa8d8a0a26679862eccb0b1a9151b2b9f1cd2c212e7a6335778faaff5833 \ + --hash=sha256:df37b620684e19b5e25724412518ccafc3b1a49cdac706fdbd2f983fad943450 \ + --hash=sha256:e1cc2bfaee8c214f06080a7c7d5772419b8a1108e8e5349236189811823fb02a \ + --hash=sha256:e29347c142cf6e99e0dff5e2995ead1d50fa3b51bf37a7c726a7ccfe5419745a \ + --hash=sha256:e4f5cf4dc72a71c4cfa9751b4950be22f733626670230d46e7d606592aa22d59 \ + --hash=sha256:e724a7b6091f0b1ac064f9d1b15ff9ec52e6033a86cdae649e5f086e32a3c0db \ + --hash=sha256:e87046c8ff77a8decdb6a41d8ab25824b47531b2da933aeab0c1e21c7acff329 \ + --hash=sha256:e95c8def4b81c5d68d5cf1f54c07acd7c0d2577af244e5b6da802120825737c6 \ + --hash=sha256:eb324e2009fb54db30a071dad7caf6998ee2879c4704007efb244514dad1fec1 \ + --hash=sha256:ef60869969180ec2464f1349aff07138ae35ca2200f0946cb3552e49e8f301a8 \ + --hash=sha256:ef692a24087a699c0a4a26af45e746e0c1eae2116f6d8a5ff91d8aae2b867b45 \ + --hash=sha256:efc21a454892828368b11c2c780de0ff8bc991f73f6b99c6b66e56205470929b \ + --hash=sha256:f001b571ead90ca1770f1e616db255351a1703317f20374c361ef22f12c06d09 \ + --hash=sha256:f2a7966bda23dd85051f1661ce0ace38d6890e05ec6c357ecae9d2479cba377e \ + --hash=sha256:f2ebb54b3f932210503072f09974b4fb574d823e497a944adfdcd140a6a00255 \ + --hash=sha256:f2ed8b64dc0c651c0f5a9c926777719770021251b8f336d97c4b80b660836ce1 \ + --hash=sha256:f375db73a39f5cf83696d500e21a67f418dc9a988955756f254be8f03b7b3651 \ + --hash=sha256:f59c7673465908cbe506117176156c127f29f917677afceada34957179221d91 \ + --hash=sha256:f8d40ce41991e9d56fab4f5dc4a51fe59bc3b5c77c27f4b148963064d00232e8 \ + --hash=sha256:f9033b43f511f27547c557dcaba0177649e10a3725336ccd2cce0fdc1dc4850d \ + --hash=sha256:fba47bc2c3d7303c3d027c6cf4d07626c37b1314ac81f5820c31032e0ca1f677 \ + --hash=sha256:fbdc5ec49f9ca3cd24955cf3520b10a4d4c901ba2572094c84274e9e7eb30534 \ + --hash=sha256:fce9523df31cea6284f3e2c479876750d7687cf671d7b25d32b19effc0e86441 \ + --hash=sha256:ff75a7537413a86e7cafe98e0e1d6e3dc4b15c6349896e7d5c6b881bfdb6d550 +aiosignal==1.4.0 \ + --hash=sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e \ + --hash=sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7 +annotated-doc==0.0.6 \ + --hash=sha256:361ca0950cc7082f53fa69e9328409f40a62c61e57e0a47e1825a08078a58a53 \ + --hash=sha256:7969bb69912085b2285849c0dcac0b4b374fd180c13cf10a87f284ffcf347bbf +annotated-types==0.8.0 \ + --hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \ + --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0 +anyio==4.14.2 \ + --hash=sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494 \ + --hash=sha256:cfa139f3ed1a23ee8f88a145ddb5ac7605b8bbfd8592baacd7ce3d8bb4313c7f +attrs==25.4.0 \ + --hash=sha256:16d5969b87f0859ef33a48b35d55ac1be6e42ae49d5e853b597db70c35c57e11 \ + --hash=sha256:adcf7e2a1fb3b36ac48d97835bb6d8ade15b8dcce26aba8bf1d14847b57a3373 +brotli==1.2.1 \ + --hash=sha256:0023348c448140a6ea71615eba331835c971d38ae8acf8a89b4e963b1f38f131 \ + --hash=sha256:00a50d063aae2e69c2eb28818ccf6dc3e51f2ea5b74e3c2082a47943ee23f399 \ + --hash=sha256:00c9a4262dd81cdc32968f8bc2482c735ad238010d95b49698f1b788c359c7a4 \ + --hash=sha256:02b2f7b5a83485efe448a44ddf7983def05c3bb1dcf917d4f7154070260e13de \ + --hash=sha256:035f3bf861328d8b7fcb61f4a976f9913027158e5666116733d59ffc65f2745e \ + --hash=sha256:06a22fcbcae059c0679098232779095fc50a735a3fea02db5c79cab10b84d877 \ + --hash=sha256:09a2f112a638aca15a88f298571788795fc45d62f2bca7f3870c1152153ef399 \ + --hash=sha256:09b560859a04d112d206639c7e444161ee2f413098aa6de11d43daf3ce883d24 \ + --hash=sha256:0a30e5df5ba985b67f85e13dfd7e5a68e186d8d9b5cff7d9a8904832bb413e81 \ + --hash=sha256:0c5c6144aa4b4585e4e0b3595f9fb2743a2e32650bce4b2669a0e809b3e7bbbd \ + --hash=sha256:103b4762941760ae245d8d0d50e3ee4a7e034fcd786f122d177f76d6afc90c63 \ + --hash=sha256:104d3504678db9172de523bdd8e6ab8d3643067fbde18e5b89476f405b64cf25 \ + --hash=sha256:11aec6ea5c20cad61a33302e06baa48b0243bfa4d173bc2985dabd047e367d08 \ + --hash=sha256:1329c80daa60752f1d94f507479504921e358e71746c5fce9b55b3d51ac038bc \ + --hash=sha256:1624ca7006d2776cc8f0313e62d63aef9d3720b66f0d24e4439f5d754488e001 \ + --hash=sha256:1880db6241276e191d3e34a6e4eea708c6629103c396f0ea21e75b0ce63a9a2c \ + --hash=sha256:1f5d8c6e68555b82692f8180ee646cd1752aa9ab98daf68769a7c56a6e8d7af7 \ + --hash=sha256:1f65a91f3576949793b8720b12a47e7ea06debc970a2da6d54ff8458053e2109 \ + --hash=sha256:228abf241b39925450ea5046cbd8bc88ae1b91cd229037b0e194409df4ef2f4a \ + --hash=sha256:23f0d23995100458d17f3bf5ce1e959fe46df894b472063a74266f7adeb2e72e \ + --hash=sha256:24a3f765167e6ecac3d85a9fe3da857a068097cf44abc08bd67c5681d8251bca \ + --hash=sha256:25d7c19ea92df4be1358126b6712209ac58229d17af915397d1510f9efe0411d \ + --hash=sha256:264fd5b200f6f6170cb551a4b9fcaabf8aa846ddaefe72db4d5f49f9d3743df9 \ + --hash=sha256:2df1678c2c25db2f669c613fe8b4e587d0dd24c6acf7746bad13d6e87e4b051d \ + --hash=sha256:304ee5bf4f85b719f6a274fa0b50d86b39b5dd1219f4cc61410d4eae315757a9 \ + --hash=sha256:32567555e2e0040c596beb7f5f2ef69da6bf224aee4617c2a52099248dd3e243 \ + --hash=sha256:338856ae9ff63af4fc3dbbd6184a7276a6ae83df2243562e86e5ee5cf980cce7 \ + --hash=sha256:37de1818ce469b3c37324c89d4d4dbb5e64461d9dc01c16f8abb2a17c465b132 \ + --hash=sha256:390f5e174ac2296dafd047d0785591e61194ff3df11ad43abd2fddb0e750eff5 \ + --hash=sha256:3975fb11f63e212b87a087e4a910187b522c6969a4989ca362d6f85f9dc36acd \ + --hash=sha256:3b7df499157279a4d5d83ab86bd328c58c9ccfc48f5de45d4e791d3234a54dff \ + --hash=sha256:4092027deb7313156d2b601fb0e3637cbdf9d598f5bd57dc57348432967ecd31 \ + --hash=sha256:457f011c135263900805b4bf0dd290724d277785656c32e4f5fefe4a1feede1e \ + --hash=sha256:4583e4d11d40fa4a05b7d81cd822008d65bce755dd78c49945b5a98272953759 \ + --hash=sha256:461daaef60db39e407a6a6954a2b4804170db56c6212c009a6cdadbdd12d7a9b \ + --hash=sha256:4839f1a1ec3a95671238b2a165eba7a0a823090913ab4fc48aa03dc6f666dd02 \ + --hash=sha256:49de36a626557629db1f9b1eb57e7d88f3815a42373ff7f9d8b87c1da120687e \ + --hash=sha256:4acd709bfe362c2ed80da311d195654467110bc747de1484c731304810fd20e5 \ + --hash=sha256:4b9dd0173ca5e01d1eb307d3c184fe8c09bdc168ede560889b1018d216d38c61 \ + --hash=sha256:4d47a9f0ba5ee608f3f3a9c942dcd244443068ae5b0d90183dd396dea02236e4 \ + --hash=sha256:4e89a05511f8538911d98566f6ddd0883f28a5ab35fefbd70c036ab630feae1b \ + --hash=sha256:4f94a73b5f30b8bb36ac684f2b6a6e9bdc58a9b4bfe1658592727369443bce93 \ + --hash=sha256:50248e2f05c8335089b9c2a80ebb4a8b5833a3581a433438b523e2341f45e681 \ + --hash=sha256:509ee1058937d80d88b33aa893ca46e1925779d928181916bd60bda3a8738687 \ + --hash=sha256:59ca34c7a83d7a3b842247183c426f891a95a8f57db41b7aac92195c51e8a83a \ + --hash=sha256:59ec359a56f44277ad424fb4b7cf1a0ae2fd855b35ba8f15dcfbcabb3fb51aeb \ + --hash=sha256:5c77d41984e388c9f393da124394af941ef757fb33bb6f1eb72e8167fc557489 \ + --hash=sha256:5da5cb778a7fc889f72bd2238ddf39b9f7e8b0979ccefd760380f1c24bd9f33b \ + --hash=sha256:5f3da70516b1bd1b2aa183ec4ab5c02dfc6ad5c1184d47bb65ade25e710439b6 \ + --hash=sha256:624240d21823e1805425c155fe8b35b4124e0a837eb8ea271bd0a54caeac4ef6 \ + --hash=sha256:6532d2c58018121a9eb5882656cf862cdbbd853600cb5fbccac59bcff14f66b0 \ + --hash=sha256:66f171af80744c06f6b4e5b01fe6e40c70cc4e17570888746a281422fed83fc0 \ + --hash=sha256:67f4dceb22ce3a742751cee849644449b169684699aa548e77d771de304e963c \ + --hash=sha256:6b3c3d5794212a54434b4856f808f7bdf7ad48eacadaadb5b2346fc9a639365a \ + --hash=sha256:6b885b6b1a3b01c5980dddeb2d9dccbc5a5dc0f255ea15904bf585b73ef375a1 \ + --hash=sha256:6bd29ab84bb8972370cacd310e8a91651f54476d01de1cd1a4cf0bece5eb25e1 \ + --hash=sha256:6beca755e6b691096a398df587f544c3f8ff6e9e3a8119d90eae37872a829382 \ + --hash=sha256:6f83664d0e48fd22114dd5ca2cd5202743a7b75b5e6e3fbc6ed61489cee749c8 \ + --hash=sha256:7248c282d7d6aef4ae89363da5fc3df7b9250eb04b252622955296eb5d0ea82f \ + --hash=sha256:727c922e0e8511e22a7f3c81fbcce0aeebc8c7cdb7bd8f13f505394ea9865dcf \ + --hash=sha256:761db18dc32b24d00fbedca1013089eb3470053cefa8492bd9c07b11102d72bf \ + --hash=sha256:76b11b4af067c2b55ffde313ae978d8ab51cfa65046bb70de23448c9dc4e18c4 \ + --hash=sha256:77ef5882c5318ffc3dd94c6abc6a8f1ec2af75d66522319f1a250a07d53d0546 \ + --hash=sha256:77fe6845833339ff6c54be391b56dc5fcff9e7a9acdf7df54647d27e5d3afdd2 \ + --hash=sha256:78c9b5c2cceaeb158d56d03ba9336b3d310c64da6d304296ba39b6c00b8840c1 \ + --hash=sha256:7a553fffd70a518916ce5b595b3067a55c0357732b4f0a96db2dce70a4db717b \ + --hash=sha256:7aa24d49840c016a8256adb1f104f4e064ed9fa7d97523675dd50e08c05b143d \ + --hash=sha256:7c0f9fcfa54570222eb4cbece2fc44b71de3710e0ea6e075bc0ffdc8965ca1ac \ + --hash=sha256:7ec678c52c3ef5e37482a094d109c04cf9e4a0e2923dd1e0fbddb4bf133a976e \ + --hash=sha256:7f38649a7711c301ee231e296e0c8f14376a9d4f9ea7369ecc3cb22187813d9e \ + --hash=sha256:810aea5958d6a2d92593fd27218df528644aeb72cc7f6d401e650752d6c98949 \ + --hash=sha256:81f289389af277345b85aea4b36f4ed2bbdf7504d4466cbec7d28702c4926b01 \ + --hash=sha256:87492842770cd772fce25e9cd279913eaea6c55a91a960b6302aedfa2ec7b152 \ + --hash=sha256:875975f91870682cca4371260522ad3f22d636e845b5c5355c52bc045c0f75c8 \ + --hash=sha256:90bd49511341dd7c40bb3acaa97cd8b9e5df4821a5714b842117e7069c7cc03e \ + --hash=sha256:91097d66ebb8ca8d23372081a33405a44e2239445614888e38929bd7f5879dae \ + --hash=sha256:9307679936e86d7773eadfa444a4a4ee80f6f45230e93379875f4a6897a09a2b \ + --hash=sha256:93269f11303fc9a3e3990b57e0533f41949546156d9f0e535571f313032563cc \ + --hash=sha256:96e6966edcfae74ffac2522d2dd1a304450d18807a9791f5ed0a3232192c9437 \ + --hash=sha256:970a3dbce807a3f5c2b8232036052bade01e4bc92ade37d73ea3750418307fa1 \ + --hash=sha256:972a2e19dbaab47d0aa77c1d07f71c930bdc53538f2b33decc905e92a4be5cbd \ + --hash=sha256:972e34c5cbbfe6c90358bfae38edae1a29d3456e920da5a4664c98f221ee4df8 \ + --hash=sha256:9acd83184eed969a08c1afa404a202a3f4287e3580781f2a36e927d4f25363fd \ + --hash=sha256:9f9aba3f8d2e3c22cf233d9bf2c2cfc050989d9da627802845df317d7ab33e84 \ + --hash=sha256:a151eca7da2b04b6bed1f70138b50f5634704b98ee3ee63046316d7661f21b75 \ + --hash=sha256:a26384540c88b7c157899c2a08ff34c180a83ec1de97064d80c68bf8141af2f4 \ + --hash=sha256:a34be674fe74b35a67ce768cbb86b9350caa22c4b04f2eb0d868d9c01f6539d1 \ + --hash=sha256:a3942e2d365f009e5e7839114fa315e1a2bcfea12b52064a28f1a7281862a2a7 \ + --hash=sha256:a3dea7e1ac49e29306500a8627fa3eacabcc9e238d22495eea2d8e61de77065b \ + --hash=sha256:a84e0ae14d1efe782a9f143021c4e01d5ed986a140fe5070505cc5978eaf0592 \ + --hash=sha256:a961713b7bb90671a7d601886f0d603c8276ae95c6c63baaf36957fddba6fa72 \ + --hash=sha256:a998857af4fcd19920bdf5f30f0f1a23f38472a703d33e49168cd4fd32438377 \ + --hash=sha256:aa32b51702a0b6e9fddc0d1dc66cb6ed6af112f1bba0cac2be9039546a862b5c \ + --hash=sha256:b0c32f0660bb21e810ffc1d3d04b6ea682e118b8141c6e12522a3dacadeb70ee \ + --hash=sha256:b0ee9e74480cb7393288ac2ed837e132200bfedd620e765e6db3a3192c9b5b9a \ + --hash=sha256:b0faa0b9af9367748388345d5b12f6add2a9cf896481e72910e88fbfe14ecd54 \ + --hash=sha256:b5b458950312830913f837e179ce9221000ab7a20b4e42d7b48c1fcd79140de1 \ + --hash=sha256:b8b2fc7901b31d5885f26521cf2d74feccdc126a272ba1d879b7545bb25468bc \ + --hash=sha256:b95809496769fb09777136f3e259433ac21c495f3517bf7aab7dfb5a95cfde8b \ + --hash=sha256:b9e56ed83aa2ad78496788afe87d830725a752deb590fa8b7c95e1105da21dc0 \ + --hash=sha256:bd18576a758364b194e9347e0859362e158df99fb0dec3af480578fd9d92ae27 \ + --hash=sha256:be371af72af54b6e508b68a7a87768e05b7e13023f6c82a3e3f5e4d0e829e186 \ + --hash=sha256:bfb2d71edaaa0c6e0e51c52328154c635aec3ee6ea6a29271fbac1a8bc157c12 \ + --hash=sha256:c3f667dc60a875b12a5ecd7828062ccd97c0fb79c4adc6c8699d23d5ff2af7e1 \ + --hash=sha256:c4b68ce579b05c66bb18a16356a4f713bebac2446ee498dd8bb1ecab3da77b89 \ + --hash=sha256:c4c82b91f512942db9bfb4f33ab6b8e17e49cba0e9e98ed34c0cf7c33a48a458 \ + --hash=sha256:c5302747f969d5ec925810176f7697712a3fa2ea0fae0c7a85aa4ad9325247fd \ + --hash=sha256:c741ff72829507be41dc50c731565fa2413287e845e55f0661dedf0a942c1c31 \ + --hash=sha256:c788fdab2eeeab671f5ab375ad010ef743f6c95be67f60f878e8876a51f6c671 \ + --hash=sha256:cba95509120e059fb1a13089428bfba90535b0fa296890650137282a066d7db2 \ + --hash=sha256:cc5eb1be95fb880bd083fb24df064bd5fc8caa85c05cf0ee5f33e2ddf9af625d \ + --hash=sha256:cd678af3f73bcacd0391897a8697e19ba4bd1445b35ba6d776342e64f8c98f29 \ + --hash=sha256:cfa54e7f5bd5ef482e7f5336f7cf3c30ae608d9767e514dd930b7c30a03fa977 \ + --hash=sha256:d6ef0035b6ae338a46951c144081c61fb044f4c1eb6d20acc5ba6277f666a4c0 \ + --hash=sha256:d9ff3dcfaf60de01805e0268a29947205a71742e02797ef07ca46a58ab2a3390 \ + --hash=sha256:dafaeb38712f99e5c31ad7f02c366f1ddd3792921b94066015f8c49f197163b0 \ + --hash=sha256:dca1bf90b3a6a7440904f128464eb95bf46ac9da7ad3c85912483dd83128fd95 \ + --hash=sha256:ddc832886517c5009863209a4a292c4353967cd304ba55822d533e0d59eb6a60 \ + --hash=sha256:de1bf30d819809a964060356032e6670c9923644666afaaf3d1719d05ddb844e \ + --hash=sha256:de499e2492c8106a5e163d3cf5b6726e2797f9234cfbc6055fbb5f9d8f198f39 \ + --hash=sha256:e4a7be59d374c445766fa4ac066a04d19a757365ae00a950053d0ab7388d1039 \ + --hash=sha256:e6c4fa55eab6b5684b33239597876a18a35ce1280b63ab960164032afbb8783f \ + --hash=sha256:ea396d0ab0c9e082e009a16d7bda6849784b411b884d86e287a1b0a36eb278fb \ + --hash=sha256:eaa5178a4c1fe619eff9cbe93b57919d426332e219870301d4ef5fc09a522ae9 \ + --hash=sha256:ecfb50c208c59d9a786262ab06ee25688d1ada618e48a442eb4a12b38835f294 \ + --hash=sha256:ed62c15ce5e8b975b2710a0f7c8bb953cbffb472fccb05055be6afcba9520c19 \ + --hash=sha256:ed8e452f5cb34f59f4861d50d029c6203b5f8f11c13d4186264392a64b4def8d \ + --hash=sha256:eea17e3cdc6f9aecffe15fe9a9eeba8e8c049a5d347de1561eed2240cdf35a79 \ + --hash=sha256:f00ff4b56caf151365c77988eb85a4a71eb26fe63047d4084d5614e06d65e3cf \ + --hash=sha256:f06dd6a30438692d48c0d54de4b659cd55a57c2c2f6591c969c98d0a5523ab07 \ + --hash=sha256:f20bec84117a324b6c4b679d2c748d2813df55e1fe181b3a6bcaa93b6719a772 \ + --hash=sha256:f34405292fca45cd77419005c1ea35ba1c03eaff9042afe76d6fe189fe474669 \ + --hash=sha256:f352f797b1477c46a20e45f4cbc3a0e258e61963c8ae8f79f84a7bfb4195b37e \ + --hash=sha256:f37ccd159dae35d4914651d57142c8077aa67ab7e3ffef690b00bcb7a7dbd8e6 \ + --hash=sha256:f51bca8fcac4266519533698c316f3d23340768a8e57c4796c9f6e0a4f353807 \ + --hash=sha256:f5342b8256476554b4045db8b7bf4dc4044d0405485f220f0cd80764bc0d7faf \ + --hash=sha256:f5fbda9703bce94a976e1a6bbdbbe0af25fb613a593a56091991359928b66c05 \ + --hash=sha256:f760d9a9c441bfc87eee720ddb0946d3e19995b20983ae14038e033f1664efcb \ + --hash=sha256:f9e9f04e5cb640cf7bbf6fdd4e3970e821138df320ae85cad81b4efc2f5cc802 \ + --hash=sha256:faa8520b1c2a3c8216065077e047f84b116405661b1ba070862dac82d464ef39 \ + --hash=sha256:fb5df75d1b1c42d997adbb39eac61f2cdb48efa26304a0cb9c0b757c9bc20732 \ + --hash=sha256:fb6a4d400aa531c73a718b337116fad77ba8dc6df34fa615c808bfc55ffb19ca \ + --hash=sha256:ff02e697d947f518e9e99f2b25698045a5ddffa95049c4d95b5a8cf3618d9008 +certifi==2026.10.23 \ + --hash=sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd \ + --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1 +cffi==2.0.0 \ + --hash=sha256:00bdf7acc5f795150faa6957054fbbca2439db2f775ce831222b66f192f03beb \ + --hash=sha256:07b271772c100085dd28b74fa0cd81c8fb1a3ba18b21e03d7c27f3436a10606b \ + --hash=sha256:087067fa8953339c723661eda6b54bc98c5625757ea62e95eb4898ad5e776e9f \ + --hash=sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9 \ + --hash=sha256:0cf2d91ecc3fcc0625c2c530fe004f82c110405f101548512cce44322fa8ac44 \ + --hash=sha256:0f6084a0ea23d05d20c3edcda20c3d006f9b6f3fefeac38f59262e10cef47ee2 \ + --hash=sha256:12873ca6cb9b0f0d3a0da705d6086fe911591737a59f28b7936bdfed27c0d47c \ + --hash=sha256:19f705ada2530c1167abacb171925dd886168931e0a7b78f5bffcae5c6b5be75 \ + --hash=sha256:1cd13c99ce269b3ed80b417dcd591415d3372bcac067009b6e0f59c7d4015e65 \ + --hash=sha256:1e3a615586f05fc4065a8b22b8152f0c1b00cdbc60596d187c2a74f9e3036e4e \ + --hash=sha256:1f72fb8906754ac8a2cc3f9f5aaa298070652a0ffae577e0ea9bd480dc3c931a \ + --hash=sha256:1fc9ea04857caf665289b7a75923f2c6ed559b8298a1b8c49e59f7dd95c8481e \ + --hash=sha256:203a48d1fb583fc7d78a4c6655692963b860a417c0528492a6bc21f1aaefab25 \ + --hash=sha256:2081580ebb843f759b9f617314a24ed5738c51d2aee65d31e02f6f7a2b97707a \ + --hash=sha256:21d1152871b019407d8ac3985f6775c079416c282e431a4da6afe7aefd2bccbe \ + --hash=sha256:24b6f81f1983e6df8db3adc38562c83f7d4a0c36162885ec7f7b77c7dcbec97b \ + --hash=sha256:256f80b80ca3853f90c21b23ee78cd008713787b1b1e93eae9f3d6a7134abd91 \ + --hash=sha256:28a3a209b96630bca57cce802da70c266eb08c6e97e5afd61a75611ee6c64592 \ + --hash=sha256:2c8f814d84194c9ea681642fd164267891702542f028a15fc97d4674b6206187 \ + --hash=sha256:2de9a304e27f7596cd03d16f1b7c72219bd944e99cc52b84d0145aefb07cbd3c \ + --hash=sha256:38100abb9d1b1435bc4cc340bb4489635dc2f0da7456590877030c9b3d40b0c1 \ + --hash=sha256:3925dd22fa2b7699ed2617149842d2e6adde22b262fcbfada50e3d195e4b3a94 \ + --hash=sha256:3e17ed538242334bf70832644a32a7aae3d83b57567f9fd60a26257e992b79ba \ + --hash=sha256:3e837e369566884707ddaf85fc1744b47575005c0a229de3327f8f9a20f4efeb \ + --hash=sha256:3f4d46d8b35698056ec29bca21546e1551a205058ae1a181d871e278b0b28165 \ + --hash=sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529 \ + --hash=sha256:45d5e886156860dc35862657e1494b9bae8dfa63bf56796f2fb56e1679fc0bca \ + --hash=sha256:4647afc2f90d1ddd33441e5b0e85b16b12ddec4fca55f0d9671fef036ecca27c \ + --hash=sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6 \ + --hash=sha256:53f77cbe57044e88bbd5ed26ac1d0514d2acf0591dd6bb02a3ae37f76811b80c \ + --hash=sha256:5eda85d6d1879e692d546a078b44251cdd08dd1cfb98dfb77b670c97cee49ea0 \ + --hash=sha256:5fed36fccc0612a53f1d4d9a816b50a36702c28a2aa880cb8a122b3466638743 \ + --hash=sha256:61d028e90346df14fedc3d1e5441df818d095f3b87d286825dfcbd6459b7ef63 \ + --hash=sha256:66f011380d0e49ed280c789fbd08ff0d40968ee7b665575489afa95c98196ab5 \ + --hash=sha256:6824f87845e3396029f3820c206e459ccc91760e8fa24422f8b0c3d1731cbec5 \ + --hash=sha256:6c6c373cfc5c83a975506110d17457138c8c63016b563cc9ed6e056a82f13ce4 \ + --hash=sha256:6d02d6655b0e54f54c4ef0b94eb6be0607b70853c45ce98bd278dc7de718be5d \ + --hash=sha256:6d50360be4546678fc1b79ffe7a66265e28667840010348dd69a314145807a1b \ + --hash=sha256:730cacb21e1bdff3ce90babf007d0a0917cc3e6492f336c2f0134101e0944f93 \ + --hash=sha256:737fe7d37e1a1bffe70bd5754ea763a62a066dc5913ca57e957824b72a85e205 \ + --hash=sha256:74a03b9698e198d47562765773b4a8309919089150a0bb17d829ad7b44b60d27 \ + --hash=sha256:7553fb2090d71822f02c629afe6042c299edf91ba1bf94951165613553984512 \ + --hash=sha256:7a66c7204d8869299919db4d5069a82f1561581af12b11b3c9f48c584eb8743d \ + --hash=sha256:7cc09976e8b56f8cebd752f7113ad07752461f48a58cbba644139015ac24954c \ + --hash=sha256:81afed14892743bbe14dacb9e36d9e0e504cd204e0b165062c488942b9718037 \ + --hash=sha256:8941aaadaf67246224cee8c3803777eed332a19d909b47e29c9842ef1e79ac26 \ + --hash=sha256:89472c9762729b5ae1ad974b777416bfda4ac5642423fa93bd57a09204712322 \ + --hash=sha256:8ea985900c5c95ce9db1745f7933eeef5d314f0565b27625d9a10ec9881e1bfb \ + --hash=sha256:8eca2a813c1cb7ad4fb74d368c2ffbbb4789d377ee5bb8df98373c2cc0dee76c \ + --hash=sha256:92b68146a71df78564e4ef48af17551a5ddd142e5190cdf2c5624d0c3ff5b2e8 \ + --hash=sha256:9332088d75dc3241c702d852d4671613136d90fa6881da7d770a483fd05248b4 \ + --hash=sha256:94698a9c5f91f9d138526b48fe26a199609544591f859c870d477351dc7b2414 \ + --hash=sha256:9a67fc9e8eb39039280526379fb3a70023d77caec1852002b4da7e8b270c4dd9 \ + --hash=sha256:9de40a7b0323d889cf8d23d1ef214f565ab154443c42737dfe52ff82cf857664 \ + --hash=sha256:a05d0c237b3349096d3981b727493e22147f934b20f6f125a3eba8f994bec4a9 \ + --hash=sha256:afb8db5439b81cf9c9d0c80404b60c3cc9c3add93e114dcae767f1477cb53775 \ + --hash=sha256:b18a3ed7d5b3bd8d9ef7a8cb226502c6bf8308df1525e1cc676c3680e7176739 \ + --hash=sha256:b1e74d11748e7e98e2f426ab176d4ed720a64412b6a15054378afdb71e0f37dc \ + --hash=sha256:b21e08af67b8a103c71a250401c78d5e0893beff75e28c53c98f4de42f774062 \ + --hash=sha256:b4c854ef3adc177950a8dfc81a86f5115d2abd545751a304c5bcf2c2c7283cfe \ + --hash=sha256:b882b3df248017dba09d6b16defe9b5c407fe32fc7c65a9c69798e6175601be9 \ + --hash=sha256:baf5215e0ab74c16e2dd324e8ec067ef59e41125d3eade2b863d294fd5035c92 \ + --hash=sha256:c649e3a33450ec82378822b3dad03cc228b8f5963c0c12fc3b1e0ab940f768a5 \ + --hash=sha256:c654de545946e0db659b3400168c9ad31b5d29593291482c43e3564effbcee13 \ + --hash=sha256:c6638687455baf640e37344fe26d37c404db8b80d037c3d29f58fe8d1c3b194d \ + --hash=sha256:c8d3b5532fc71b7a77c09192b4a5a200ea992702734a2e9279a37f2478236f26 \ + --hash=sha256:cb527a79772e5ef98fb1d700678fe031e353e765d1ca2d409c92263c6d43e09f \ + --hash=sha256:cf364028c016c03078a23b503f02058f1814320a56ad535686f90565636a9495 \ + --hash=sha256:d48a880098c96020b02d5a1f7d9251308510ce8858940e6fa99ece33f610838b \ + --hash=sha256:d68b6cef7827e8641e8ef16f4494edda8b36104d79773a334beaa1e3521430f6 \ + --hash=sha256:d9b29c1f0ae438d5ee9acb31cadee00a58c46cc9c0b2f9038c6b0b3470877a8c \ + --hash=sha256:d9b97165e8aed9272a6bb17c01e3cc5871a594a446ebedc996e2397a1c1ea8ef \ + --hash=sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5 \ + --hash=sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18 \ + --hash=sha256:dbd5c7a25a7cb98f5ca55d258b103a2054f859a46ae11aaf23134f9cc0d356ad \ + --hash=sha256:dd4f05f54a52fb558f1ba9f528228066954fee3ebe629fc1660d874d040ae5a3 \ + --hash=sha256:de8dad4425a6ca6e4e5e297b27b5c824ecc7581910bf9aee86cb6835e6812aa7 \ + --hash=sha256:e11e82b744887154b182fd3e7e8512418446501191994dbf9c9fc1f32cc8efd5 \ + --hash=sha256:e6e73b9e02893c764e7e8d5bb5ce277f1a009cd5243f8228f75f842bf937c534 \ + --hash=sha256:f73b96c41e3b2adedc34a7356e64c8eb96e03a3782b535e043a986276ce12a49 \ + --hash=sha256:f93fd8e5c8c0a4aa1f424d6173f14a892044054871c771f8566e4008eaa359d2 \ + --hash=sha256:fc33c5141b55ed366cfaad382df24fe7dcbc686de5be719b207bb248e3053dc5 \ + --hash=sha256:fc7de24befaeae77ba923797c7c87834c73648a05a4bde34b3b7e5588973a453 \ + --hash=sha256:fe562eb1a64e67dd297ccc4f5addea2501664954f2692b69a76449ec7913ecbf +charset-normalizer==3.4.4 \ + --hash=sha256:027f6de494925c0ab2a55eab46ae5129951638a49a34d87f4c3eda90f696b4ad \ + --hash=sha256:077fbb858e903c73f6c9db43374fd213b0b6a778106bc7032446a8e8b5b38b93 \ + --hash=sha256:0a98e6759f854bd25a58a73fa88833fba3b7c491169f86ce1180c948ab3fd394 \ + --hash=sha256:0d3d8f15c07f86e9ff82319b3d9ef6f4bf907608f53fe9d92b28ea9ae3d1fd89 \ + --hash=sha256:0f04b14ffe5fdc8c4933862d8306109a2c51e0704acfa35d51598eb45a1e89fc \ + --hash=sha256:11d694519d7f29d6cd09f6ac70028dba10f92f6cdd059096db198c283794ac86 \ + --hash=sha256:194f08cbb32dc406d6e1aea671a68be0823673db2832b38405deba2fb0d88f63 \ + --hash=sha256:1bee1e43c28aa63cb16e5c14e582580546b08e535299b8b6158a7c9c768a1f3d \ + --hash=sha256:21d142cc6c0ec30d2efee5068ca36c128a30b0f2c53c1c07bd78cb6bc1d3be5f \ + --hash=sha256:2437418e20515acec67d86e12bf70056a33abdacb5cb1655042f6538d6b085a8 \ + --hash=sha256:244bfb999c71b35de57821b8ea746b24e863398194a4014e4c76adc2bbdfeff0 \ + --hash=sha256:2677acec1a2f8ef614c6888b5b4ae4060cc184174a938ed4e8ef690e15d3e505 \ + --hash=sha256:277e970e750505ed74c832b4bf75dac7476262ee2a013f5574dd49075879e161 \ + --hash=sha256:2aaba3b0819274cc41757a1da876f810a3e4d7b6eb25699253a4effef9e8e4af \ + --hash=sha256:2b7d8f6c26245217bd2ad053761201e9f9680f8ce52f0fcd8d0755aeae5b2152 \ + --hash=sha256:2c9d3c380143a1fedbff95a312aa798578371eb29da42106a29019368a475318 \ + --hash=sha256:3162d5d8ce1bb98dd51af660f2121c55d0fa541b46dff7bb9b9f86ea1d87de72 \ + --hash=sha256:31fd66405eaf47bb62e8cd575dc621c56c668f27d46a61d975a249930dd5e2a4 \ + --hash=sha256:362d61fd13843997c1c446760ef36f240cf81d3ebf74ac62652aebaf7838561e \ + --hash=sha256:376bec83a63b8021bb5c8ea75e21c4ccb86e7e45ca4eb81146091b56599b80c3 \ + --hash=sha256:44c2a8734b333e0578090c4cd6b16f275e07aa6614ca8715e6c038e865e70576 \ + --hash=sha256:47cc91b2f4dd2833fddaedd2893006b0106129d4b94fdb6af1f4ce5a9965577c \ + --hash=sha256:4902828217069c3c5c71094537a8e623f5d097858ac6ca8252f7b4d10b7560f1 \ + --hash=sha256:4bd5d4137d500351a30687c2d3971758aac9a19208fc110ccb9d7188fbe709e8 \ + --hash=sha256:4fe7859a4e3e8457458e2ff592f15ccb02f3da787fcd31e0183879c3ad4692a1 \ + --hash=sha256:542d2cee80be6f80247095cc36c418f7bddd14f4a6de45af91dfad36d817bba2 \ + --hash=sha256:554af85e960429cf30784dd47447d5125aaa3b99a6f0683589dbd27e2f45da44 \ + --hash=sha256:5833d2c39d8896e4e19b689ffc198f08ea58116bee26dea51e362ecc7cd3ed26 \ + --hash=sha256:5947809c8a2417be3267efc979c47d76a079758166f7d43ef5ae8e9f92751f88 \ + --hash=sha256:5ae497466c7901d54b639cf42d5b8c1b6a4fead55215500d2f486d34db48d016 \ + --hash=sha256:5bd2293095d766545ec1a8f612559f6b40abc0eb18bb2f5d1171872d34036ede \ + --hash=sha256:5bfbb1b9acf3334612667b61bd3002196fe2a1eb4dd74d247e0f2a4d50ec9bbf \ + --hash=sha256:5cb4d72eea50c8868f5288b7f7f33ed276118325c1dfd3957089f6b519e1382a \ + --hash=sha256:5dbe56a36425d26d6cfb40ce79c314a2e4dd6211d51d6d2191c00bed34f354cc \ + --hash=sha256:5f819d5fe9234f9f82d75bdfa9aef3a3d72c4d24a6e57aeaebba32a704553aa0 \ + --hash=sha256:64b55f9dce520635f018f907ff1b0df1fdc31f2795a922fb49dd14fbcdf48c84 \ + --hash=sha256:6515f3182dbe4ea06ced2d9e8666d97b46ef4c75e326b79bb624110f122551db \ + --hash=sha256:65e2befcd84bc6f37095f5961e68a6f077bf44946771354a28ad434c2cce0ae1 \ + --hash=sha256:6aee717dcfead04c6eb1ce3bd29ac1e22663cdea57f943c87d1eab9a025438d7 \ + --hash=sha256:6b39f987ae8ccdf0d2642338faf2abb1862340facc796048b604ef14919e55ed \ + --hash=sha256:6e1fcf0720908f200cd21aa4e6750a48ff6ce4afe7ff5a79a90d5ed8a08296f8 \ + --hash=sha256:74018750915ee7ad843a774364e13a3db91682f26142baddf775342c3f5b1133 \ + --hash=sha256:74664978bb272435107de04e36db5a9735e78232b85b77d45cfb38f758efd33e \ + --hash=sha256:74bb723680f9f7a6234dcf67aea57e708ec1fbdf5699fb91dfd6f511b0a320ef \ + --hash=sha256:752944c7ffbfdd10c074dc58ec2d5a8a4cd9493b314d367c14d24c17684ddd14 \ + --hash=sha256:778d2e08eda00f4256d7f672ca9fef386071c9202f5e4607920b86d7803387f2 \ + --hash=sha256:780236ac706e66881f3b7f2f32dfe90507a09e67d1d454c762cf642e6e1586e0 \ + --hash=sha256:798d75d81754988d2565bff1b97ba5a44411867c0cf32b77a7e8f8d84796b10d \ + --hash=sha256:799a7a5e4fb2d5898c60b640fd4981d6a25f1c11790935a44ce38c54e985f828 \ + --hash=sha256:7a32c560861a02ff789ad905a2fe94e3f840803362c84fecf1851cb4cf3dc37f \ + --hash=sha256:7c308f7e26e4363d79df40ca5b2be1c6ba9f02bdbccfed5abddb7859a6ce72cf \ + --hash=sha256:7fa17817dc5625de8a027cb8b26d9fefa3ea28c8253929b8d6649e705d2835b6 \ + --hash=sha256:81d5eb2a312700f4ecaa977a8235b634ce853200e828fbadf3a9c50bab278328 \ + --hash=sha256:82004af6c302b5d3ab2cfc4cc5f29db16123b1a8417f2e25f9066f91d4411090 \ + --hash=sha256:837c2ce8c5a65a2035be9b3569c684358dfbf109fd3b6969630a87535495ceaa \ + --hash=sha256:840c25fb618a231545cbab0564a799f101b63b9901f2569faecd6b222ac72381 \ + --hash=sha256:8a6562c3700cce886c5be75ade4a5db4214fda19fede41d9792d100288d8f94c \ + --hash=sha256:8af65f14dc14a79b924524b1e7fffe304517b2bff5a58bf64f30b98bbc5079eb \ + --hash=sha256:8ef3c867360f88ac904fd3f5e1f902f13307af9052646963ee08ff4f131adafc \ + --hash=sha256:94537985111c35f28720e43603b8e7b43a6ecfb2ce1d3058bbe955b73404e21a \ + --hash=sha256:99ae2cffebb06e6c22bdc25801d7b30f503cc87dbd283479e7b606f70aff57ec \ + --hash=sha256:9a26f18905b8dd5d685d6d07b0cdf98a79f3c7a918906af7cc143ea2e164c8bc \ + --hash=sha256:9b35f4c90079ff2e2edc5b26c0c77925e5d2d255c42c74fdb70fb49b172726ac \ + --hash=sha256:9cd98cdc06614a2f768d2b7286d66805f94c48cde050acdbbb7db2600ab3197e \ + --hash=sha256:9d1bb833febdff5c8927f922386db610b49db6e0d4f4ee29601d71e7c2694313 \ + --hash=sha256:9f7fcd74d410a36883701fafa2482a6af2ff5ba96b9a620e9e0721e28ead5569 \ + --hash=sha256:a59cb51917aa591b1c4e6a43c132f0cdc3c76dbad6155df4e28ee626cc77a0a3 \ + --hash=sha256:a61900df84c667873b292c3de315a786dd8dac506704dea57bc957bd31e22c7d \ + --hash=sha256:a79cfe37875f822425b89a82333404539ae63dbdddf97f84dcbc3d339aae9525 \ + --hash=sha256:a8a8b89589086a25749f471e6a900d3f662d1d3b6e2e59dcecf787b1cc3a1894 \ + --hash=sha256:a8bf8d0f749c5757af2142fe7903a9df1d2e8aa3841559b2bad34b08d0e2bcf3 \ + --hash=sha256:a9768c477b9d7bd54bc0c86dbaebdec6f03306675526c9927c0e8a04e8f94af9 \ + --hash=sha256:ac1c4a689edcc530fc9d9aa11f5774b9e2f33f9a0c6a57864e90908f5208d30a \ + --hash=sha256:af2d8c67d8e573d6de5bc30cdb27e9b95e49115cd9baad5ddbd1a6207aaa82a9 \ + --hash=sha256:b435cba5f4f750aa6c0a0d92c541fb79f69a387c91e61f1795227e4ed9cece14 \ + --hash=sha256:b5b290ccc2a263e8d185130284f8501e3e36c5e02750fc6b6bdeb2e9e96f1e25 \ + --hash=sha256:b5d84d37db046c5ca74ee7bb47dd6cbc13f80665fdde3e8040bdd3fb015ecb50 \ + --hash=sha256:b7cf1017d601aa35e6bb650b6ad28652c9cd78ee6caff19f3c28d03e1c80acbf \ + --hash=sha256:bc7637e2f80d8530ee4a78e878bce464f70087ce73cf7c1caf142416923b98f1 \ + --hash=sha256:c0463276121fdee9c49b98908b3a89c39be45d86d1dbaa22957e38f6321d4ce3 \ + --hash=sha256:c4ef880e27901b6cc782f1b95f82da9313c0eb95c3af699103088fa0ac3ce9ac \ + --hash=sha256:c8ae8a0f02f57a6e61203a31428fa1d677cbe50c93622b4149d5c0f319c1d19e \ + --hash=sha256:ca5862d5b3928c4940729dacc329aa9102900382fea192fc5e52eb69d6093815 \ + --hash=sha256:cb01158d8b88ee68f15949894ccc6712278243d95f344770fa7593fa2d94410c \ + --hash=sha256:cb6254dc36b47a990e59e1068afacdcd02958bdcce30bb50cc1700a8b9d624a6 \ + --hash=sha256:cc00f04ed596e9dc0da42ed17ac5e596c6ccba999ba6bd92b0e0aef2f170f2d6 \ + --hash=sha256:cd09d08005f958f370f539f186d10aec3377d55b9eeb0d796025d4886119d76e \ + --hash=sha256:cd4b7ca9984e5e7985c12bc60a6f173f3c958eae74f3ef6624bb6b26e2abbae4 \ + --hash=sha256:ce8a0633f41a967713a59c4139d29110c07e826d131a316b50ce11b1d79b4f84 \ + --hash=sha256:cead0978fc57397645f12578bfd2d5ea9138ea0fac82b2f63f7f7c6877986a69 \ + --hash=sha256:d055ec1e26e441f6187acf818b73564e6e6282709e9bcb5b63f5b23068356a15 \ + --hash=sha256:d1f13550535ad8cff21b8d757a3257963e951d96e20ec82ab44bc64aeb62a191 \ + --hash=sha256:d9c7f57c3d666a53421049053eaacdd14bbd0a528e2186fcb2e672effd053bb0 \ + --hash=sha256:d9e45d7faa48ee908174d8fe84854479ef838fc6a705c9315372eacbc2f02897 \ + --hash=sha256:da3326d9e65ef63a817ecbcc0df6e94463713b754fe293eaa03da99befb9a5bd \ + --hash=sha256:de00632ca48df9daf77a2c65a484531649261ec9f25489917f09e455cb09ddb2 \ + --hash=sha256:e1f185f86a6f3403aa2420e815904c67b2f9ebc443f045edd0de921108345794 \ + --hash=sha256:e824f1492727fa856dd6eda4f7cee25f8518a12f3c4a56a74e8095695089cf6d \ + --hash=sha256:e912091979546adf63357d7e2ccff9b44f026c075aeaf25a52d0e95ad2281074 \ + --hash=sha256:eaabd426fe94daf8fd157c32e571c85cb12e66692f15516a83a03264b08d06c3 \ + --hash=sha256:ebf3e58c7ec8a8bed6d66a75d7fb37b55e5015b03ceae72a8e7c74495551e224 \ + --hash=sha256:ecaae4149d99b1c9e7b88bb03e3221956f68fd6d50be2ef061b2381b61d20838 \ + --hash=sha256:eecbc200c7fd5ddb9a7f16c7decb07b566c29fa2161a16cf67b8d068bd21690a \ + --hash=sha256:f155a433c2ec037d4e8df17d18922c3a0d9b3232a396690f17175d2946f0218d \ + --hash=sha256:f1e34719c6ed0b92f418c7c780480b26b5d9c50349e9a9af7d76bf757530350d \ + --hash=sha256:f34be2938726fc13801220747472850852fe6b1ea75869a048d6f896838c896f \ + --hash=sha256:f820802628d2694cb7e56db99213f930856014862f3fd943d290ea8438d07ca8 \ + --hash=sha256:f8bf04158c6b607d747e93949aa60618b61312fe647a6369f88ce2ff16043490 \ + --hash=sha256:f8e160feb2aed042cd657a72acc0b481212ed28b1b9a95c0cee1621b524e1966 \ + --hash=sha256:f9d332f8c2a2fcbffe1378594431458ddbef721c1769d78e2cbc06280d8155f9 \ + --hash=sha256:fa09f53c465e532f4d3db095e0c55b615f010ad81803d383195b6b5ca6cbf5f3 \ + --hash=sha256:faa3a41b2b66b6e50f84ae4a68c64fcd0c44355741c6374813a800cd6695db9e \ + --hash=sha256:fd44c878ea55ba351104cb93cc85e74916eb8fa440ca7903e57575e97394f608 +click==8.5.1 \ + --hash=sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37 \ + --hash=sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4 +contourpy==1.4.0 \ + --hash=sha256:018227e134b73090b06f911e773a526c77c9af426be29065500ce096a5accd4c \ + --hash=sha256:072a702e2e178f4fcf96f04775d0c059e4c917925abf0d3208ebb6865df3c23d \ + --hash=sha256:0c7a4c2716a4e98342221954416a836cca77c996c14ddbf22b5f01d5d93ca09c \ + --hash=sha256:107ec46f7aa1664266d69b1181aadc953d58d39f7d8d648fa5b795d4a060b0de \ + --hash=sha256:181bea01bc742734ae672fa00c717d855dd35e1f029536406538c52e7b0cd73d \ + --hash=sha256:186ba929df36d61b6127da2e89cd1357e4cb79aca647381ab1a6feb0b152877b \ + --hash=sha256:196759a3e4db60e1546167e361090ebb6d199aa3aafc9e34ea17a5ac3b23e814 \ + --hash=sha256:20156f5a1ac4f8ce02656e39a61e82164a3d359796dc8026f75b062783d500e1 \ + --hash=sha256:20da2f86bfaed60dbba729fe738c8241b1dd22b6cf7e8cbbf30df290bd04ba28 \ + --hash=sha256:2deb580178ca19437a84bd77e4bc2cd91a8ccad212413a83c273900868b5978c \ + --hash=sha256:2e741a39dfc96babe1722561e81351aeec104526c57dbe91c167c1db606c2d55 \ + --hash=sha256:3863ef2e2b13fe93f8c0ebb08ee400cb07153b8b0e91c5acb26e4537f283634f \ + --hash=sha256:3e0a2392533e5e2abdf277c951047516acc8d2f3c42b2dd9dc34c907c9ebabf2 \ + --hash=sha256:404dbcd9233513dfd1323b66ea593fef90e899f658f6b8a9ed8e93bd0ca669db \ + --hash=sha256:417be048f7e122cefbe2a34c51a1f2b0410f8eb35796f794d45475ddb7872d9d \ + --hash=sha256:423bd5f4b3f11d54a8c597234e513382e3454bb106b8ec7ae32ba4ed63f8d99b \ + --hash=sha256:432e89f835cf01f8d2123a130a3126b17ee6e0348e4d62c0973872b30aa873bf \ + --hash=sha256:43c3ccbb32c6294b183dcc8e8c46dacf5ecef809497e3d48a5be298eef185ad0 \ + --hash=sha256:43d80072a32299bf945de0a6dd4e034ea0162e832261de2e07a274a5adbba9c9 \ + --hash=sha256:4bffcb2e8cc5c0e837631acab59dd04265fdac376550e7c3e310523877c68cb7 \ + --hash=sha256:510f7d93d94cf6ebf4e2cd0640bea16ab8affac7547230175b6745b596ce0599 \ + --hash=sha256:5450f091ac1be0be3ad3a2a3b3f23b5e443e78c670ced4fd347d626f92a28fd2 \ + --hash=sha256:5545ff38229c15d11d822fc6f7415b932da9f4975f53e305b7b96ebfb01f889c \ + --hash=sha256:5a4c89c7f38a0d7a94356d74e3391073c4325c4d47ad2fd065c3fe7dbae16c0c \ + --hash=sha256:61624f6722480aa7e168fd746164e7bfdf48f8ccb6542f1613741200dc37e2b1 \ + --hash=sha256:618137ec5778fb76d494c9ec854b104a377fddba0d128bef7136cce2c3bf0df8 \ + --hash=sha256:630d32f06cedf37b7f1dd2b6a12e4492826bd477a4c9c7b2e2fee6ce3a2cea76 \ + --hash=sha256:64039341e2d8804f1a13bda8c69083eab935167bbd7e856cf096241f17d5bd45 \ + --hash=sha256:6507a016976a75a15aee47809a34605de6244ccc056e6164bf9fb14b27eecad4 \ + --hash=sha256:6ced1670fafee703b8277ab1645072a226e74f167166eae146fb743916119b67 \ + --hash=sha256:6e697d94e69f499ff6bebb899cae97a58d5d14f0e1fe9568b43a0248d2f9af8c \ + --hash=sha256:6f963ea9f0d68d2b6a02d861e3c0aae09ae25ba21f243fcf281e9fed468b078d \ + --hash=sha256:738c44fa71735a617f36da58e32810512407d283d5d1bb5b1cecb00d7eeba7cf \ + --hash=sha256:758e7496cec3195fc28a28945eab3ceef348c47fb95c7afc2eca2f3901209c8c \ + --hash=sha256:78ed5c5f962b3e156109f0531b174a65ba80d13cc681a70227b12524c162e184 \ + --hash=sha256:79b06c60d5e569ce12c5da8f0c51217cdc484386e2349fa717c30fafb56d2871 \ + --hash=sha256:7f861af508fca2384eef392bc1d8377cfa349b2b854cb11b45d89c75780e2561 \ + --hash=sha256:80c7fc8e7ac217777ce7ba2db3cf8478652b5a4b335283111012ff9eaac9d842 \ + --hash=sha256:86d05cec773c9507a3950122e0e40ce77c23c75ceeb2fc189514e71893cbb34b \ + --hash=sha256:875f42444c9cf48d56f724f2637e60d0f73b3b12c9041e1484580a233edf9591 \ + --hash=sha256:90feb8da006803a95ba573fddc9536357d0c3faddc3a4c9e22816ca49af52878 \ + --hash=sha256:912c6afaa106e2f74ba22b30416b77ef7eb94e3bdc5a4df51ab147845dba9b6d \ + --hash=sha256:96019f059bcb3774acc0104be3360a57b36d33eaaa2e1d7f77c800ca8e07618b \ + --hash=sha256:9c0e07c691f3b3321913ed9b8161c50ea5f77fadd006f52f5e755359b0dcbfc5 \ + --hash=sha256:a03b32c2e7eda8b17757c022162c13c86f5c3d6f937dddf9ba3c3ff7b513953b \ + --hash=sha256:a1c8a74744fa746eeaa12f0f9ed7f8b4add9d8f1b14d95e3b5e133675eac888f \ + --hash=sha256:a3e67bc1a6a4618a1dac7c3053a9ffece5ddfa2046b2670b342cf430bb0b87d1 \ + --hash=sha256:a58b5f130afec61a093d743cdda435cc4047748b6791627e34a68f41ec3a9b07 \ + --hash=sha256:a5e2bb871b90cd7a52bdee63bf80ef7acb46398d27efc66d7679240016efc5aa \ + --hash=sha256:abd0f7e51ecc52bf8c95713bd80b1c17c516a71fa391c54475308a4377903c2b \ + --hash=sha256:b7794ea07cab575633daad8d6e963b662053391022294d3aacc1d9ba9ef54114 \ + --hash=sha256:b9dc493e7924e5aa32d89d0b8e50986280f3d4b284968a792787bd7bcffd3cad \ + --hash=sha256:be85d160e7c795113c2a93254dde2fc7e86b375322570eee78b420969426973c \ + --hash=sha256:bee6ff96653e0807cd0f8eaef00174a031e3a2effa5c20f49a5a8d574b05af23 \ + --hash=sha256:c76f3a5318164db7d9401132fc1b5364b784c613c93fa506e3b5e6d1bf353ec8 \ + --hash=sha256:c8be3392b84cf43373a488874dc1ebf46f60784a70977f92586e18019d71c7ed \ + --hash=sha256:c927ec747633e68c9920bcaad48b0bcefe648812b822f18c34e2d0e2270a3d2a \ + --hash=sha256:cc87f2ffa84a49a77d76cb792f28a48ff3b05a222aa0b2bddbd839ba78e1d5ca \ + --hash=sha256:dd59df9e2fb0aff8bd7fd1adb9f349b7c835245a9d0f18c2f2deeb537190f2b1 \ + --hash=sha256:ddf5a2596d716fd3793434844caf31abc7a40b1e8718431420c89858268fb909 \ + --hash=sha256:de503609fdb71f597634ca64fb4bd2f13d27c97f140e912b1e8ed93544840df0 \ + --hash=sha256:e21d1d4a9db5b3a793649c7ab0ddb4697f2818929eec871a7b9c45fce7b2a1ea \ + --hash=sha256:e439ab450c93455feb0218532ded3e946ec7a9b5f459069f122cfa44b89229f6 \ + --hash=sha256:ea09dc704029930cbd097f75cb0cc1db9852adbcf1a151fac7e9559f7bcbfd19 \ + --hash=sha256:ef47fef9a912c77e3d84b014f701e5a9340f25703e9ed3bcebe37f91fb69dc49 \ + --hash=sha256:ef9440f6f8506246269a82734f5ff9e2e4c5e775b3996fc883cc491c5257eca6 \ + --hash=sha256:f1219a8898523cba821085f2da8a1b962cc696325763f09d7f93538ba43b2d70 \ + --hash=sha256:f863c6100bf926cf47d13f3cd75f9bb8ebd98aaab230eeb4468b91f98f39a6b3 \ + --hash=sha256:fa1b787362a3856e63dd2b89449f6c384d55ee1beb8f94f4bcc871b40f02462c \ + --hash=sha256:fc9feef8f1f001c5b87decadc67c4a5d1eebb62ca39c4763d1237ff62cf2b707 +cycler==0.12.1 \ + --hash=sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30 \ + --hash=sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c +diffusers==0.38.0 \ + --hash=sha256:18e53f9e539096320470f62c6360a6fd5727ff28cffda566265316e13fcdb612 \ + --hash=sha256:1e094ec5c16f18c42fb89d37f07a94cf9aab3ebbe527ab059c609597b8857626 +einops==0.8.2 \ + --hash=sha256:54058201ac7087911181bfec4af6091bb59380360f069276601256a76af08193 \ + --hash=sha256:609da665570e5e265e27283aab09e7f279ade90c4f01bcfca111f3d3e13f2827 +einx==0.3.0 \ + --hash=sha256:17ff87c6a0f68ab358c1da489f00e95f1de106fd12ff17d0fb3e210aaa1e5f8c \ + --hash=sha256:367d62bab8dbb8c4937308512abb6f746cc0920990589892ba0d281356d39345 +filelock==4.2.4 \ + --hash=sha256:301241438c57936ef93f4243a94f2559022268bfcf9b375a9a72eb0f8db8358e \ + --hash=sha256:c6d8663535e1650ee430507b4ffbac7b464dd64b7647ea0112a9f406499d163d +fonttools==4.68.0 \ + --hash=sha256:039142b75a068c93f8596ef68787f82c74940b9153d24c224ab31e750eb083a2 \ + --hash=sha256:03c9ef1272e464747f67c623f76449b888da6d5de7fb46275bb36488b9ceedba \ + --hash=sha256:04365b897c9ee29a048b6d4db74c75c38b70aa6d1074726fbdd7ea1a23aa8ed2 \ + --hash=sha256:04a4868dcfcc23f00bb033147d5afc1a118a992842644c3eb9da55467ab4fd74 \ + --hash=sha256:054a4d5de7e1f973ab9789e9ae3f20238774783ca9bf7ee0359aebae4de9400c \ + --hash=sha256:0841a4dac69efda309fca2ed0834186ee66d39787f1d26430ed7f779a699a096 \ + --hash=sha256:08851f7d2b983412f490b73a7c56f17cbda1d4d85d2ad3f857564bf15b5d9475 \ + --hash=sha256:1695cd2e1f9768fe3f14d369ce6ef1b3e8561069cc9e47059571985d1ea42614 \ + --hash=sha256:1782f2cf952eb262c4126b1f57b5f0e027e71bf2b632350a033dec526f448428 \ + --hash=sha256:1dde2f0ec3fd0fb43cf818593b38a8202eb7f3b59cae86289a8b19fbf6f6313b \ + --hash=sha256:35425bba603cf9d72c9f3c173ea6c98632164f3bdfb1ce1a3dcc928979c6ec6d \ + --hash=sha256:362443ab355701d6fd26b10d022cd6c8456e1e248f80103c44cbe5ef0228f87f \ + --hash=sha256:39913c1f576af86c69519dc351302332561ee62b39fed04dcfa8019d9c2d129f \ + --hash=sha256:3b9b87645bcdbfc3f30240e2758a37bbef4fdd0f708683b2bfceb60975d63e59 \ + --hash=sha256:3edce69ecdefa73ab1041901ca22eefed6ebb93a77bc77e889d940479f25bf7d \ + --hash=sha256:419bf78474adaa6fb320a06822f4f941b19345d598a9de379d6e2f0e4d819df6 \ + --hash=sha256:4b9c89b5876f1a74b1341632dfaf4c4c2be565d76c060445df401ebe7a4ceefa \ + --hash=sha256:4bc352572abc800177fba513995c01b1cfbe8c810ac2506cbf29f0795ae061c5 \ + --hash=sha256:4be32afa53ba3dea243b95b62e9b2e6ed6cf7096acd741d379c12f4113694ddc \ + --hash=sha256:4da99b83ae17f531838bc750abf56164ff37e1543e8e9b2b5403548f50497ce0 \ + --hash=sha256:5083a456d68d2995ab78600ccb18ec08c42f9bc14f0ef80c12e2e5b11cc371ce \ + --hash=sha256:53f2387d7e3816763f30e08d14263be18e28ead53d4dc20a82f9280d0c99d88a \ + --hash=sha256:573ccce8b5fd9b6952dcbc5d896255041ab330cc33520d13b1266fca859d8aba \ + --hash=sha256:664dfa7a4869b3c827dfc2c38dbbb7a58d53e97933d1bd51ee6729792ee73d50 \ + --hash=sha256:6aea5cdbc32f5fd202cf8dec053a784b08692f8b1992af80eba32bef82bf84c7 \ + --hash=sha256:6e73d4b1526343b45bbafa9badc0396a49d902f9a1774666ed4244f1df717629 \ + --hash=sha256:6ed796b220654b4d37ad20af73419ec7969b669dd678cab88afb602c5683a331 \ + --hash=sha256:73294e233070f71e2b3653b6bd8564af676d57f26d075761fb06d1ab2e4a7a5d \ + --hash=sha256:7ab8097e7e191784974c5608eb95fb31e1243fe3054cb66778ac82558e9b36f8 \ + --hash=sha256:81ea963d4390bb9e79f91a905310d91ac7ff7675d8e1c0cfc0f1712521c41a43 \ + --hash=sha256:82b8024fbdcddc399b1e21575b9b82f46b8391e711a44d6bd4a1616b0aca3681 \ + --hash=sha256:83bd3d558c15f4e1d87b8f3fcfb337c2bce63c7e5c05212abc8fdcf15e216c54 \ + --hash=sha256:86d319a1feedfc75c8ff582d947b21fa1854e2829cb8cf9428784d750a05f1d9 \ + --hash=sha256:93afd51f30ae38f7d826f4632eb799a06bd94e1fb4bc59fdce6d291e93491027 \ + --hash=sha256:956230858b7a7bb9f5e0971ae07dc64b6155307304acd8c62aedca30e6aae874 \ + --hash=sha256:95628bbc5ea81d5761268f4c4f1ba709af510b970f363498ac801c0c1fd7a4a8 \ + --hash=sha256:9b6e4ae9763c67df2b0f4c4f1a0b18e47ee6572eb602b82e798acc88b64a6137 \ + --hash=sha256:9d80813ae74b969ef2166a3040b591826e80ecd879bdeab7f13f4e8eaf08b345 \ + --hash=sha256:9fee5880486c3fd6f45f5a1679a9f4291ae74e503d725de7f1e30efa2d627440 \ + --hash=sha256:a325e6d7f96f20b3004658c5ed17ccfce5b66277b43ccd883035c61be6945275 \ + --hash=sha256:a6837def5de49772b82683dadd836df214def04b307cb98d0e7723d49e7e15bb \ + --hash=sha256:ab6505dfbe3199453d8542b25f55c1ea3260d38029d9db58c0c7304d438abdc0 \ + --hash=sha256:b2ee7b9c1a5e1d637073c39b0978956febad7e862a1269719f527934c65535a4 \ + --hash=sha256:b41e71b2657c9843b2327b4e3c116db1757dc8cd05d978cd47cb5061272d4997 \ + --hash=sha256:b5a015b322275d3d745b06d5e69cf74ef4b1ce2dae02afbe4826cb186d8527a3 \ + --hash=sha256:b612613f0165f560571c4e372af0ebbb1c4b36067de409922dcea349beb8bb20 \ + --hash=sha256:b637d82a488116da2869afbddccfd93ca14e3c47b404c8ec5a9bad9d4381b08c \ + --hash=sha256:b65c2f3c4449383429507a7e1b372bd759f60a2df8ddc8d6c1cf9010585576b1 \ + --hash=sha256:b6f7c5fabf5b1d9ca79f204664f2c3e2f8218e50aebc43e85e02df0b2d9cc313 \ + --hash=sha256:bd5b047ed8f16b83d0344fef053668712ab9c88e2e46d8612ec41df83c5222e1 \ + --hash=sha256:cbb63b26d33acc3eb61f544c22a0cadbe01682fc064b266bb0e33fa66cea853f \ + --hash=sha256:cd4b0d00523cae1e5e1eaed1d2b85ef342cec000f58d0738e12b064d72a7bbc2 \ + --hash=sha256:cea1969b9bfe230cb3fd66f1c66da5a63a9a917d9cd25a0839524d3d1a88b40e \ + --hash=sha256:d225096687fc3bac0ebe3357e95b2dd8b0a49d191f016db0771d537ccdd6f47e \ + --hash=sha256:d76f8fdcb6936f5e1045a0c9dd721a4bf11112e60d1e243bfa1d39f06a8b3104 \ + --hash=sha256:d8d5674de2b614575f0751671727056af042ac1d61beacb59a298d74282fa492 \ + --hash=sha256:e00bfc6fc0158f156d34f923829e6f62ca00df2e0ea42ba3b0db4089b6d921c2 \ + --hash=sha256:e3ecdb0b248cd0bf43100a8b3cb40f7b45d52ea4be8616edea5dea8fefe90229 \ + --hash=sha256:e80ac66627a01698675ce6e98d90ea9817d1e06644129ec8b0093f66ff1cbeac \ + --hash=sha256:f0b39924698a85bee107184a3c2ee9ae27248144977160534f7d558831db50cf \ + --hash=sha256:f15de48b82a816c72f358e772792801bd3788a156caa76e1806cb0aa8148cd61 \ + --hash=sha256:f265c85432c398d86f26add143423924a4747879b2dce001a3ffe0a5fed30638 \ + --hash=sha256:fde43b9785c7f105aa563b6b5481edabea4ab6be7d9ef14ff4d76225950923e8 \ + --hash=sha256:fe80d05dd85e6ac58d0cd4fa10ddb96252a6f1046ee0fd00cd1d48f0c25921ac \ + --hash=sha256:fedc183bdbc3fdbfbdca26e0e04566d089cbb404712509a4e824608e9304cc77 +frozendict==2.4.7 \ + --hash=sha256:05dd27415f913cd11649009f53d97eb565ce7b76787d7869c4733738c10e8d27 \ + --hash=sha256:0664092614d2b9d0aa404731f33ad5459a54fe8dab9d1fd45aa714fa6de4d0ef \ + --hash=sha256:0ece525da7d0aa3eb56c3e479f30612028d545081c15450d67d771a303ee7d4c \ + --hash=sha256:0ff6f57854cc8aa8b30947ec005f9246d96e795a78b21441614e85d39b708822 \ + --hash=sha256:115a822ecd754574e11205e0880e9d61258d960863d6fd1b90883aa800f6d3b3 \ + --hash=sha256:11d35075f979c96f528d74ccbf89322a7ef8211977dd566bc384985ebce689be \ + --hash=sha256:1662f1b72b4f4a2ffdfdc4981ece275ca11f90244208ac1f1fc2c17fc9c9437a \ + --hash=sha256:176a66094428b9fd66270927b9787e3b8b1c9505ef92723c7b0ef1923dbe3c4a \ + --hash=sha256:176dd384dfe1d0d79449e05f67764c57c6f0f3095378bf00deb33165d5d2df5b \ + --hash=sha256:1c521ad3d747aa475e9040e231f5f1847c04423bae5571c010a9d969e6983c40 \ + --hash=sha256:1df8e22f7d24172c08434b10911f3971434bb5a59b4d1b0078ae33a623625294 \ + --hash=sha256:1e307be0e1f26cbc9593f6bdad5238a1408a50f39f63c9c39eb93c7de5926767 \ + --hash=sha256:1e801d62e35df24be2c6f7f43c114058712efa79a8549c289437754dad0207a3 \ + --hash=sha256:2808bab8e21887a8c106cca5f6f0ab5bda7ee81e159409a10f53d57542ccd99c \ + --hash=sha256:294a7d7d51dd979021a8691b46aedf9bd4a594ce3ed33a4bdf0a712d6929d712 \ + --hash=sha256:2b96f224a5431889f04b2bc99c0e9abe285679464273ead83d7d7f2a15907d35 \ + --hash=sha256:2cf0a665bf2f1ce69d3cd8b6d3574b1d32ae00981a16fa1d255d2da8a2e44b7c \ + --hash=sha256:2e5d2c30f4a3fea83a14b0a5722f21c10de5c755ab5637c70de5eb60886d58cd \ + --hash=sha256:2ebd953c41408acfb8041ff9e6c3519c09988fb7e007df7ab6b56e229029d788 \ + --hash=sha256:313e0e1d8b22b317aa1f7dd48aec8cbb0416ddd625addf7648a69148fcb9ccff \ + --hash=sha256:34233deb8d09e798e874a6ac00b054d2e842164d982ebd43eb91b9f0a6a34876 \ + --hash=sha256:346a53640f15c1640a3503f60ba99df39e4ab174979f10db4304bbb378df5cbd \ + --hash=sha256:3842cfc2d69df5b9978f2e881b7678a282dbdd6846b11b5159f910bc633cbe4f \ + --hash=sha256:39abe54264ae69a0b2e00fabdb5118604f36a5b927d33e7532cd594c5142ebf4 \ + --hash=sha256:3ed9e2f3547a59f4ef5c233614c6faa6221d33004cb615ae1c07ffc551cfe178 \ + --hash=sha256:48ab42b01952bc11543577de9fe5d9ca7c41b35dda36326a07fb47d84b3d5f22 \ + --hash=sha256:4c64d34b802912ee6d107936e970b90750385a1fdfd38d310098b2918ba4cbf2 \ + --hash=sha256:5694417864875ca959932e3b98e2b7d5d27c75177bf510939d0da583712ddf58 \ + --hash=sha256:57134ef5df1dd32229c148c75a7b89245dbdb89966a155d6dfd4bda653e8c7af \ + --hash=sha256:57a754671c5746e11140363aa2f4e7a75c8607de6e85a2bf89dcd1daf51885a7 \ + --hash=sha256:5943c3f683d3f32036f6ca975e920e383d85add1857eee547742de9c1f283716 \ + --hash=sha256:5c1781f28c4bbb177644b3cb6d5cf7da59be374b02d91cdde68d1d5ef32e046b \ + --hash=sha256:6991469a889ee8a108fe5ed1b044447c7b7a07da9067e93c59cbfac8c1d625cf \ + --hash=sha256:6d30dbba6eb1497c695f3108c2c292807e7a237c67a1b9ff92c04e89969d22d1 \ + --hash=sha256:708382875c3cfe91be625dddcba03dee2dfdadbad2c431568a8c7f2f2af0bbee \ + --hash=sha256:70e655c3aa5f893807830f549a7275031a181dbebeaf74c461b51adc755d9335 \ + --hash=sha256:735be62d757e1e7e496ccb6401efe82b473faa653e95eec0826cd7819a29a34c \ + --hash=sha256:739ee81e574f33b46f1e6d9312f3ec2c549bdd574a4ebb6bf106775c9d85ca7b \ + --hash=sha256:7469912c1a04102457871ff675aebe600dbb7e79a6450a166cc8079b88f6ca79 \ + --hash=sha256:75eefdf257a84ea73d553eb80d0abbff0af4c9df62529e4600fd3f96ff17eeb3 \ + --hash=sha256:76bd99f3508cb2ec87976f2e3fe7d92fb373a661cacffb863013d15e4cfaf0eb \ + --hash=sha256:78a55f320ca924545494ce153df02d4349156cd95dc4603c1f0e80c42c889249 \ + --hash=sha256:7ddffe7c0b3be414f88185e212758989c65b497315781290eb029e2c1e1fd64e \ + --hash=sha256:7fd0d0bd3a79e009dddbf5fedfd927ad495c218cd7b13a112d28a37e2079725c \ + --hash=sha256:7fe194f37052a8f45a1a8507e36229e28b79f3d21542ae55ea6a18c6a444f625 \ + --hash=sha256:82d5272d08451bcef6fb6235a0a04cf1816b6b6815cec76be5ace1de17e0c1a4 \ + --hash=sha256:830d181781bb263c9fa430b81f82c867546f5dcb368e73931c8591f533a04afb \ + --hash=sha256:88c6bea948da03087035bb9ca9625305d70e084aa33f11e17048cb7dda4ca293 \ + --hash=sha256:8a06f6c3d3b8d487226fdde93f621e04a54faecc5bf5d9b16497b8f9ead0ac3e \ + --hash=sha256:8dfe2f4840b043436ee5bdd07b0fa5daecedf086e6957e7df050a56ab6db078d \ + --hash=sha256:8ef11dd996208c5a96eab0683f7a17cb4b992948464d2498520efd75a10a2aac \ + --hash=sha256:91a06ee46b3e3ef3b237046b914c0c905eab9fdfeac677e9b51473b482e24c28 \ + --hash=sha256:972af65924ea25cf5b4d9326d549e69a9a4918d8a76a9d3a7cd174d98b237550 \ + --hash=sha256:a10d38fa300f6bef230fae1fdb4bc98706b78c8a3a2f3140fde748469ef3cfe8 \ + --hash=sha256:a1a083e9ee7a1904e545a6307c7db1dd76200077520fcbf7a98d886f81b57dd7 \ + --hash=sha256:a265e95e7087f44b88a6d78a63ea95a2ca0eb0a21ab4f76047f4c164a8beb413 \ + --hash=sha256:a404857e48d85a517bb5b974d740f8c4fccb25d8df98885f3a2a4d950870b845 \ + --hash=sha256:a4d2b27d8156922c9739dd2ff4f3934716e17cfd1cf6fb61aa17af7d378555e9 \ + --hash=sha256:ad0448ed5569f0a9b9b010af9fb5b6d9bdc0b4b877a3ddb188396c4742e62284 \ + --hash=sha256:b1a94e8935c69ae30043b465af496f447950f2c03660aee8657074084faae0b3 \ + --hash=sha256:b22d337c76b765cb7961d4ee47fe29f89e30921eb47bf856b14dc7641f4df3e5 \ + --hash=sha256:b809d1c861436a75b2b015dbfd94f6154fa4e7cb0a70e389df1d5f6246b21d1e \ + --hash=sha256:b960e700dc95faca7dd6919d0dce183ef89bfe01554d323cf5de7331a2e80f83 \ + --hash=sha256:bd37c087a538944652363cfd77fb7abe8100cc1f48afea0b88b38bf0f469c3d2 \ + --hash=sha256:c570649ceccfa5e11ad9351e9009dc484c315a51a56aa02ced07ae97644bb7aa \ + --hash=sha256:c89617a784e1c24a31f5aa4809402f8072a26b64ddbc437897f6391ff69b0ee9 \ + --hash=sha256:c93827e0854393cd904b927ceb529afc17776706f5b9e45c7eaf6a40b3fc7b25 \ + --hash=sha256:ca17ac727ffeeba6c46f5a88e0284a7cb1520fb03127645fcdd7041080adf849 \ + --hash=sha256:cc2085926872a1b26deda4b81b2254d2e5d2cb2c4d7b327abe4c820b7c93f40b \ + --hash=sha256:cc520f3f4af14f456143a534d554175dbc0f0636ffd653e63675cd591862a9d9 \ + --hash=sha256:d10c2ea7c90ba204cd053167ba214d0cdd00f3184c7b8d117a56d7fd2b0c6553 \ + --hash=sha256:d1b4426457757c30ad86b57cdbcc0adaa328399f1ec3d231a0a2ce7447248987 \ + --hash=sha256:d4d7ec24d3bfcfac3baf4dffd7fcea3fa8474b087ce32696232132064aa062cf \ + --hash=sha256:d774df483c12d6cba896eb9a1337bbc5ad3f564eb18cfaaee3e95fb4402f2a86 \ + --hash=sha256:d8930877a2dd40461968d9238d95c754e51b33ce7d2a45500f88ffeed5cb7202 \ + --hash=sha256:dd518f300e5eb6a8827bee380f2e1a31c01dc0af069b13abdecd4e5769bd8a97 \ + --hash=sha256:de1fff2683d8af01299ec01eb21a24b6097ce92015fc1fbefa977cecf076a3fc \ + --hash=sha256:de8d2c98777ba266f5466e211778d4e3bd00635a207c54f6f7511d8613b86dd3 \ + --hash=sha256:e0d450c9d444befe2668bf9386ac2945a2f38152248d58f6b3feea63db59ba08 \ + --hash=sha256:e478fb2a1391a56c8a6e10cc97c4a9002b410ecd1ac28c18d780661762e271bd \ + --hash=sha256:e89492dfcc4c27a718f8b5a4c8df1a2dec6c689718cccd70cb2ceba69ab8c642 \ + --hash=sha256:eab9ef8a9268042e819de03079b984eb0894f05a7b63c4e5319b1cf1ef362ba7 \ + --hash=sha256:ebae8f4a07372acfc3963fc8d68070cdaab70272c3dd836f057ebbe9b7d38643 \ + --hash=sha256:ec846bde66b75d68518c7b24a0a46d09db0aee5a6aefd2209d9901faf6e9df21 \ + --hash=sha256:f42e2c25d3eee4ea3da88466f38ed0dce8c622a1a9d92572e5ee53b7a6bb9ef1 \ + --hash=sha256:f556ea05d9c5f6dae50d57ce6234e4ab1fbf4551dd0d52b4fed6ef537d9f3d3c \ + --hash=sha256:f65d1b90e9ddc791ea82ef91a9ae0ab27ef6c0cfa88fadfa0e5ca5a22f8fa22f \ + --hash=sha256:fc43257a06e6117da6a8a0779243b974cdb9205fed82e32eb669f6746c75d27d \ + --hash=sha256:fd7ba56cf6340c732ecb78787c4e9600c4bd01372af7313ded21037126d33ec6 \ + --hash=sha256:ffd1a9f9babec9119712e76a39397d8aa0d72ef8c4ccad917c6175d7e7f81b74 \ + --hash=sha256:fff8584e3bbdc5c1713cd016fbf4b88babfffd4e5e89b39020f2a208dd24c900 +frozenlist==1.8.0 \ + --hash=sha256:0325024fe97f94c41c08872db482cf8ac4800d80e79222c6b0b7b162d5b13686 \ + --hash=sha256:032efa2674356903cd0261c4317a561a6850f3ac864a63fc1583147fb05a79b0 \ + --hash=sha256:03ae967b4e297f58f8c774c7eabcce57fe3c2434817d4385c50661845a058121 \ + --hash=sha256:06be8f67f39c8b1dc671f5d83aaefd3358ae5cdcf8314552c57e7ed3e6475bdd \ + --hash=sha256:073f8bf8becba60aa931eb3bc420b217bb7d5b8f4750e6f8b3be7f3da85d38b7 \ + --hash=sha256:07cdca25a91a4386d2e76ad992916a85038a9b97561bf7a3fd12d5d9ce31870c \ + --hash=sha256:09474e9831bc2b2199fad6da3c14c7b0fbdd377cce9d3d77131be28906cb7d84 \ + --hash=sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d \ + --hash=sha256:0f96534f8bfebc1a394209427d0f8a63d343c9779cda6fc25e8e121b5fd8555b \ + --hash=sha256:102e6314ca4da683dca92e3b1355490fed5f313b768500084fbe6371fddfdb79 \ + --hash=sha256:11847b53d722050808926e785df837353bd4d75f1d494377e59b23594d834967 \ + --hash=sha256:119fb2a1bd47307e899c2fac7f28e85b9a543864df47aa7ec9d3c1b4545f096f \ + --hash=sha256:13d23a45c4cebade99340c4165bd90eeb4a56c6d8a9d8aa49568cac19a6d0dc4 \ + --hash=sha256:154e55ec0655291b5dd1b8731c637ecdb50975a2ae70c606d100750a540082f7 \ + --hash=sha256:168c0969a329b416119507ba30b9ea13688fafffac1b7822802537569a1cb0ef \ + --hash=sha256:17c883ab0ab67200b5f964d2b9ed6b00971917d5d8a92df149dc2c9779208ee9 \ + --hash=sha256:1a7607e17ad33361677adcd1443edf6f5da0ce5e5377b798fba20fae194825f3 \ + --hash=sha256:1a7fa382a4a223773ed64242dbe1c9c326ec09457e6b8428efb4118c685c3dfd \ + --hash=sha256:1aa77cb5697069af47472e39612976ed05343ff2e84a3dcf15437b232cbfd087 \ + --hash=sha256:1b9290cf81e95e93fdf90548ce9d3c1211cf574b8e3f4b3b7cb0537cf2227068 \ + --hash=sha256:20e63c9493d33ee48536600d1a5c95eefc870cd71e7ab037763d1fbb89cc51e7 \ + --hash=sha256:21900c48ae04d13d416f0e1e0c4d81f7931f73a9dfa0b7a8746fb2fe7dd970ed \ + --hash=sha256:229bf37d2e4acdaf808fd3f06e854a4a7a3661e871b10dc1f8f1896a3b05f18b \ + --hash=sha256:2552f44204b744fba866e573be4c1f9048d6a324dfe14475103fd51613eb1d1f \ + --hash=sha256:27c6e8077956cf73eadd514be8fb04d77fc946a7fe9f7fe167648b0b9085cc25 \ + --hash=sha256:28bd570e8e189d7f7b001966435f9dac6718324b5be2990ac496cf1ea9ddb7fe \ + --hash=sha256:294e487f9ec720bd8ffcebc99d575f7eff3568a08a253d1ee1a0378754b74143 \ + --hash=sha256:29548f9b5b5e3460ce7378144c3010363d8035cea44bc0bf02d57f5a685e084e \ + --hash=sha256:2c5dcbbc55383e5883246d11fd179782a9d07a986c40f49abe89ddf865913930 \ + --hash=sha256:2dc43a022e555de94c3b68a4ef0b11c4f747d12c024a520c7101709a2144fb37 \ + --hash=sha256:2f05983daecab868a31e1da44462873306d3cbfd76d1f0b5b69c473d21dbb128 \ + --hash=sha256:33139dc858c580ea50e7e60a1b0ea003efa1fd42e6ec7fdbad78fff65fad2fd2 \ + --hash=sha256:332db6b2563333c5671fecacd085141b5800cb866be16d5e3eb15a2086476675 \ + --hash=sha256:33f48f51a446114bc5d251fb2954ab0164d5be02ad3382abcbfe07e2531d650f \ + --hash=sha256:34187385b08f866104f0c0617404c8eb08165ab1272e884abc89c112e9c00746 \ + --hash=sha256:342c97bf697ac5480c0a7ec73cd700ecfa5a8a40ac923bd035484616efecc2df \ + --hash=sha256:3462dd9475af2025c31cc61be6652dfa25cbfb56cbbf52f4ccfe029f38decaf8 \ + --hash=sha256:39ecbc32f1390387d2aa4f5a995e465e9e2f79ba3adcac92d68e3e0afae6657c \ + --hash=sha256:3e0761f4d1a44f1d1a47996511752cf3dcec5bbdd9cc2b4fe595caf97754b7a0 \ + --hash=sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad \ + --hash=sha256:3ef2d026f16a2b1866e1d86fc4e1291e1ed8a387b2c333809419a2f8b3a77b82 \ + --hash=sha256:405e8fe955c2280ce66428b3ca55e12b3c4e9c336fb2103a4937e891c69a4a29 \ + --hash=sha256:42145cd2748ca39f32801dad54aeea10039da6f86e303659db90db1c4b614c8c \ + --hash=sha256:4314debad13beb564b708b4a496020e5306c7333fa9a3ab90374169a20ffab30 \ + --hash=sha256:433403ae80709741ce34038da08511d4a77062aa924baf411ef73d1146e74faf \ + --hash=sha256:44389d135b3ff43ba8cc89ff7f51f5a0bb6b63d829c8300f79a2fe4fe61bcc62 \ + --hash=sha256:48e6d3f4ec5c7273dfe83ff27c91083c6c9065af655dc2684d2c200c94308bb5 \ + --hash=sha256:494a5952b1c597ba44e0e78113a7266e656b9794eec897b19ead706bd7074383 \ + --hash=sha256:4970ece02dbc8c3a92fcc5228e36a3e933a01a999f7094ff7c23fbd2beeaa67c \ + --hash=sha256:4e0c11f2cc6717e0a741f84a527c52616140741cd812a50422f83dc31749fb52 \ + --hash=sha256:50066c3997d0091c411a66e710f4e11752251e6d2d73d70d8d5d4c76442a199d \ + --hash=sha256:517279f58009d0b1f2e7c1b130b377a349405da3f7621ed6bfae50b10adf20c1 \ + --hash=sha256:54b2077180eb7f83dd52c40b2750d0a9f175e06a42e3213ce047219de902717a \ + --hash=sha256:5500ef82073f599ac84d888e3a8c1f77ac831183244bfd7f11eaa0289fb30714 \ + --hash=sha256:581ef5194c48035a7de2aefc72ac6539823bb71508189e5de01d60c9dcd5fa65 \ + --hash=sha256:59a6a5876ca59d1b63af8cd5e7ffffb024c3dc1e9cf9301b21a2e76286505c95 \ + --hash=sha256:5a3a935c3a4e89c733303a2d5a7c257ea44af3a56c8202df486b7f5de40f37e1 \ + --hash=sha256:5c1c8e78426e59b3f8005e9b19f6ff46e5845895adbde20ece9218319eca6506 \ + --hash=sha256:5d63a068f978fc69421fb0e6eb91a9603187527c86b7cd3f534a5b77a592b888 \ + --hash=sha256:667c3777ca571e5dbeb76f331562ff98b957431df140b54c85fd4d52eea8d8f6 \ + --hash=sha256:6da155091429aeba16851ecb10a9104a108bcd32f6c1642867eadaee401c1c41 \ + --hash=sha256:6dc4126390929823e2d2d9dc79ab4046ed74680360fc5f38b585c12c66cdf459 \ + --hash=sha256:7398c222d1d405e796970320036b1b563892b65809d9e5261487bb2c7f7b5c6a \ + --hash=sha256:74c51543498289c0c43656701be6b077f4b265868fa7f8a8859c197006efb608 \ + --hash=sha256:776f352e8329135506a1d6bf16ac3f87bc25b28e765949282dcc627af36123aa \ + --hash=sha256:778a11b15673f6f1df23d9586f83c4846c471a8af693a22e066508b77d201ec8 \ + --hash=sha256:78f7b9e5d6f2fdb88cdde9440dc147259b62b9d3b019924def9f6478be254ac1 \ + --hash=sha256:799345ab092bee59f01a915620b5d014698547afd011e691a208637312db9186 \ + --hash=sha256:7bf6cdf8e07c8151fba6fe85735441240ec7f619f935a5205953d58009aef8c6 \ + --hash=sha256:8009897cdef112072f93a0efdce29cd819e717fd2f649ee3016efd3cd885a7ed \ + --hash=sha256:80f85f0a7cc86e7a54c46d99c9e1318ff01f4687c172ede30fd52d19d1da1c8e \ + --hash=sha256:8585e3bb2cdea02fc88ffa245069c36555557ad3609e83be0ec71f54fd4abb52 \ + --hash=sha256:878be833caa6a3821caf85eb39c5ba92d28e85df26d57afb06b35b2efd937231 \ + --hash=sha256:8a76ea0f0b9dfa06f254ee06053d93a600865b3274358ca48a352ce4f0798450 \ + --hash=sha256:8b7b94a067d1c504ee0b16def57ad5738701e4ba10cec90529f13fa03c833496 \ + --hash=sha256:8d92f1a84bb12d9e56f818b3a746f3efba93c1b63c8387a73dde655e1e42282a \ + --hash=sha256:908bd3f6439f2fef9e85031b59fd4f1297af54415fb60e4254a95f75b3cab3f3 \ + --hash=sha256:92db2bf818d5cc8d9c1f1fc56b897662e24ea5adb36ad1f1d82875bd64e03c24 \ + --hash=sha256:940d4a017dbfed9daf46a3b086e1d2167e7012ee297fef9e1c545c4d022f5178 \ + --hash=sha256:957e7c38f250991e48a9a73e6423db1bb9dd14e722a10f6b8bb8e16a0f55f695 \ + --hash=sha256:96153e77a591c8adc2ee805756c61f59fef4cf4073a9275ee86fe8cba41241f7 \ + --hash=sha256:96f423a119f4777a4a056b66ce11527366a8bb92f54e541ade21f2374433f6d4 \ + --hash=sha256:97260ff46b207a82a7567b581ab4190bd4dfa09f4db8a8b49d1a958f6aa4940e \ + --hash=sha256:974b28cf63cc99dfb2188d8d222bc6843656188164848c4f679e63dae4b0708e \ + --hash=sha256:9ff15928d62a0b80bb875655c39bf517938c7d589554cbd2669be42d97c2cb61 \ + --hash=sha256:a6483e309ca809f1efd154b4d37dc6d9f61037d6c6a81c2dc7a15cb22c8c5dca \ + --hash=sha256:a88f062f072d1589b7b46e951698950e7da00442fc1cacbe17e19e025dc327ad \ + --hash=sha256:ac913f8403b36a2c8610bbfd25b8013488533e71e62b4b4adce9c86c8cea905b \ + --hash=sha256:adbeebaebae3526afc3c96fad434367cafbfd1b25d72369a9e5858453b1bb71a \ + --hash=sha256:b2a095d45c5d46e5e79ba1e5b9cb787f541a8dee0433836cea4b96a2c439dcd8 \ + --hash=sha256:b3210649ee28062ea6099cfda39e147fa1bc039583c8ee4481cb7811e2448c51 \ + --hash=sha256:b37f6d31b3dcea7deb5e9696e529a6aa4a898adc33db82da12e4c60a7c4d2011 \ + --hash=sha256:b4dec9482a65c54a5044486847b8a66bf10c9cb4926d42927ec4e8fd5db7fed8 \ + --hash=sha256:b4f3b365f31c6cd4af24545ca0a244a53688cad8834e32f56831c4923b50a103 \ + --hash=sha256:b6db2185db9be0a04fecf2f241c70b63b1a242e2805be291855078f2b404dd6b \ + --hash=sha256:b9be22a69a014bc47e78072d0ecae716f5eb56c15238acca0f43d6eb8e4a5bda \ + --hash=sha256:bac9c42ba2ac65ddc115d930c78d24ab8d4f465fd3fc473cdedfccadb9429806 \ + --hash=sha256:bf0a7e10b077bf5fb9380ad3ae8ce20ef919a6ad93b4552896419ac7e1d8e042 \ + --hash=sha256:c23c3ff005322a6e16f71bf8692fcf4d5a304aaafe1e262c98c6d4adc7be863e \ + --hash=sha256:c4c800524c9cd9bac5166cd6f55285957fcfc907db323e193f2afcd4d9abd69b \ + --hash=sha256:c7366fe1418a6133d5aa824ee53d406550110984de7637d65a178010f759c6ef \ + --hash=sha256:c8d1634419f39ea6f5c427ea2f90ca85126b54b50837f31497f3bf38266e853d \ + --hash=sha256:c9a63152fe95756b85f31186bddf42e4c02c6321207fd6601a1c89ebac4fe567 \ + --hash=sha256:cb89a7f2de3602cfed448095bab3f178399646ab7c61454315089787df07733a \ + --hash=sha256:cba69cb73723c3f329622e34bdbf5ce1f80c21c290ff04256cff1cd3c2036ed2 \ + --hash=sha256:cee686f1f4cadeb2136007ddedd0aaf928ab95216e7691c63e50a8ec066336d0 \ + --hash=sha256:cf253e0e1c3ceb4aaff6df637ce033ff6535fb8c70a764a8f46aafd3d6ab798e \ + --hash=sha256:d1eaff1d00c7751b7c6662e9c5ba6eb2c17a2306ba5e2a37f24ddf3cc953402b \ + --hash=sha256:d3bb933317c52d7ea5004a1c442eef86f426886fba134ef8cf4226ea6ee1821d \ + --hash=sha256:d4d3214a0f8394edfa3e303136d0575eece0745ff2b47bd2cb2e66dd92d4351a \ + --hash=sha256:d6a5df73acd3399d893dafc71663ad22534b5aa4f94e8a2fabfe856c3c1b6a52 \ + --hash=sha256:d8b7138e5cd0647e4523d6685b0eac5d4be9a184ae9634492f25c6eb38c12a47 \ + --hash=sha256:db1e72ede2d0d7ccb213f218df6a078a9c09a7de257c2fe8fcef16d5925230b1 \ + --hash=sha256:e25ac20a2ef37e91c1b39938b591457666a0fa835c7783c3a8f33ea42870db94 \ + --hash=sha256:e2de870d16a7a53901e41b64ffdf26f2fbb8917b3e6ebf398098d72c5b20bd7f \ + --hash=sha256:e4a3408834f65da56c83528fb52ce7911484f0d1eaf7b761fc66001db1646eff \ + --hash=sha256:eaa352d7047a31d87dafcacbabe89df0aa506abb5b1b85a2fb91bc3faa02d822 \ + --hash=sha256:eab8145831a0d56ec9c4139b6c3e594c7a83c2c8be25d5bcf2d86136a532287a \ + --hash=sha256:ec3cc8c5d4084591b4237c0a272cc4f50a5b03396a47d9caaf76f5d7b38a4f11 \ + --hash=sha256:edee74874ce20a373d62dc28b0b18b93f645633c2943fd90ee9d898550770581 \ + --hash=sha256:eefdba20de0d938cec6a89bd4d70f346a03108a19b9df4248d3cf0d88f1b0f51 \ + --hash=sha256:ef2b7b394f208233e471abc541cc6991f907ffd47dc72584acee3147899d6565 \ + --hash=sha256:f21f00a91358803399890ab167098c131ec2ddd5f8f5fd5fe9c9f2c6fcd91e40 \ + --hash=sha256:f4be2e3d8bc8aabd566f8d5b8ba7ecc09249d74ba3c9ed52e54dc23a293f0b92 \ + --hash=sha256:f57fb59d9f385710aa7060e89410aeb5058b99e62f4d16b08b91986b9a2140c2 \ + --hash=sha256:f6292f1de555ffcc675941d65fffffb0a5bcd992905015f85d0592201793e0e5 \ + --hash=sha256:f833670942247a14eafbb675458b4e61c82e002a148f49e68257b79296e865c4 \ + --hash=sha256:fa47e444b8ba08fffd1c18e8cdb9a75db1b6a27f17507522834ad13ed5922b93 \ + --hash=sha256:fb30f9626572a76dfe4293c7194a09fb1fe93ba94c7d4f720dfae3b646b45027 \ + --hash=sha256:fe3c58d2f5db5fbd18c2987cba06d51b0529f52bc3a6cdc33d3f4eab725104bd +fsspec==2026.9.0 \ + --hash=sha256:0f08147951c8cb31d844c3547d631053b127863b60be04cf06e121333ee0e2fe \ + --hash=sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f +h11==0.16.0 \ + --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \ + --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86 +hf-xet==1.8.0 \ + --hash=sha256:07a06d7481702616726c2d8578cfb00052a5b3f21beed6a674592bc837a10330 \ + --hash=sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e \ + --hash=sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01 \ + --hash=sha256:23c262e9f5e137b18dadbce60becfeea84156b0d43119c320bffe260d32cd2fa \ + --hash=sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d \ + --hash=sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4 \ + --hash=sha256:3ecfe2934448cca55a4c42732b60f985266aecb241905945219b3d388aceb7ba \ + --hash=sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b \ + --hash=sha256:56735c2d4f416d7473fc986586b26a8756e067832ca4b7fdaad32a0d6f2ce740 \ + --hash=sha256:62b056aedb89ac809f78940baf465fe553b70c8b25ee56890fbab3039fffec1b \ + --hash=sha256:7edeb21c5d381903ee5f4857fc746fa7b52a4b374035e8811ecfb67ee27add0c \ + --hash=sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f \ + --hash=sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec \ + --hash=sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c \ + --hash=sha256:c74e3751cbcdae9222c5170e8d788e83201a03dc5e5f4308a20f17a5b6023b56 \ + --hash=sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e \ + --hash=sha256:f42940869572dc2b05dfe06f4cc398c6291503e086ddc4eddfb7a6ab9409ad01 +httpcore==1.0.9 \ + --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55 \ + --hash=sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8 +httpx==0.28.1 \ + --hash=sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc \ + --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad +huggingface-hub==1.33.0 \ + --hash=sha256:04e434b06e100eddbce9a6e817d72693a7884b10a79bd67ab48080d5c07eb899 \ + --hash=sha256:367be21a201db9523eddf8aeac7048f2602c1b308691c97640d5e72ed188007e +idna==3.20 \ + --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \ + --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c +importlib-metadata==10.2.0 \ + --hash=sha256:9413a2029fd9ca5669d27f1386071bbfe3c7ebca0545692ec975088241fe1d79 \ + --hash=sha256:c7a4bf1c7479601f6b8e437cfc14f4f77028ba62a8f34ae95cd93d9774dfba51 +jinja2==3.1.6 \ + --hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \ + --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67 +kiwisolver==1.4.9 \ + --hash=sha256:0749fd8f4218ad2e851e11cc4dc05c7cbc0cbc4267bdfdb31782e65aace4ee9c \ + --hash=sha256:0763515d4df10edf6d06a3c19734e2566368980d21ebec439f33f9eb936c07b7 \ + --hash=sha256:0856e241c2d3df4efef7c04a1e46b1936b6120c9bcf36dd216e3acd84bc4fb21 \ + --hash=sha256:0a590506f303f512dff6b7f75fd2fd18e16943efee932008fe7140e5fa91d80e \ + --hash=sha256:0ab74e19f6a2b027ea4f845a78827969af45ce790e6cb3e1ebab71bdf9f215ff \ + --hash=sha256:0ae37737256ba2de764ddc12aed4956460277f00c4996d51a197e72f62f5eec7 \ + --hash=sha256:0e4e2bf29574a6a7b7f6cb5fa69293b9f96c928949ac4a53ba3f525dffb87f9c \ + --hash=sha256:15163165efc2f627eb9687ea5f3a28137217d217ac4024893d753f46bce9de26 \ + --hash=sha256:17680d737d5335b552994a2008fab4c851bcd7de33094a82067ef3a576ff02fa \ + --hash=sha256:1a12cf6398e8a0a001a059747a1cbf24705e18fe413bc22de7b3d15c67cffe3f \ + --hash=sha256:1b11d6a633e4ed84fc0ddafd4ebfd8ea49b3f25082c04ad12b8315c11d504dc1 \ + --hash=sha256:1fa333e8b2ce4d9660f2cda9c0e1b6bafcfb2457a9d259faa82289e73ec24891 \ + --hash=sha256:2327a4a30d3ee07d2fbe2e7933e8a37c591663b96ce42a00bc67461a87d7df77 \ + --hash=sha256:2405a7d98604b87f3fc28b1716783534b1b4b8510d8142adca34ee0bc3c87543 \ + --hash=sha256:2489e4e5d7ef9a1c300a5e0196e43d9c739f066ef23270607d45aba368b91f2d \ + --hash=sha256:24c175051354f4a28c5d6a31c93906dc653e2bf234e8a4bbfb964892078898ce \ + --hash=sha256:2635d352d67458b66fd0667c14cb1d4145e9560d503219034a18a87e971ce4f3 \ + --hash=sha256:2c1a4f57df73965f3f14df20b80ee29e6a7930a57d2d9e8491a25f676e197c60 \ + --hash=sha256:2c93f00dcba2eea70af2be5f11a830a742fe6b579a1d4e00f47760ef13be247a \ + --hash=sha256:39a219e1c81ae3b103643d2aedb90f1ef22650deb266ff12a19e7773f3e5f089 \ + --hash=sha256:3b3115b2581ea35bb6d1f24a4c90af37e5d9b49dcff267eeed14c3893c5b86ab \ + --hash=sha256:40092754720b174e6ccf9e845d0d8c7d8e12c3d71e7fc35f55f3813e96376f78 \ + --hash=sha256:412f287c55a6f54b0650bd9b6dce5aceddb95864a1a90c87af16979d37c89771 \ + --hash=sha256:464415881e4801295659462c49461a24fb107c140de781d55518c4b80cb6790f \ + --hash=sha256:497d05f29a1300d14e02e6441cf0f5ee81c1ff5a304b0d9fb77423974684e08b \ + --hash=sha256:4a2899935e724dd1074cb568ce7ac0dce28b2cd6ab539c8e001a8578eb106d14 \ + --hash=sha256:4a48a2ce79d65d363597ef7b567ce3d14d68783d2b2263d98db3d9477805ba32 \ + --hash=sha256:4d1d9e582ad4d63062d34077a9a1e9f3c34088a2ec5135b1f7190c07cf366527 \ + --hash=sha256:52a15b0f35dad39862d376df10c5230155243a2c1a436e39eb55623ccbd68185 \ + --hash=sha256:540c7c72324d864406a009d72f5d6856f49693db95d1fbb46cf86febef873634 \ + --hash=sha256:5656aa670507437af0207645273ccdfee4f14bacd7f7c67a4306d0dcaeaf6eed \ + --hash=sha256:5a0f2724dfd4e3b3ac5a82436a8e6fd16baa7d507117e4279b660fe8ca38a3a1 \ + --hash=sha256:60c439763a969a6af93b4881db0eed8fadf93ee98e18cbc35bc8da868d0c4f0c \ + --hash=sha256:61874cdb0a36016354853593cffc38e56fc9ca5aa97d2c05d3dcf6922cd55a11 \ + --hash=sha256:67bb8b474b4181770f926f7b7d2f8c0248cbcb78b660fdd41a47054b28d2a752 \ + --hash=sha256:720e05574713db64c356e86732c0f3c5252818d05f9df320f0ad8380641acea5 \ + --hash=sha256:72d0eb9fba308b8311685c2268cf7d0a0639a6cd027d8128659f72bdd8a024b4 \ + --hash=sha256:767c23ad1c58c9e827b649a9ab7809fd5fd9db266a9cf02b0e926ddc2c680d58 \ + --hash=sha256:77937e5e2a38a7b48eef0585114fe7930346993a88060d0bf886086d2aa49ef5 \ + --hash=sha256:7a08b491ec91b1d5053ac177afe5290adacf1f0f6307d771ccac5de30592d198 \ + --hash=sha256:7b4da0d01ac866a57dd61ac258c5607b4cd677f63abaec7b148354d2b2cdd536 \ + --hash=sha256:7cf974dd4e35fa315563ac99d6287a1024e4dc2077b8a7d7cd3d2fb65d283134 \ + --hash=sha256:84fd60810829c27ae375114cd379da1fa65e6918e1da405f356a775d49a62bcf \ + --hash=sha256:858e4c22fb075920b96a291928cb7dea5644e94c0ee4fcd5af7e865655e4ccf2 \ + --hash=sha256:85b5352f94e490c028926ea567fc569c52ec79ce131dadb968d3853e809518c2 \ + --hash=sha256:85bd218b5ecfbee8c8a82e121802dcb519a86044c9c3b2e4aef02fa05c6da370 \ + --hash=sha256:8a1f570ce4d62d718dce3f179ee78dac3b545ac16c0c04bb363b7607a949c0d1 \ + --hash=sha256:8fdca1def57a2e88ef339de1737a1449d6dbf5fab184c54a1fca01d541317154 \ + --hash=sha256:90f47e70293fc3688b71271100a1a5453aa9944a81d27ff779c108372cf5567b \ + --hash=sha256:92a2f997387a1b79a75e7803aa7ded2cfbe2823852ccf1ba3bcf613b62ae3197 \ + --hash=sha256:9928fe1eb816d11ae170885a74d074f57af3a0d65777ca47e9aeb854a1fba386 \ + --hash=sha256:9af39d6551f97d31a4deebeac6f45b156f9755ddc59c07b402c148f5dbb6482a \ + --hash=sha256:9cf554f21be770f5111a1690d42313e140355e687e05cf82cb23d0a721a64a48 \ + --hash=sha256:a30fd6fdef1430fd9e1ba7b3398b5ee4e2887783917a687d86ba69985fb08748 \ + --hash=sha256:a31d512c812daea6d8b3be3b2bfcbeb091dbb09177706569bcfc6240dcf8b41c \ + --hash=sha256:a5d0432ccf1c7ab14f9949eec60c5d1f924f17c037e9f8b33352fa05799359b8 \ + --hash=sha256:a60ea74330b91bd22a29638940d115df9dc00af5035a9a2a6ad9399ffb4ceca5 \ + --hash=sha256:ac5a486ac389dddcc5bef4f365b6ae3ffff2c433324fb38dd35e3fab7c957999 \ + --hash=sha256:aedff62918805fb62d43a4aa2ecd4482c380dc76cd31bd7c8878588a61bd0369 \ + --hash=sha256:b34e51affded8faee0dfdb705416153819d8ea9250bbbf7ea1b249bdeb5f1122 \ + --hash=sha256:b4b4d74bda2b8ebf4da5bd42af11d02d04428b2c32846e4c2c93219df8a7987b \ + --hash=sha256:b67e6efbf68e077dd71d1a6b37e43e1a99d0bff1a3d51867d45ee8908b931098 \ + --hash=sha256:b78efa4c6e804ecdf727e580dbb9cba85624d2e1c6b5cb059c66290063bd99a9 \ + --hash=sha256:bb4ae2b57fc1d8cbd1cf7b1d9913803681ffa903e7488012be5b76dedf49297f \ + --hash=sha256:bdd1a81a1860476eb41ac4bc1e07b3f07259e6d55bbf739b79c8aaedcf512799 \ + --hash=sha256:bdee92c56a71d2b24c33a7d4c2856bd6419d017e08caa7802d2963870e315028 \ + --hash=sha256:be6a04e6c79819c9a8c2373317d19a96048e5a3f90bec587787e86a1153883c2 \ + --hash=sha256:bfc08add558155345129c7803b3671cf195e6a56e7a12f3dde7c57d9b417f525 \ + --hash=sha256:c3b22c26c6fd6811b0ae8363b95ca8ce4ea3c202d3d0975b2914310ceb1bcc4d \ + --hash=sha256:c9e7cdf45d594ee04d5be1b24dd9d49f3d1590959b2271fb30b5ca2b262c00fb \ + --hash=sha256:cb27e7b78d716c591e88e0a09a2139c6577865d7f2e152488c2cc6257f460872 \ + --hash=sha256:cc9617b46837c6468197b5945e196ee9ca43057bb7d9d1ae688101e4e1dddf64 \ + --hash=sha256:ccd09f20ccdbbd341b21a67ab50a119b64a403b09288c27481575105283c1586 \ + --hash=sha256:ce6a3a4e106cf35c2d9c4fa17c05ce0b180db622736845d4315519397a77beaf \ + --hash=sha256:d0005b053977e7b43388ddec89fa567f43d4f6d5c2c0affe57de5ebf290dc552 \ + --hash=sha256:d4188e73af84ca82468f09cadc5ac4db578109e52acb4518d8154698d3a87ca2 \ + --hash=sha256:d4efec7bcf21671db6a3294ff301d2fc861c31faa3c8740d1a94689234d1b415 \ + --hash=sha256:d75aa530ccfaa593da12834b86a0724f58bff12706659baa9227c2ccaa06264c \ + --hash=sha256:d84cd4061ae292d8ac367b2c3fa3aad11cb8625a95d135fe93f286f914f3f5a6 \ + --hash=sha256:d8aacd3d4b33b772542b2e01beb50187536967b514b00003bdda7589722d2a64 \ + --hash=sha256:d8fc5c867c22b828001b6a38d2eaeb88160bf5783c6cb4a5e440efc981ce286d \ + --hash=sha256:d976bbb382b202f71c67f77b0ac11244021cfa3f7dfd9e562eefcea2df711548 \ + --hash=sha256:dba5ee5d3981160c28d5490f0d1b7ed730c22470ff7f6cc26cfcfaacb9896a07 \ + --hash=sha256:dc1ae486f9abcef254b5618dfb4113dd49f94c68e3e027d03cf0143f3f772b61 \ + --hash=sha256:dd0a578400839256df88c16abddf9ba14813ec5f21362e1fe65022e00c883d4d \ + --hash=sha256:deed0c7258ceb4c44ad5ec7d9918f9f14fd05b2be86378d86cf50e63d1e7b771 \ + --hash=sha256:e09c2279a4d01f099f52d5c4b3d9e208e91edcbd1a175c9662a8b16e000fece9 \ + --hash=sha256:e2ea9f7ab7fbf18fffb1b5434ce7c69a07582f7acc7717720f1d69f3e806f90c \ + --hash=sha256:e6b93f13371d341afee3be9f7c5964e3fe61d5fa30f6a30eb49856935dfe4fc3 \ + --hash=sha256:eb14a5da6dc7642b0f3a18f13654847cd8b7a2550e2645a5bda677862b03ba16 \ + --hash=sha256:ed0fecd28cc62c54b262e3736f8bb2512d8dcfdc2bcf08be5f47f96bf405b145 \ + --hash=sha256:ede8c6d533bc6601a47ad4046080d36b8fc99f81e6f1c17b0ac3c2dc91ac7611 \ + --hash=sha256:efb3a45b35622bb6c16dbfab491a8f5a391fe0e9d45ef32f4df85658232ca0e2 \ + --hash=sha256:f117e1a089d9411663a3207ba874f31be9ac8eaa5b533787024dc07aeb74f464 \ + --hash=sha256:f2ba92255faa7309d06fe44c3a4a97efe1c8d640c2a79a5ef728b685762a6fd2 \ + --hash=sha256:f6008a4919fdbc0b0097089f67a1eb55d950ed7e90ce2cc3e640abadd2757a04 \ + --hash=sha256:f68208a520c3d86ea51acf688a3e3002615a7f0238002cccc17affecc86a8a54 \ + --hash=sha256:f68e4f3eeca8fb22cc3d731f9715a13b652795ef657a13df1ad0c7dc0e9731df \ + --hash=sha256:fb3b8132019ea572f4611d770991000d7f58127560c4889729248eb5852a102f \ + --hash=sha256:fb940820c63a9590d31d88b815e7a3aa5915cad3ce735ab45f0c730b39547de1 \ + --hash=sha256:fc1795ac5cd0510207482c3d1d3ed781143383b8cfd36f5c645f3897ce066220 +lazy-importer==0.1.0 \ + --hash=sha256:b2e296716ce015c0cd80e57b940e52727c5b934b34b8656d5ce06bdd0ee5fbdd \ + --hash=sha256:bd93fab7bef18e842eea02b839410954d37889140dc64ca4d9680aec6880c739 +lightning==2.6.6 \ + --hash=sha256:1c6329e241f8a85f29fedead89c1ee138b36caa08de60c260c6a7eaee81c8295 \ + --hash=sha256:2bcbd6ee840071cd076c7dc9953d7ac1040df92f1c5fa76583aae644f037ab85 +lightning-utilities==0.15.2 \ + --hash=sha256:ad3ab1703775044bbf880dbf7ddaaac899396c96315f3aa1779cec9d618a9841 \ + --hash=sha256:cdf12f530214a63dacefd713f180d1ecf5d165338101617b4742e8f22c032e24 +loguru==0.7.3 \ + --hash=sha256:19480589e77d47b8d85b2c827ad95d49bf31b0dcde16593892eb51dd18706eb6 \ + --hash=sha256:31a33c10c8e1e10422bfd431aeb5d351c7cf7fa671e3c4df004162264b28220c +lycoris-lora==3.4.0 \ + --hash=sha256:88ce950017206b9932209d8f17c472d65e117115dbe693da94e3307061631379 +markdown-it-py==4.3.0 \ + --hash=sha256:7aa1511a46c39138de78d9eba92ce47e63124d8003fc98b3a351909e04239efa \ + --hash=sha256:91a58fa5b72c71a40cf7177250fd767480d7a2bb3ac426ccfb76fb90305fdaaa +markupsafe==3.0.3 \ + --hash=sha256:0303439a41979d9e74d18ff5e2dd8c43ed6c6001fd40e5bf2e43f7bd9bbc523f \ + --hash=sha256:068f375c472b3e7acbe2d5318dea141359e6900156b5b2ba06a30b169086b91a \ + --hash=sha256:0bf2a864d67e76e5c9a34dc26ec616a66b9888e25e7b9460e1c76d3293bd9dbf \ + --hash=sha256:0db14f5dafddbb6d9208827849fad01f1a2609380add406671a26386cdf15a19 \ + --hash=sha256:0eb9ff8191e8498cca014656ae6b8d61f39da5f95b488805da4bb029cccbfbaf \ + --hash=sha256:0f4b68347f8c5eab4a13419215bdfd7f8c9b19f2b25520968adfad23eb0ce60c \ + --hash=sha256:1085e7fbddd3be5f89cc898938f42c0b3c711fdcb37d75221de2666af647c175 \ + --hash=sha256:116bb52f642a37c115f517494ea5feb03889e04df47eeff5b130b1808ce7c219 \ + --hash=sha256:12c63dfb4a98206f045aa9563db46507995f7ef6d83b2f68eda65c307c6829eb \ + --hash=sha256:133a43e73a802c5562be9bbcd03d090aa5a1fe899db609c29e8c8d815c5f6de6 \ + --hash=sha256:1353ef0c1b138e1907ae78e2f6c63ff67501122006b0f9abad68fda5f4ffc6ab \ + --hash=sha256:15d939a21d546304880945ca1ecb8a039db6b4dc49b2c5a400387cdae6a62e26 \ + --hash=sha256:177b5253b2834fe3678cb4a5f0059808258584c559193998be2601324fdeafb1 \ + --hash=sha256:1872df69a4de6aead3491198eaf13810b565bdbeec3ae2dc8780f14458ec73ce \ + --hash=sha256:1b4b79e8ebf6b55351f0d91fe80f893b4743f104bff22e90697db1590e47a218 \ + --hash=sha256:1b52b4fb9df4eb9ae465f8d0c228a00624de2334f216f178a995ccdcf82c4634 \ + --hash=sha256:1ba88449deb3de88bd40044603fafffb7bc2b055d626a330323a9ed736661695 \ + --hash=sha256:1cc7ea17a6824959616c525620e387f6dd30fec8cb44f649e31712db02123dad \ + --hash=sha256:218551f6df4868a8d527e3062d0fb968682fe92054e89978594c28e642c43a73 \ + --hash=sha256:26a5784ded40c9e318cfc2bdb30fe164bdb8665ded9cd64d500a34fb42067b1c \ + --hash=sha256:2713baf880df847f2bece4230d4d094280f4e67b1e813eec43b4c0e144a34ffe \ + --hash=sha256:2a15a08b17dd94c53a1da0438822d70ebcd13f8c3a95abe3a9ef9f11a94830aa \ + --hash=sha256:2f981d352f04553a7171b8e44369f2af4055f888dfb147d55e42d29e29e74559 \ + --hash=sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa \ + --hash=sha256:3524b778fe5cfb3452a09d31e7b5adefeea8c5be1d43c4f810ba09f2ceb29d37 \ + --hash=sha256:3537e01efc9d4dccdf77221fb1cb3b8e1a38d5428920e0657ce299b20324d758 \ + --hash=sha256:35add3b638a5d900e807944a078b51922212fb3dedb01633a8defc4b01a3c85f \ + --hash=sha256:38664109c14ffc9e7437e86b4dceb442b0096dfe3541d7864d9cbe1da4cf36c8 \ + --hash=sha256:3a7e8ae81ae39e62a41ec302f972ba6ae23a5c5396c8e60113e9066ef893da0d \ + --hash=sha256:3b562dd9e9ea93f13d53989d23a7e775fdfd1066c33494ff43f5418bc8c58a5c \ + --hash=sha256:457a69a9577064c05a97c41f4e65148652db078a3a509039e64d3467b9e7ef97 \ + --hash=sha256:4bd4cd07944443f5a265608cc6aab442e4f74dff8088b0dfc8238647b8f6ae9a \ + --hash=sha256:4e885a3d1efa2eadc93c894a21770e4bc67899e3543680313b09f139e149ab19 \ + --hash=sha256:4faffd047e07c38848ce017e8725090413cd80cbc23d86e55c587bf979e579c9 \ + --hash=sha256:509fa21c6deb7a7a273d629cf5ec029bc209d1a51178615ddf718f5918992ab9 \ + --hash=sha256:5678211cb9333a6468fb8d8be0305520aa073f50d17f089b5b4b477ea6e67fdc \ + --hash=sha256:591ae9f2a647529ca990bc681daebdd52c8791ff06c2bfa05b65163e28102ef2 \ + --hash=sha256:5a7d5dc5140555cf21a6fefbdbf8723f06fcd2f63ef108f2854de715e4422cb4 \ + --hash=sha256:69c0b73548bc525c8cb9a251cddf1931d1db4d2258e9599c28c07ef3580ef354 \ + --hash=sha256:6b5420a1d9450023228968e7e6a9ce57f65d148ab56d2313fcd589eee96a7a50 \ + --hash=sha256:722695808f4b6457b320fdc131280796bdceb04ab50fe1795cd540799ebe1698 \ + --hash=sha256:729586769a26dbceff69f7a7dbbf59ab6572b99d94576a5592625d5b411576b9 \ + --hash=sha256:77f0643abe7495da77fb436f50f8dab76dbc6e5fd25d39589a0f1fe6548bfa2b \ + --hash=sha256:795e7751525cae078558e679d646ae45574b47ed6e7771863fcc079a6171a0fc \ + --hash=sha256:7be7b61bb172e1ed687f1754f8e7484f1c8019780f6f6b0786e76bb01c2ae115 \ + --hash=sha256:7c3fb7d25180895632e5d3148dbdc29ea38ccb7fd210aa27acbd1201a1902c6e \ + --hash=sha256:7e68f88e5b8799aa49c85cd116c932a1ac15caaa3f5db09087854d218359e485 \ + --hash=sha256:83891d0e9fb81a825d9a6d61e3f07550ca70a076484292a70fde82c4b807286f \ + --hash=sha256:8485f406a96febb5140bfeca44a73e3ce5116b2501ac54fe953e488fb1d03b12 \ + --hash=sha256:8709b08f4a89aa7586de0aadc8da56180242ee0ada3999749b183aa23df95025 \ + --hash=sha256:8f71bc33915be5186016f675cd83a1e08523649b0e33efdb898db577ef5bb009 \ + --hash=sha256:915c04ba3851909ce68ccc2b8e2cd691618c4dc4c4232fb7982bca3f41fd8c3d \ + --hash=sha256:949b8d66bc381ee8b007cd945914c721d9aba8e27f71959d750a46f7c282b20b \ + --hash=sha256:94c6f0bb423f739146aec64595853541634bde58b2135f27f61c1ffd1cd4d16a \ + --hash=sha256:9a1abfdc021a164803f4d485104931fb8f8c1efd55bc6b748d2f5774e78b62c5 \ + --hash=sha256:9b79b7a16f7fedff2495d684f2b59b0457c3b493778c9eed31111be64d58279f \ + --hash=sha256:a320721ab5a1aba0a233739394eb907f8c8da5c98c9181d1161e77a0c8e36f2d \ + --hash=sha256:a4afe79fb3de0b7097d81da19090f4df4f8d3a2b3adaa8764138aac2e44f3af1 \ + --hash=sha256:ad2cf8aa28b8c020ab2fc8287b0f823d0a7d8630784c31e9ee5edea20f406287 \ + --hash=sha256:b8512a91625c9b3da6f127803b166b629725e68af71f8184ae7e7d54686a56d6 \ + --hash=sha256:bc51efed119bc9cfdf792cdeaa4d67e8f6fcccab66ed4bfdd6bde3e59bfcbb2f \ + --hash=sha256:bdc919ead48f234740ad807933cdf545180bfbe9342c2bb451556db2ed958581 \ + --hash=sha256:bdd37121970bfd8be76c5fb069c7751683bdf373db1ed6c010162b2a130248ed \ + --hash=sha256:be8813b57049a7dc738189df53d69395eba14fb99345e0a5994914a3864c8a4b \ + --hash=sha256:c0c0b3ade1c0b13b936d7970b1d37a57acde9199dc2aecc4c336773e1d86049c \ + --hash=sha256:c47a551199eb8eb2121d4f0f15ae0f923d31350ab9280078d1e5f12b249e0026 \ + --hash=sha256:c4ffb7ebf07cfe8931028e3e4c85f0357459a3f9f9490886198848f4fa002ec8 \ + --hash=sha256:ccfcd093f13f0f0b7fdd0f198b90053bf7b2f02a3927a30e63f3ccc9df56b676 \ + --hash=sha256:d2ee202e79d8ed691ceebae8e0486bd9a2cd4794cec4824e1c99b6f5009502f6 \ + --hash=sha256:d53197da72cc091b024dd97249dfc7794d6a56530370992a5e1a08983ad9230e \ + --hash=sha256:d6dd0be5b5b189d31db7cda48b91d7e0a9795f31430b7f271219ab30f1d3ac9d \ + --hash=sha256:d88b440e37a16e651bda4c7c2b930eb586fd15ca7406cb39e211fcff3bf3017d \ + --hash=sha256:de8a88e63464af587c950061a5e6a67d3632e36df62b986892331d4620a35c01 \ + --hash=sha256:df2449253ef108a379b8b5d6b43f4b1a8e81a061d6537becd5582fba5f9196d7 \ + --hash=sha256:e1c1493fb6e50ab01d20a22826e57520f1284df32f2d8601fdd90b6304601419 \ + --hash=sha256:e1cf1972137e83c5d4c136c43ced9ac51d0e124706ee1c8aa8532c1287fa8795 \ + --hash=sha256:e2103a929dfa2fcaf9bb4e7c091983a49c9ac3b19c9061b6d5427dd7d14d81a1 \ + --hash=sha256:e56b7d45a839a697b5eb268c82a71bd8c7f6c94d6fd50c3d577fa39a9f1409f5 \ + --hash=sha256:e8afc3f2ccfa24215f8cb28dcf43f0113ac3c37c2f0f0806d8c70e4228c5cf4d \ + --hash=sha256:e8fc20152abba6b83724d7ff268c249fa196d8259ff481f3b1476383f8f24e42 \ + --hash=sha256:eaa9599de571d72e2daf60164784109f19978b327a3910d3e9de8c97b5b70cfe \ + --hash=sha256:ec15a59cf5af7be74194f7ab02d0f59a62bdcf1a537677ce67a2537c9b87fcda \ + --hash=sha256:f190daf01f13c72eac4efd5c430a8de82489d9cff23c364c3ea822545032993e \ + --hash=sha256:f34c41761022dd093b4b6896d4810782ffbabe30f2d443ff5f083e0cbbb8c737 \ + --hash=sha256:f3e98bb3798ead92273dc0e5fd0f31ade220f59a266ffd8a4f6065e0a3ce0523 \ + --hash=sha256:f42d0984e947b8adf7dd6dde396e720934d12c506ce84eea8476409563607591 \ + --hash=sha256:f71a396b3bf33ecaa1626c255855702aca4d3d9fea5e051b41ac59a9c1c41edc \ + --hash=sha256:f9e130248f4462aaa8e2552d547f36ddadbeaa573879158d721bbd33dfe4743a \ + --hash=sha256:fed51ac40f757d41b7c48425901843666a6677e3e8eb0abcff09e4ba6e664f50 +matplotlib==3.10.8 \ + --hash=sha256:00270d217d6b20d14b584c521f810d60c5c78406dc289859776550df837dcda7 \ + --hash=sha256:0a33deb84c15ede243aead39f77e990469fff93ad1521163305095b77b72ce4a \ + --hash=sha256:113bb52413ea508ce954a02c10ffd0d565f9c3bc7f2eddc27dfe1731e71c7b5f \ + --hash=sha256:12d90df9183093fcd479f4172ac26b322b1248b15729cb57f42f71f24c7e37a3 \ + --hash=sha256:15d30132718972c2c074cd14638c7f4592bd98719e2308bccea40e0538bc0cb5 \ + --hash=sha256:18821ace09c763ec93aef5eeff087ee493a24051936d7b9ebcad9662f66501f9 \ + --hash=sha256:1ae029229a57cd1e8fe542485f27e7ca7b23aa9e8944ddb4985d0bc444f1eca2 \ + --hash=sha256:2299372c19d56bcd35cf05a2738308758d32b9eaed2371898d8f5bd33f084aa3 \ + --hash=sha256:238b7ce5717600615c895050239ec955d91f321c209dd110db988500558e70d6 \ + --hash=sha256:24d50994d8c5816ddc35411e50a86ab05f575e2530c02752e02538122613371f \ + --hash=sha256:25d380fe8b1dc32cf8f0b1b448470a77afb195438bafdf1d858bfb876f3edf7b \ + --hash=sha256:2c1998e92cd5999e295a731bcb2911c75f597d937341f3030cc24ef2733d78a8 \ + --hash=sha256:2cf5bd12cecf46908f286d7838b2abc6c91cda506c0445b8223a7c19a00df008 \ + --hash=sha256:32f8dce744be5569bebe789e46727946041199030db8aeb2954d26013a0eb26b \ + --hash=sha256:37b3c1cc42aa184b3f738cfa18c1c1d72fd496d85467a6cf7b807936d39aa656 \ + --hash=sha256:3a48a78d2786784cc2413e57397981fb45c79e968d99656706018d6e62e57958 \ + --hash=sha256:3ab4aabc72de4ff77b3ec33a6d78a68227bf1123465887f9905ba79184a1cc04 \ + --hash=sha256:3c624e43ed56313651bc18a47f838b60d7b8032ed348911c54906b130b20071b \ + --hash=sha256:3f2e409836d7f5ac2f1c013110a4d50b9f7edc26328c108915f9075d7d7a91b6 \ + --hash=sha256:3f5c3e4da343bba819f0234186b9004faba952cc420fbc522dc4e103c1985908 \ + --hash=sha256:41703cc95688f2516b480f7f339d8851a6035f18e100ee6a32bc0b8536a12a9c \ + --hash=sha256:495672de149445ec1b772ff2c9ede9b769e3cb4f0d0aa7fa730d7f59e2d4e1c1 \ + --hash=sha256:4cf267add95b1c88300d96ca837833d4112756045364f5c734a2276038dae27d \ + --hash=sha256:56271f3dac49a88d7fca5060f004d9d22b865f743a12a23b1e937a0be4818ee1 \ + --hash=sha256:595ba4d8fe983b88f0eec8c26a241e16d6376fe1979086232f481f8f3f67494c \ + --hash=sha256:5f62550b9a30afde8c1c3ae450e5eb547d579dd69b25c2fc7a1c67f934c1717a \ + --hash=sha256:646d95230efb9ca614a7a594d4fcacde0ac61d25e37dd51710b36477594963ce \ + --hash=sha256:64fcc24778ca0404ce0cb7b6b77ae1f4c7231cdd60e6778f999ee05cbd581b9a \ + --hash=sha256:6be43b667360fef5c754dda5d25a32e6307a03c204f3c0fc5468b78fa87b4160 \ + --hash=sha256:6da7c2ce169267d0d066adcf63758f0604aa6c3eebf67458930f9d9b79ad1db1 \ + --hash=sha256:83d282364ea9f3e52363da262ce32a09dfe241e4080dcedda3c0db059d3c1f11 \ + --hash=sha256:9153c3292705be9f9c64498a8872118540c3f4123d1a1c840172edf262c8be4a \ + --hash=sha256:99eefd13c0dc3b3c1b4d561c1169e65fe47aab7b8158754d7c084088e2329466 \ + --hash=sha256:a0a7f52498f72f13d4a25ea70f35f4cb60642b466cbb0a9be951b5bc3f45a486 \ + --hash=sha256:a2b336e2d91a3d7006864e0990c83b216fcdca64b5a6484912902cef87313d78 \ + --hash=sha256:a48f2b74020919552ea25d222d5cc6af9ca3f4eb43a93e14d068457f545c2a17 \ + --hash=sha256:ad3d9833a64cf48cc4300f2b406c3d0f4f4724a91c0bd5640678a6ba7c102077 \ + --hash=sha256:b44d07310e404ba95f8c25aa5536f154c0a8ec473303535949e52eb71d0a1565 \ + --hash=sha256:b53285e65d4fa4c86399979e956235deb900be5baa7fc1218ea67fbfaeaadd6f \ + --hash=sha256:b5a2b97dbdc7d4f353ebf343744f1d1f1cca8aa8bfddb4262fcf4306c3761d50 \ + --hash=sha256:b9a5ca4ac220a0cdd1ba6bcba3608547117d30468fefce49bb26f55c1a3d5c58 \ + --hash=sha256:bab485bcf8b1c7d2060b4fcb6fc368a9e6f4cd754c9c2fea281f4be21df394a2 \ + --hash=sha256:c108a1d6fa78a50646029cb6d49808ff0fc1330fda87fa6f6250c6b5369b6645 \ + --hash=sha256:d56a1efd5bfd61486c8bc968fa18734464556f0fb8e51690f4ac25d85cbbbbc2 \ + --hash=sha256:d9050fee89a89ed57b4fb2c1bfac9a3d0c57a0d55aed95949eedbc42070fea39 \ + --hash=sha256:dd80ecb295460a5d9d260df63c43f4afbdd832d725a531f008dad1664f458adf \ + --hash=sha256:e8ea3e2d4066083e264e75c829078f9e149fa119d27e19acd503de65e0b13149 \ + --hash=sha256:eb3823f11823deade26ce3b9f40dcb4a213da7a670013929f31d5f5ed1055b22 \ + --hash=sha256:ee40c27c795bda6a5292e9cff9890189d32f7e3a0bf04e0e3c9430c4a00c37df \ + --hash=sha256:efb30e3baaea72ce5928e32bab719ab4770099079d66726a62b11b1ef7273be4 \ + --hash=sha256:f254d118d14a7f99d616271d6c3c27922c092dac11112670b157798b89bf4933 \ + --hash=sha256:f89c151aab2e2e23cb3fe0acad1e8b82841fd265379c4cecd0f3fcb34c15e0f6 \ + --hash=sha256:f97aeb209c3d2511443f8797e3e5a569aebb040d4f8bc79aa3ee78a8fb9e3dd8 \ + --hash=sha256:f9b587c9c7274c1613a30afabf65a272114cd6cdbe67b3406f818c79d7ab2e2a \ + --hash=sha256:fb061f596dad3a0f52b60dc6a5dec4a0c300dec41e058a7efe09256188d170b7 +mdurl==0.1.2 \ + --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \ + --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba +mlx==0.32.4 \ + --hash=sha256:001b07946f2867a800aee73d302ffdaf5eb81cafe64c7ba19fddf7e219324822 \ + --hash=sha256:05cca4bed007230e109ca33ac377bac96f3b4c8ed5b67097499de4e913dd011c \ + --hash=sha256:071566ae01dae3a293f3612b623eb68eeb2ef28d27d85ff66e661b6a6f254593 \ + --hash=sha256:09da967a668de8b7033de3d74930efcf36ef993ede93173f51f11452a1c09b22 \ + --hash=sha256:0c3cb35b709275d1791d435d2f1c4bd734e8a82ba99c340954cdda68570acaa2 \ + --hash=sha256:105ddb962e3dab018971dba4bd195167512fa0a43b431fb680d0019efbae0903 \ + --hash=sha256:18de5b82203c18d4e5be1a85c773afdd3e855266d8ecbdf2138072e29ee4cbbd \ + --hash=sha256:1933ecd6bbe639e98b5bb9c753e928103357df01a5791ca0d8285db3d810e4c7 \ + --hash=sha256:1dd56491b44a2bfa217f60da66a5c9c889add7ad9dc2cbcf526389ea31d83bee \ + --hash=sha256:1e52124110303abb7513e6575f59c4c1d32e721c1a45f7a2ae200e8cc492ef13 \ + --hash=sha256:2154f5ce28b51de46b990eb794223bebf8e0a5326ae2658a1e45c247e50779d6 \ + --hash=sha256:22e84ed60fb6386c9426ba2c23808052a4c2edd9643dabda0772886f849e4527 \ + --hash=sha256:32eb7a6c6a9646325e7dc5749d46cae30fb74eab8a39d3bbb0603163127bf7a4 \ + --hash=sha256:370cbb0b307c40ccdd0131587734520c498829b54364dceca7e2c7e517ef89ee \ + --hash=sha256:3f1ea7ed238d18e49cf266155039256e87987f43dab5e87ea7bb91a959e64f91 \ + --hash=sha256:42f57e27ea37642222e00031ea73e47420a40f7de6e6af870e82b8cdd033c5ec \ + --hash=sha256:43a6469797f09a985f8f035df63cd072105d5f16bfbe27d82b542065c988c3dd \ + --hash=sha256:4f8e640fd3afcc19da343c5a769743f361573b8db98cd739e295a387921486a5 \ + --hash=sha256:4f95afac25431585b34846d472ea0ad5db83fc97fb014d62c70082456f6b6b5c \ + --hash=sha256:539ff8b596669263bd531f49fa1a825f570c766ab43c48e454447d6a47e91271 \ + --hash=sha256:5f34d5aa0b23e2a52234665837e4804b045e9928df1be36f1a2450e0d1e996bb \ + --hash=sha256:6017de097cecbc28adec1048f89e579e93e2c2292b1325d1396f26aacd4107bc \ + --hash=sha256:60ba41564e8b5018c9d8a5f8ce7a5aaf70c96d8dd98c1a54b854cbada362d471 \ + --hash=sha256:6267be0db81a9d850b3ecd9bf0cf7dd0f439408db9fbc59237e37fda3f7676b0 \ + --hash=sha256:63ac6fde8a55d688448fc25eb32b645276501e0a30ff961a72958dfd0a4065df \ + --hash=sha256:668cc9dd0518b00c092b44dca365a12ffe0cebb5cca0af0b9790fe3cd8f51782 \ + --hash=sha256:6c6cf406fe093b4ea21876949e0d21f75384900f3df543e8411447ee37cdd394 \ + --hash=sha256:6dd2d7948c3708a62a1b13c32b03b5a94031e0cd3b7f5c5a0343e5a4a3b3bc41 \ + --hash=sha256:6e92768199ffcbc271c2fe0b0bf32f734d78bbc91d15ad7347cd7d5624a9b338 \ + --hash=sha256:70bac04a877236b059fdc7b317d47db335a48d6eafccda9b91a59907c594758f \ + --hash=sha256:733d28fc6b200910211924cd8d5deef86095cd085a0bf64502943c80b22942d5 \ + --hash=sha256:7928869076db6267ab3ebdb253b2c80be1e738b3032c783170bd1d59d460c578 \ + --hash=sha256:82716e3051bbf12d67d95397ce5018236c15edb87fe55f949bc383e5668d8f1e \ + --hash=sha256:83adc889ae89057fd9f292ca1a9ee56da43f181fccc7ae48a060d7aadc179eaa \ + --hash=sha256:869c4e2d99ef622cfb39e6581afe5d3286e0c01161e03ad580561db28bcd3992 \ + --hash=sha256:95830850ababacf86d4e1e11b8cfa062a14b12c0c5f332dad1d4f99e1679a162 \ + --hash=sha256:986f001874378d0a4c1f919817b7e331be96bbebf3993f5182459bcfc6ac0116 \ + --hash=sha256:9c2040afc35e71e210007a6bfb45c75fdffd8a1609885b8d138cdea919a6ef5e \ + --hash=sha256:9dee6ddc835bc16968daaa0fb804ef99bcc3cca5abf6c33bca17c52a1dd99823 \ + --hash=sha256:a01855e2c023e64683798d7148f9760c59b32be6e43f4bcbea8eb8137b650a5b \ + --hash=sha256:a9c09da5cbb4cf8b142f3b7bbda05e10b51d7793f861904e440208f63578a194 \ + --hash=sha256:b517badcb8174f8937699465a0ba5b58c2daeaa9bd13d69b1e6ab13401d24a74 \ + --hash=sha256:c1844df29fd58a78147b7fc2509682179d25edc81eb83659d26fef3c5930c25b \ + --hash=sha256:c45854cd4e20559bb2aa613c6aaffb58e86ec7cf5bdd32100c4a59d8bcaf4d9d \ + --hash=sha256:c4cb0d445a54278e5ba64a2d18b338421b1e8faac3e78b6b722ad9d83ac191fd \ + --hash=sha256:c7375f2d6acd8c72f413d018266ae06387cb9caab31f475f3ff1c5600a7cb4c5 \ + --hash=sha256:d124475e725707a94598211d3c80edfa9755bea9c327e8babff6ce4511344d9f \ + --hash=sha256:d46dd07f57a65bae00ba7da239ee76ebf87e3202f042808d209b56be3140e416 \ + --hash=sha256:dd0c9070d9c362fe280a0224806b1b47719b154984735041ebcc907e597c08ca \ + --hash=sha256:dfd5269398bb64372137d8c354530b6e81159ce0e92fd1ed7e9140b294fd939a \ + --hash=sha256:e1ce3514d2bc6f9c14e1c69787acee0926aae0599d73bacf4a8048394a2d2ca4 \ + --hash=sha256:e5ed9e82d813ed9314be9acbab95f519c5816233a2ab38270be2ff5d10d2786e \ + --hash=sha256:e635385a4f778b248ea6f61fbeb285b6bb14a1891d75cfbfd5af12e010298308 \ + --hash=sha256:ebed763d7da5833982529baf02d0330c5437f4ee5207a1a8a60ab261bd94302d \ + --hash=sha256:ef130e3da895c85374b11a6c389acb122893f2ffcbed826b8b62fd45a20b7ad6 \ + --hash=sha256:f0604cb3015091f285c79c7b7dbfcabcfa9948248728c7bab6e0263513c3d3fe \ + --hash=sha256:f1e6ef441e1e2ce54159022a8fa5597f8ea4f7acf278752049c4f774bbd0501d \ + --hash=sha256:f50b2b759c98d50ded360dc470d03d62ce1a41b3a6da81dd5e0b995865dca067 \ + --hash=sha256:f6cbda9cb8c33c9f8673a2b69fb19bdab75b5032d4e47a42a0e7b36db1c3ebcc \ + --hash=sha256:fbb3fcf1363a631d05aa5adcb30d07655158be07e09339c1fe62f7267b3a78f5 \ + --hash=sha256:fc8bfe0478c96cdcf0c4786f13edaa20490fa1714fb145f254627bd66654d81d \ + --hash=sha256:ff1d7be54758ea3a875b8fe54eff13bed17ad9566505e301f5d7851bf869680f +mlx-lm==0.32.2 \ + --hash=sha256:1af8a92f6a141c3e2bf5b0369ac4464203a8e2189c47b9e40d3e921e5b3a1fe9 \ + --hash=sha256:5c0991248cfff5872503d74f466d2532dd8cb7fb3670cb9be7a06d7305dadc04 +mlx-metal==0.32.4 \ + --hash=sha256:514df92d41a286895d2564b4b18f4da45096bd7a4a0c47e1042f345ad5a7f936 \ + --hash=sha256:8019b2db622599267d66cc168b2f0dbf5af929790a6c3b3913e00eabc42a7947 \ + --hash=sha256:9f0a3cc26d89724434d9684932fc6f3e4e83669d2a895d858ed2c8a55eb84e8b +mpmath==1.3.0 \ + --hash=sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f \ + --hash=sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c +multidict==7.2.1 \ + --hash=sha256:02009b402129a73e1f3da68f48eb999afbacd29f25aef0d5052b84ff5c2786a2 \ + --hash=sha256:02d9c04d395a36eeebe89e45f2269614a4675b8e83fddcba15bba2be903971e5 \ + --hash=sha256:03846be88267369908fcd9a91159358a3b142d740991c96e4f696d362fce516c \ + --hash=sha256:08ea94663d9e7c25d14d78222f7aee906c472d4837766bec62477c38f6e419dc \ + --hash=sha256:0c454b677214fa604e9c4a38952c685dc88a62c96f5576a7ce550f213d1dc318 \ + --hash=sha256:0c52fdd8cb8194fcb6969a417149aa1d09d6e48b69fb1b34ee1b1e4cb51ec183 \ + --hash=sha256:0c7b4d8cc9e6ae7070b8129bdb840215552d4e2689ca765d37eb208a24919209 \ + --hash=sha256:0d852d3d9638f852158d7de7200dd77f7ff8d77fc8f3d396032f3d847883f631 \ + --hash=sha256:0eb7fa012ab47b13e96bffc1369642f520adcc4e3d3e170d7f1a2b39fb953bce \ + --hash=sha256:0ec95a02f9f08246cc7f1d85ac425e4d5c233fd3f098f5be1b2cca16aa690186 \ + --hash=sha256:0f30d6eaf3cb309b6c21096c6c2b4cf3800f195a78b1babae85f481ce851bdc2 \ + --hash=sha256:12bbab225ce7f69df75409ab8005b11b4e9309fae863821e019e81b32e53a2a8 \ + --hash=sha256:13268013a3db11a214ccb6920f778d175b765f69a40509610b92e43602272718 \ + --hash=sha256:15da10cf11fd8d8716720c95b93180e94c8317405d89d08524c579ef360128ac \ + --hash=sha256:1d369ed297e79b417766327ece16bb7e89306c588df63c364a85d90d4aeac843 \ + --hash=sha256:1fb8c1a3480c130c3a6422d5f16f3cad6552bf08c2089dd288ba7134649183b5 \ + --hash=sha256:2022bd3194968a027f64ed16f9779e62e71a823a9df3971a7328c1d45dfeb9ab \ + --hash=sha256:21d86f2aa58aa428fb9909d6b8587b75eea827287e3515b8506dca86b55e2c7d \ + --hash=sha256:223427392fdf993e198644ec40c404fd93f1cd2a61328d18842ecbf154d02c82 \ + --hash=sha256:2529873a3bf68c372532a9f8058bcf4199e78387e92cd6a01b73334bfe6a7e3f \ + --hash=sha256:2592fb6c335d67f1912bf72788c02fd5dab305fc3c8c7eab078a5bec1aaa0f88 \ + --hash=sha256:25ebc4208d9098f77caeb16df895a0e56eb6c3b22870ac4e3ec43e0a9d6a33b6 \ + --hash=sha256:27166b6ec73eac37696d66b2c6efbd44b6d04b597d655070959df54dc7c71c0b \ + --hash=sha256:27cc258247b13008742f0e239933ad01dec5ed4e6dfc63849e30e04e1aa5bc82 \ + --hash=sha256:295a15ccb8cfde9351dd6062b80af4e839460636b3c46813b4aa443905ded86a \ + --hash=sha256:2b4d0c4e13d329ffee73d46128e32dd3b4aeb2f9c6ac9c8a89eb28d3b82dcea8 \ + --hash=sha256:2bac371da2c3554a99ba126f545e79ab8e8d9426a3e41df81d00ad725c1e2cbf \ + --hash=sha256:2c4e6a97f79699f33e6dc13bddb5631781ee79a4a94c1822116d100e7d5c136c \ + --hash=sha256:2d4cfbbb1023f0f6795b5395c400752fb23a5a09ba756aa9003886bbc47b3e12 \ + --hash=sha256:2e279ad5a6e9347bc9e043fdbee180a0480c8fd52618c3258e983dd93d98ed49 \ + --hash=sha256:2f3cf710144b1859f4128051cc27ea86eee83caac5648cf2ca0c1b835261cbbe \ + --hash=sha256:30572b61c7932e4d3c2ad1e580de7db1f35b7a35d36db38f89397ce3f2e69096 \ + --hash=sha256:335f715f8c111654f29e4bf19086bdf0245579d2b4f4f59ca8dd9b3003b859c1 \ + --hash=sha256:363e5db93fc3f65f3218a79fe108d217b9d264181a4e993c77552bfe275d0393 \ + --hash=sha256:36b868758fb11cfa748c788b793994e73660abec90f83c780a678539c2c468bf \ + --hash=sha256:37b161535e92776788957a165fcf38a80b33c1efde7b18cab287db4e4574df78 \ + --hash=sha256:3b7542fad2706595c1b1853b46f2c3c4ae5cc5a6252b7225f294d607a29e1bdf \ + --hash=sha256:3ca4e2e9102d0788b94894a30a5e3561fd4818a0605d8748d8fe780f890aa069 \ + --hash=sha256:3ca60708f0ca9d994f46790c5a5c774771e2f1dcb75b12c70a5582f915d0e721 \ + --hash=sha256:3d22ebb716ac79bf32c2a1d15250f017faef719114af4376e8dd814d6633cf0a \ + --hash=sha256:3d6fce7cc4ef63d9a7633cbae43e737798412805a4c3ba876cdf472dc6ff9c51 \ + --hash=sha256:4b338b45dc26ca4bac702e1278754f78613d4d0081e14e94e44fe8e261bf1750 \ + --hash=sha256:4bebc9587cc29359e3b045518a7a09264fa882a7d165b0d143fdac8eeb7ea948 \ + --hash=sha256:4d61be3725016ef5db3543c95f1f062d7d150ba776582d959a982af88e75fa55 \ + --hash=sha256:4eb2650aa240b62ab0c6d87238bee5d14aa4d411c0d69ad61be53e026e0785ba \ + --hash=sha256:4f31ddf9c00e0e7db848b0236c717acbe8a51954d0d31b4d908c538ab3f0f5bc \ + --hash=sha256:522f7d2351743804cdf5c5a304bc45f9d55e935dd87706fae2dbeafe0fed0b49 \ + --hash=sha256:5324411117bdb67cfaeb3d1d28fb783710fcca3d88b855696af99044d7219e4b \ + --hash=sha256:554ee1d2e71fb5b4059c0c4ee35d8cbc8af2a3147036d65a454c53fea07ff4eb \ + --hash=sha256:57ac987ec5d26d89bbc48c03e486f659e1367d425c465552ac2e4c4af8219def \ + --hash=sha256:57b5d0df4c60ab8b1159687610a1c3ae069ad2380d390a79dedff5c82318e714 \ + --hash=sha256:584ebfa26c9dcf3e465637a5a9afa2647bebb3022b50b1ff384834ba8e0380d1 \ + --hash=sha256:5a7df927c7999d1d3196176a8d4139d3a0e1765936f5de8c768097275b2d617a \ + --hash=sha256:5b944091cfa7da4f7a9bd2587569cd90c94b89ec4721f8e87fe62504f2432b67 \ + --hash=sha256:5deadf03fb4a7842696d551f9f9a06dd4445bb43ca06b5f9736e4e1885561333 \ + --hash=sha256:5efddcdbcb73f5485dca2b6624edc8ee063604b77bd3a3eb772826063965819f \ + --hash=sha256:65e4448dadc7c94a8643bb41361e45f3a73d46e36a008a9bc03e9b525f4d7c80 \ + --hash=sha256:66af55b07e4593790157e85f897f06983ded8a8692cb2fb048f3049c1d3fa172 \ + --hash=sha256:678ac791b5820d9346eb13c8515fe0c9383659335e5cfc544bf6f54714ca1939 \ + --hash=sha256:68b97b721d95b77d75e718d1b62a227fa4b3e647bd2a9fb39552d1a79ffb67c0 \ + --hash=sha256:6966806cf917cbbeb9a8b5c581db52e19c9af0ef5fe009db54c1f5799a6e003f \ + --hash=sha256:69befda4b1ef57027ea95dc6ed733568642f330fb3203a3e5c5ef107d41e0a1f \ + --hash=sha256:6e22756c6e2d4f57ead0d2e6be179d8a16d661bee424b81de0c6c0c1305ec39f \ + --hash=sha256:6efdeed2723431999cf3bcbc84c72dbe0f65d16bb1f84e15a657f5b60ff18ca6 \ + --hash=sha256:714fe5f3eabd153b1b6911d0b5d31cfc2b808ae6b9e59a32fab17a4e6cdad5a6 \ + --hash=sha256:7238f7135481926d52a94c18a8cca633a9e72c1cbfccd5796548298a479b0656 \ + --hash=sha256:74d3e015c28b43b6c1a108eec324ea2efb185c359c459216cabd4cb98f7f02f6 \ + --hash=sha256:76a4f5132b8dc29eb3c768ee9b47e132a1d24fbc2e9259854c01af9beaff1d49 \ + --hash=sha256:7726c53b1d59eb57b009a9e8759d4f71049ebdacf30642a198a197f80cea451c \ + --hash=sha256:781ca5dfc2f1d58e47f52216a0c1c7e1ba91ce8aa235459e20de2d402af77fb3 \ + --hash=sha256:785ef2f3e372dabc131f228a275f97eca92ad17cfab1ab138790e330d99abe3e \ + --hash=sha256:7cb1a6bb70edcc06ea65cb9a35654f268ee39d9fc3a52240e6ba074db4d9c99e \ + --hash=sha256:7fb3bc8d58e1b7c1d9fa1d995e30a4ce9dbe49f4c63c755a1ffdecdfbd026ccb \ + --hash=sha256:8148c2aaaf4b85d7872f024c8bb0c9b9797cc76b10588e3594a69cb01057472a \ + --hash=sha256:81a5f84a76401c4330e6db4e170dddd58860b30c4e8a44a181e5c2809c7f9c9d \ + --hash=sha256:81c6fc88ac9bf6920a0cdf22d3c383964167f12d35eb630463fc6d5ac89e460d \ + --hash=sha256:822a7fcd33f6922b650e1b26594f09d53c5d011fe655fea7ded27b2728ce2a1b \ + --hash=sha256:83fbd7cfaca614975efdbdcd9e2df45f3e987e819216468fb73e1db6f0365b98 \ + --hash=sha256:846b17193f1c373d6f05ada894fadf56bce2473067caea0aab51828849894b31 \ + --hash=sha256:8648dd5dc4d5db32b5936dc5e85e9a4d79db1135513d40d1f54ca15503750324 \ + --hash=sha256:873d35366cc115be02a1c858f9b22a1a9f6182b99aab2171ee5276af02a153e3 \ + --hash=sha256:8c3ff4f5c376df7126695a52af61e6084b69c9e52dcb9f4713e71ce9819e1bfd \ + --hash=sha256:90efd90a0f9b7ae3844a4fb3ae614321832d364ae19567b7cd312315fac4ec39 \ + --hash=sha256:9306e0c5595f91874e685be0a9eb743d48ba069c888eea051bec3c67c08b5b8d \ + --hash=sha256:987f65f6c9321402bc7012f6c6d09ba501b88ddb1640f5b0b4a19f2caafe24a5 \ + --hash=sha256:9a53776adc1ba923c9e345fdea7b61553c44c17a9af5eba8d8def8c5dcac4dec \ + --hash=sha256:9c44bd978adddf39df5834c6a1efd7d075c84769a7a084168d035a2a276d9008 \ + --hash=sha256:9c9f285f788acf2448a57c9b93d31103ac69bd03f92907e2ffbb23c4e2b42eb6 \ + --hash=sha256:9df532dd12c59a7a4d381646fc1bf5ccb4bcdbd01c0887d07ec769fae965ea9a \ + --hash=sha256:a0f999155c22c8929cc492949c08c6fe7ec8079a5e1bfdeb34b9a3e4991959d0 \ + --hash=sha256:a2a322c8a6ca82a5a67ae6542e9c6a13ded9045cfd171dcccc5c213ac4fe0eab \ + --hash=sha256:a3d28ac22fe658ad7486d1532b3a9084fbf65b428db31f47212c5b0b6da826f1 \ + --hash=sha256:a3d9a59bcdf8531d46b56bcd512017533510c25e955c2c546efd0743bd840940 \ + --hash=sha256:a789e3d27fc5665cc0477f10a35a89383313e4c9cf8b5e6af7ea71f039cdcc0e \ + --hash=sha256:a7d120bdde5b213e67ed7dc80ea3adf4f014453fbc20195d619ba2ceb34084f3 \ + --hash=sha256:a878fef2797a7c082aa47559af68299372edebc7367bd5128dff2d36e6d820e1 \ + --hash=sha256:a92e3080d8889b0f7a80ea0c4a72181b4d4d5d3918a03136b4a459f51f5f59da \ + --hash=sha256:a9cc121b5ee2c8b4bd4b6b526d5a26bb782f4d620463f73707691b2004b8c349 \ + --hash=sha256:b4821bd30b38144d8ab75df56af0b07e9d71327c9cf94c0c7a1965f865bb9615 \ + --hash=sha256:b5fb6b048931ea925b484f0c7c01b007981415a00a6c62ee74bbf8d229d39c08 \ + --hash=sha256:b63acdf4df5a78a15223bbb510bb3e0f8234dfa807610ccb8796d0842db2c801 \ + --hash=sha256:b81ff0f2d375988152614eaea4d5023c98ecb08f77df4bb1d96762504bb86fca \ + --hash=sha256:b97bffa5772b7e853303de094829fcd3a9bd49fddd70534651ee4933691f6587 \ + --hash=sha256:ba5e8d9310a794b853fb0e327d46a827b5b015576341219a591f88ed9d799c27 \ + --hash=sha256:bc9decb36abd00ed5d123db9df70eb9a0da45d6376d86d64f4a94bfd5a1b83fe \ + --hash=sha256:c10ac5e3e76837180656079008f71add8339b00c3c26314092bcd1e8e449049f \ + --hash=sha256:c753b820738cddc097892fee95e7cd716fbdfc9640414c5e9ce9463ad125321b \ + --hash=sha256:c85a0a54a19429a17ef449e967baffe7b5089cb4f6ef2894c9168a69fa024d05 \ + --hash=sha256:cadd02ca804d6ebe799a7af19197d9730094fe2cc74b70eb4f374f4b8c1886c1 \ + --hash=sha256:cb43bb34346155d479acdc5423afccdff79ce1fc66adfcc9de995cbec8a13acf \ + --hash=sha256:cb7fc8820b206932ec6d8f8985aeba6edfd2932e13b6c4bf2434d6bcbbeef3e1 \ + --hash=sha256:cba29f12cd717f1cbbe220edf005666f8df0453347217748331a0c2f7522eca4 \ + --hash=sha256:cd69c99affd1b4debc1f9a53058ea6e3a9b34f2e733840bb45891666cd8ede0a \ + --hash=sha256:ce0f884408938fbd72e764031d0e23a8f5e438a7bf73641089c7a6465cb84456 \ + --hash=sha256:cecb2c778f00a65c6ca01410dd194d0e797a9eebb7c6dea0db87718719f293c7 \ + --hash=sha256:cff7657e79224dea46f2f2e58eb99186656ca63ebe356212210c5c00e9beb814 \ + --hash=sha256:d0381074dc21225951278d7e4a7a2241f7fb86a4d8b94154dfee1411f49cf851 \ + --hash=sha256:d094951489bb7836342c005e790bd005e60b669aaf5c936b96dd5d68cbd2e23b \ + --hash=sha256:d10e49b940e70e2a4e91f44098007dda0bacb78c3f8e31ba7a37ee2ce52269e6 \ + --hash=sha256:d37773029ba034a2cc970b6eeb67dad3bff9d894393c51f6bb1c6b4f563a032c \ + --hash=sha256:d4af0d863e72f3ea48e85d3aa1d1b426fd81e9544fd7976fc6d6753584a25b03 \ + --hash=sha256:d5738cd929f2af8651ebb284467acb58b1ec0f2f4d42489cd0597172bc82e15b \ + --hash=sha256:d615377a8e7bfc4f1983ede3f411c2ac2b0f7c3053f262d0437b7d8bcc4485e3 \ + --hash=sha256:dbda2baafe08f8431fd3333be02c261023fd454607e3bde5e7dc00565f7bebcb \ + --hash=sha256:dc6f3dcb08c4b41e64f2d6cf272b5686d9144db585b2e138a8b1664376ab3921 \ + --hash=sha256:e0f2b33a6ae233f4da38c77ea32f90aab2cb82ba819d7b6c4f1b68cd33d871b6 \ + --hash=sha256:e47d058c2db95010f5d2e1f6037acebdfb0e2fa4507650e1041437985c91db38 \ + --hash=sha256:e64b86d16158954825d12799271979c6944c1fd1d03575b2f22e869c3f7d00dc \ + --hash=sha256:e8af3e6f1bdbc31fd762b094133b478b89988eaebc63cbe82b1d9e3bbd15cede \ + --hash=sha256:eb5c4a5b1281985271b6c29be53f2c1a9decf11e30a0e2733439c4d9d61b9ebb \ + --hash=sha256:ec4ee5d2d624088775e61cada87bbe7629bfd936bfbd57f122a106970d8ab1ee \ + --hash=sha256:ed6c107642a9acaa7ede32dcd428a6c87e302c5d555ecd3ec132ffa8c6155b4b \ + --hash=sha256:edffdb3950d3a8b769ddaec3a0962fb7b76b3c96f317f6b88500455a537dded2 \ + --hash=sha256:efe695cc2081633b02fcb95bc1b13070f6647c9ad52d42a8beeb3c2a7ea062dc \ + --hash=sha256:f07f06db2e333b68dd52560b8b0b12b6f8bf6053cedebf9af4aecfecd2dc1b32 \ + --hash=sha256:f15205c67d4c45250fcff5da077f0ae54102b5bc39e9ee8bab90d99e09a728c5 \ + --hash=sha256:f2087ee23a18d1d618a135eedcafba7dfc40c6be4e8e52d7f29a1c8a2344cfcc \ + --hash=sha256:f278f118f9fdb5faba5a6792be397fbda094d1568efa4dfe8c3595ce4ce89eea \ + --hash=sha256:f29885fef157a602d1816439e5da964c70ebcdbbcd4bb9d2d21b7e8bb5636604 \ + --hash=sha256:f2cc27ec6a53b1d39bab44d2b9dd21cc31e796d01b5e18a76d569721282bb264 \ + --hash=sha256:f332b16911ffc668baec6aaf8f08a09e1af34a8ee87ccac26bd722589e264645 \ + --hash=sha256:f5812cfcf7daf3ace5fedf6e2ef8d4b342c92fb8ea3a87c1aed2b50453271093 \ + --hash=sha256:f62172cf387e92f4928b60e5936b02c06e3c8449ed7fb440978d6c9bcbfc85df \ + --hash=sha256:f9c118e866164ce05498d9106a4bd01e745321403cd6f0b77a0b2587768f8c06 \ + --hash=sha256:f9e78d98a29e969a001e953eb09167a48bbc71249e804dae5db987ee7e6531c9 \ + --hash=sha256:fa0ecd064b0ae18d235283abb5adbc4e07304dba8f2aa7c0d61f28bebcc70d4c \ + --hash=sha256:fa949c81e3865c10f981dea72fd8d418b59edd13a047a0aee89ae64790113d53 \ + --hash=sha256:fba33e264cdd2ec43b762b9960d1648478eecfc1ce6e8159e7573510f0412c0a \ + --hash=sha256:fc45ff19520bc5321dcd9c6dd7df6f35ddd894eed35e5be65d1828a9c3f5e7fb \ + --hash=sha256:fcfebcb537f419e415b6e2bfc77ddbd33abe3c036f0105410a25a14741df9c31 \ + --hash=sha256:fd24c4425fdb8e822601335602375c6d0cb020f7a368e1d5842eb7925a9c8748 +networkx==3.7 \ + --hash=sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0 \ + --hash=sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a +numpy==2.3.5 \ + --hash=sha256:00dc4e846108a382c5869e77c6ed514394bdeb3403461d25a829711041217d5b \ + --hash=sha256:0472f11f6ec23a74a906a00b48a4dcf3849209696dff7c189714511268d103ae \ + --hash=sha256:04822c00b5fd0323c8166d66c701dc31b7fbd252c100acd708c48f763968d6a3 \ + --hash=sha256:052e8c42e0c49d2575621c158934920524f6c5da05a1d3b9bab5d8e259e045f0 \ + --hash=sha256:09a1bea522b25109bf8e6f3027bd810f7c1085c64a0c7ce050c1676ad0ba010b \ + --hash=sha256:0cd00b7b36e35398fa2d16af7b907b65304ef8bb4817a550e06e5012929830fa \ + --hash=sha256:0d8163f43acde9a73c2a33605353a4f1bc4798745a8b1d73183b28e5b435ae28 \ + --hash=sha256:1062fde1dcf469571705945b0f221b73928f34a20c904ffb45db101907c3454e \ + --hash=sha256:11e06aa0af8c0f05104d56450d6093ee639e15f24ecf62d417329d06e522e017 \ + --hash=sha256:17531366a2e3a9e30762c000f2c43a9aaa05728712e25c11ce1dbe700c53ad41 \ + --hash=sha256:1978155dd49972084bd6ef388d66ab70f0c323ddee6f693d539376498720fb7e \ + --hash=sha256:1ed1ec893cff7040a02c8aa1c8611b94d395590d553f6b53629a4461dc7f7b63 \ + --hash=sha256:2dcd0808a421a482a080f89859a18beb0b3d1e905b81e617a188bd80422d62e9 \ + --hash=sha256:2e2eb32ddb9ccb817d620ac1d8dae7c3f641c1e5f55f531a33e8ab97960a75b8 \ + --hash=sha256:2feae0d2c91d46e59fcd62784a3a83b3fb677fead592ce51b5a6fbb4f95965ff \ + --hash=sha256:3095bdb8dd297e5920b010e96134ed91d852d81d490e787beca7e35ae1d89cf7 \ + --hash=sha256:30bc11310e8153ca664b14c5f1b73e94bd0503681fcf136a163de856f3a50139 \ + --hash=sha256:3101e5177d114a593d79dd79658650fe28b5a0d8abeb8ce6f437c0e6df5be1a4 \ + --hash=sha256:396084a36abdb603546b119d96528c2f6263921c50df3c8fd7cb28873a237748 \ + --hash=sha256:3997b5b3c9a771e157f9aae01dd579ee35ad7109be18db0e85dbdbe1de06e952 \ + --hash=sha256:414802f3b97f3c1eef41e530aaba3b3c1620649871d8cb38c6eaff034c2e16bd \ + --hash=sha256:51c1e14eb1e154ebd80e860722f9e6ed6ec89714ad2db2d3aa33c31d7c12179b \ + --hash=sha256:51c55fe3451421f3a6ef9a9c1439e82101c57a2c9eab9feb196a62b1a10b58ce \ + --hash=sha256:5ee6609ac3604fa7780e30a03e5e241a7956f8e2fcfe547d51e3afa5247ac47f \ + --hash=sha256:612a95a17655e213502f60cfb9bf9408efdc9eb1d5f50535cc6eb365d11b42b5 \ + --hash=sha256:6203fdf9f3dc5bdaed7319ad8698e685c7a3be10819f41d32a0723e611733b42 \ + --hash=sha256:63c0e9e7eea69588479ebf4a8a270d5ac22763cc5854e9a7eae952a3908103f7 \ + --hash=sha256:66f85ce62c70b843bab1fb14a05d5737741e74e28c7b8b5a064de10142fad248 \ + --hash=sha256:6cf9b429b21df6b99f4dee7a1218b8b7ffbbe7df8764dc0bd60ce8a0708fed1e \ + --hash=sha256:70b37199913c1bd300ff6e2693316c6f869c7ee16378faf10e4f5e3275b299c3 \ + --hash=sha256:727fd05b57df37dc0bcf1a27767a3d9a78cbbc92822445f32cc3436ba797337b \ + --hash=sha256:74ae7b798248fe62021dbf3c914245ad45d1a6b0cb4a29ecb4b31d0bfbc4cc3e \ + --hash=sha256:784db1dcdab56bf0517743e746dfb0f885fc68d948aba86eeec2cba234bdf1c0 \ + --hash=sha256:86945f2ee6d10cdfd67bcb4069c1662dd711f7e2a4343db5cecec06b87cf31aa \ + --hash=sha256:86d835afea1eaa143012a2d7a3f45a3adce2d7adc8b4961f0b362214d800846a \ + --hash=sha256:872a5cf366aec6bb1147336480fef14c9164b154aeb6542327de4970282cd2f5 \ + --hash=sha256:8b973c57ff8e184109db042c842423ff4f60446239bd585a5131cc47f06f789d \ + --hash=sha256:8cba086a43d54ca804ce711b2a940b16e452807acebe7852ff327f1ecd49b0d4 \ + --hash=sha256:8f7f0e05112916223d3f438f293abf0727e1181b5983f413dfa2fefc4098245c \ + --hash=sha256:900218e456384ea676e24ea6a0417f030a3b07306d29d7ad843957b40a9d8d52 \ + --hash=sha256:93eebbcf1aafdf7e2ddd44c2923e2672e1010bddc014138b229e49725b4d6be5 \ + --hash=sha256:9c75442b2209b8470d6d5d8b1c25714270686f14c749028d2199c54e29f20b4d \ + --hash=sha256:9ee2197ef8c4f0dfe405d835f3b6a14f5fee7782b5de51ba06fb65fc9b36e9f1 \ + --hash=sha256:a414504bef8945eae5f2d7cb7be2d4af77c5d1cb5e20b296c2c25b61dff2900c \ + --hash=sha256:a4b9159734b326535f4dd01d947f919c6eefd2d9827466a696c44ced82dfbc18 \ + --hash=sha256:a80afd79f45f3c4a7d341f13acbe058d1ca8ac017c165d3fa0d3de6bc1a079d7 \ + --hash=sha256:aa5bc7c5d59d831d9773d1170acac7893ce3a5e130540605770ade83280e7188 \ + --hash=sha256:acfd89508504a19ed06ef963ad544ec6664518c863436306153e13e94605c218 \ + --hash=sha256:aeffcab3d4b43712bb7a60b65f6044d444e75e563ff6180af8f98dd4b905dfd2 \ + --hash=sha256:afaffc4393205524af9dfa400fa250143a6c3bc646c08c9f5e25a9f4b4d6a903 \ + --hash=sha256:b0c7088a73aef3d687c4deef8452a3ac7c1be4e29ed8bf3b366c8111128ac60c \ + --hash=sha256:b46b4ec24f7293f23adcd2d146960559aaf8020213de8ad1909dba6c013bf89c \ + --hash=sha256:b501b5fa195cc9e24fe102f21ec0a44dffc231d2af79950b451e0d99cea02234 \ + --hash=sha256:bf06bc2af43fa8d32d30fae16ad965663e966b1a3202ed407b84c989c3221e82 \ + --hash=sha256:c804e3a5aba5460c73955c955bdbd5c08c354954e9270a2c1565f62e866bdc39 \ + --hash=sha256:c8a9958e88b65c3b27e22ca2a076311636850b612d6bbfb76e8d156aacde2aaf \ + --hash=sha256:cc0a57f895b96ec78969c34f682c602bf8da1a0270b09bc65673df2e7638ec20 \ + --hash=sha256:cc8920d2ec5fa99875b670bb86ddeb21e295cb07aa331810d9e486e0b969d946 \ + --hash=sha256:ccc933afd4d20aad3c00bcef049cb40049f7f196e0397f1109dba6fed63267b0 \ + --hash=sha256:ce581db493ea1a96c0556360ede6607496e8bf9b3a8efa66e06477267bc831e9 \ + --hash=sha256:d0f23b44f57077c1ede8c5f26b30f706498b4862d3ff0a7298b8411dd2f043ff \ + --hash=sha256:d21644de1b609825ede2f48be98dfde4656aefc713654eeee280e37cadc4e0ad \ + --hash=sha256:d6889ec4ec662a1a37eb4b4fb26b6100841804dac55bd9df579e326cdc146227 \ + --hash=sha256:de5672f4a7b200c15a4127042170a694d4df43c992948f5e1af57f0174beed10 \ + --hash=sha256:e6a0bc88393d65807d751a614207b7129a310ca4fe76a74e5c7da5fa5671417e \ + --hash=sha256:ed89927b86296067b4f81f108a2271d8926467a8868e554eaf370fc27fa3ccaf \ + --hash=sha256:ee3888d9ff7c14604052b2ca5535a30216aa0a58e948cdd3eeb8d3415f638769 \ + --hash=sha256:f0963b55cdd70fad460fa4c1341f12f976bb26cb66021a5580329bd498988310 \ + --hash=sha256:f16417ec91f12f814b10bafe79ef77e70113a2f5f7018640e7425ff979253425 \ + --hash=sha256:f28620fe26bee16243be2b7b874da327312240a7cdc38b769a697578d2100013 \ + --hash=sha256:f4255143f5160d0de972d28c8f9665d882b5f61309d8362fdd3e103cf7bf010c \ + --hash=sha256:ffac52f28a7849ad7576293c0cb7b9f08304e8f7d738a8cb8a90ec4c55a998eb \ + --hash=sha256:ffe22d2b05504f786c867c8395de703937f934272eb67586817b46188b4ded6d \ + --hash=sha256:fffe29a1ef00883599d1dc2c51aa2e5d80afe49523c261a74933df395c15c520 +orjson==3.11.6 \ + --hash=sha256:09dded2de64e77ac0b312ad59f35023548fb87393a57447e1bb36a26c181a90f \ + --hash=sha256:0a54c72259f35299fd033042367df781c2f66d10252955ca1efb7db309b954cb \ + --hash=sha256:0b14dd49f3462b014455a28a4d810d3549bf990567653eb43765cd847df09145 \ + --hash=sha256:132b0ab2e20c73afa85cf142e547511feb3d2f5b7943468984658f3952b467d4 \ + --hash=sha256:150f12e59d6864197770c78126e1a6e07a3da73d1728731bf3bc1e8b96ffdbe6 \ + --hash=sha256:1608999478664de848e5900ce41f25c4ecdfc4beacbc632b6fd55e1a586e5d38 \ + --hash=sha256:1f42da604ee65a6b87eef858c913ce3e5777872b19321d11e6fc6d21de89b64f \ + --hash=sha256:2a42efebc45afabb1448001e90458c4020d5c64fbac8a8dc4045b777db76cb5a \ + --hash=sha256:2a8eeed7d4544cf391a142b0dd06029dac588e96cc692d9ab1c3f05b1e57c7f6 \ + --hash=sha256:2c68de30131481150073d90a5d227a4a421982f42c025ecdfb66157f9579e06f \ + --hash=sha256:2c6b81f47b13dac2caa5d20fbc953c75eb802543abf48403a4703ed3bff225f0 \ + --hash=sha256:300360edf27c8c9bf7047345a94fddf3a8b8922df0ff69d71d854a170cb375cf \ + --hash=sha256:313dfd7184cde50c733fc0d5c8c0e2f09017b573afd11dc36bd7476b30b4cb17 \ + --hash=sha256:314e9c45e0b81b547e3a1cfa3df3e07a815821b3dac9fe8cb75014071d0c16a4 \ + --hash=sha256:351b96b614e3c37a27b8ab048239ebc1e0be76cc17481a430d70a77fb95d3844 \ + --hash=sha256:380f9709c275917af28feb086813923251e11ee10687257cd7f1ea188bcd4485 \ + --hash=sha256:3a63b5e7841ca8635214c6be7c0bf0246aa8c5cd4ef0c419b14362d0b2fb13de \ + --hash=sha256:40dc277999c2ef227dcc13072be879b4cfd325502daeb5c35ed768f706f2bf30 \ + --hash=sha256:46ebee78f709d3ba7a65384cfe285bb0763157c6d2f836e7bde2f12d33a867a2 \ + --hash=sha256:52263949f41b4a4822c6b1353bcc5ee2f7109d53a3b493501d3369d6d0e7937a \ + --hash=sha256:5ae45df804f2d344cffb36c43fdf03c82fb6cd247f5faa41e21891b40dfbf733 \ + --hash=sha256:6026db2692041d2a23fe2545606df591687787825ad5821971ef0974f2c47630 \ + --hash=sha256:6439e742fa7834a24698d358a27346bb203bff356ae0402e7f5df8f749c621a8 \ + --hash=sha256:647d6d034e463764e86670644bdcaf8e68b076e6e74783383b01085ae9ab334f \ + --hash=sha256:65dfa096f4e3a5e02834b681f539a87fbe85adc82001383c0db907557f666bfc \ + --hash=sha256:6dddf9ba706294906c56ef5150a958317b09aa3a8a48df1c52ccf22ec1907eac \ + --hash=sha256:6e0bb2c1ea30ef302f0f89f9bf3e7f9ab5e2af29dc9f80eb87aa99788e4e2d65 \ + --hash=sha256:6f03f30cd8953f75f2a439070c743c7336d10ee940da918d71c6f3556af3ddcf \ + --hash=sha256:71b7cbef8471324966c3738c90ba38775563ef01b512feb5ad4805682188d1b9 \ + --hash=sha256:72c5005eb45bd2535632d4f3bec7ad392832cfc46b62a3021da3b48a67734b45 \ + --hash=sha256:75682d62b1b16b61a30716d7a2ec1f4c36195de4a1c61f6665aedd947b93a5d5 \ + --hash=sha256:7ab85bdbc138e1f73a234db6bb2e4cc1f0fcec8f4bd2bd2430e957a01aadf746 \ + --hash=sha256:825e0a85d189533c6bff7e2fc417a28f6fcea53d27125c4551979aecd6c9a197 \ + --hash=sha256:8523b9cc4ef174ae52414f7699e95ee657c16aa18b3c3c285d48d7966cce9081 \ + --hash=sha256:8d1035d1b25732ec9f971e833a3e299d2b1a330236f75e6fd945ad982c76aaf3 \ + --hash=sha256:8d777ec41a327bd3b7de97ba7bce12cc1007815ca398e4e4de9ec56c022c090b \ + --hash=sha256:905ee036064ff1e1fd1fb800055ac477cdcb547a78c22c1bc2bbf8d5d1a6fb42 \ + --hash=sha256:925e2df51f60aa50f8797830f2adfc05330425803f4105875bb511ced98b7f89 \ + --hash=sha256:931607a8865d21682bb72de54231655c86df1870502d2962dbfd12c82890d077 \ + --hash=sha256:954dae4e080574672a1dfcf2a840eddef0f27bd89b0e94903dd0824e9c1db060 \ + --hash=sha256:955368c11808c89793e847830e1b1007503a5923ddadc108547d3b77df761044 \ + --hash=sha256:9a2d9746a5b5ce20c0908ada451eb56da4ffa01552a50789a0354d8636a02953 \ + --hash=sha256:9d576865a21e5cc6695be8fb78afc812079fd361ce6a027a7d41561b61b33a90 \ + --hash=sha256:a5a5468e5e60f7ef6d7f9044b06c8f94a3c56ba528c6e4f7f06ae95164b595ec \ + --hash=sha256:a613fc37e007143d5b6286dccb1394cd114b07832417006a02b620ddd8279e37 \ + --hash=sha256:a726fa86d2368cd57990f2bd95ef5495a6e613b08fc9585dfe121ec758fb08d1 \ + --hash=sha256:a8173e0d3f6081e7034c51cf984036d02f6bab2a2126de5a759d79f8e5a140e7 \ + --hash=sha256:af44baae65ef386ad971469a8557a0673bb042b0b9fd4397becd9c2dfaa02588 \ + --hash=sha256:afd177f5dd91666d31e9019f1b06d2fcdf8a409a1637ddcb5915085dede85680 \ + --hash=sha256:b04575417a26530637f6ab4b1f7b4f666eb0433491091da4de38611f97f2fcf3 \ + --hash=sha256:b2e2e2456788ca5ea75616c40da06fc885a7dc0389780e8a41bf7c5389ba257b \ + --hash=sha256:b376fb05f20a96ec117d47987dd3b39265c635725bda40661b4c5b73b77b5fde \ + --hash=sha256:b81ffd68f084b4e993e3867acb554a049fa7787cc8710bbcc1e26965580d99be \ + --hash=sha256:b83eb2e40e8c4da6d6b340ee6b1d6125f5195eb1b0ebb7eac23c6d9d4f92d224 \ + --hash=sha256:ba8daee3e999411b50f8b50dbb0a3071dd1845f3f9a1a0a6fa6de86d1689d84d \ + --hash=sha256:c310a48542094e4f7dbb6ac076880994986dda8ca9186a58c3cb70a3514d3231 \ + --hash=sha256:caaed4dad39e271adfadc106fab634d173b2bb23d9cf7e67bd645f879175ebfc \ + --hash=sha256:cbae5c34588dc79938dffb0b6fbe8c531f4dc8a6ad7f39759a9eb5d2da405ef2 \ + --hash=sha256:cded072b9f65fcfd188aead45efa5bd528ba552add619b3ad2a81f67400ec450 \ + --hash=sha256:ce374cb98411356ba906914441fc993f271a7a666d838d8de0e0900dd4a4bc12 \ + --hash=sha256:d8dfa7a5d387f15ecad94cb6b2d2d5f4aeea64efd8d526bfc03c9812d01e1cc0 \ + --hash=sha256:e0ab8d13aa2a3e98b4a43487c9205b2c92c38c054b4237777484d503357c8437 \ + --hash=sha256:e259e85a81d76d9665f03d6129e09e4435531870de5961ddcd0bf6e3a7fde7d7 \ + --hash=sha256:e4ae1670caabb598a88d385798692ce2a1b2f078971b3329cfb85253c6097f5b \ + --hash=sha256:f0f6e9f8ff7905660bc3c8a54cd4a675aa98f7f175cf00a59815e2ff42c0d916 \ + --hash=sha256:f3a135f83185c87c13ff231fcb7dbb2fa4332a376444bd65135b50ff4cc5265c \ + --hash=sha256:f4295948d65ace0a2d8f2c4ccc429668b7eb8af547578ec882e16bf79b0050b2 \ + --hash=sha256:f75c318640acbddc419733b57f8a07515e587a939d8f54363654041fd1f4e465 \ + --hash=sha256:f8515e5910f454fe9a8e13c2bb9dc4bae4c1836313e967e72eb8a4ad874f0248 \ + --hash=sha256:f884c7fb1020d44612bd7ac0db0babba0e2f78b68d9a650c7959bf99c783773f \ + --hash=sha256:f89d104c974eafd7436d7a5fdbc57f7a1e776789959a2f4f1b2eab5c62a339f4 \ + --hash=sha256:f9959c85576beae5cdcaaf39510b15105f1ee8b70d5dacd90152617f57be8c83 \ + --hash=sha256:fe515bb89d59e1e4b48637a964f480b35c0a2676de24e65e55310f6016cca7ce \ + --hash=sha256:fe71f6b283f4f1832204ab8235ce07adad145052614f77c876fcf0dac97bc06f +packaging==26.0 \ + --hash=sha256:00243ae351a257117b6a241061796684b084ed1c516a08c48a3f7e147a9d80b4 \ + --hash=sha256:b36f1fef9334a5588b4166f8bcd26a14e521f2b55e6b9de3aaa80d3ff7a37529 +peft==0.21.3 \ + --hash=sha256:1fb60533dc417aebd39edb648856530c09419a5027ca0c3ce090d82e82a9c41f \ + --hash=sha256:b3a578733e2e94b00b50a20c107ed2a10a045b922711f078bfa925bc6e64ea2e +pillow==13.0.0 \ + --hash=sha256:02464da86f561f410e13b061ec37c3068a9cb557a095494157742d07b3c24a27 \ + --hash=sha256:04a63720f79e22fd54d897c233a68314c50ca0603360f54ce2bd5db8f0f43782 \ + --hash=sha256:05cd2cd39055d0b9650060e4513ef4a9a0aea870083950bd046a0d6490f93a22 \ + --hash=sha256:06903aac074d00c988e77a1fc435286dc498506d4ca8d6f69df9babddf4ecc15 \ + --hash=sha256:08b826a9bf1265c76de04a42061d61ea6b109418b7826f28ff1ecdfaa26c5502 \ + --hash=sha256:0d1a9cf7bc6917538b20f8d06b9ab2147e542f68849e96fc58eb66bdf6acc692 \ + --hash=sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f \ + --hash=sha256:12b0fa15879fe5a9d9eebe66e4e2d74128a773b1a4448010c9c714f45e04b9d8 \ + --hash=sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13 \ + --hash=sha256:149a1c323ba366f90b48e6f1a6db6582eb50512df374588de56fc909abc0f0f3 \ + --hash=sha256:19b66ca0a4d25cc0200b381ce824c7ea090db61427315e73cfb05dbf1b35c369 \ + --hash=sha256:1c774b9c0ba0d0b356f71530677b39028878a2cae5a93e0a13779cfd17120f88 \ + --hash=sha256:20722cd5375533ad754053363a80b8fb30c79d37930a6f7228030e237ce3bd5d \ + --hash=sha256:20822140c9a2ba9c5e42df342b0a892ab2e102fc0e3db967a133bb9ce3f898bb \ + --hash=sha256:21c32061a5512dc13f87cc7303e120e4d77c2f70df89a35af0e3ce246e5ac57f \ + --hash=sha256:2310e2adfc13c6d457d7d0f2ffdd5c56a74a317650cf765887df8d515a647ac0 \ + --hash=sha256:23edf4ec4b6f4f240e8df6e4985e9ee2ced86474632433e55fb1e2548744bf40 \ + --hash=sha256:2d50500a4a3bc6469adcdb319cf05d688b08ca3bf0f22a05339f3b25b433a599 \ + --hash=sha256:2e31c4e68cffd7b1f116127626813b82fcba19edf6b940a7b0c266d6484d0055 \ + --hash=sha256:34fb3db1149c879343861831728c243c432d4a5afc8f1878ca7612ef8de2a033 \ + --hash=sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061 \ + --hash=sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca \ + --hash=sha256:40a266371ece581e5de13b6635ef78d7487824af80561b6ca27694a88c19bc0f \ + --hash=sha256:42d63be3af4f9b951b199b0a9d23365d37ab14687e6d77b74940432c8515c4ca \ + --hash=sha256:44629d4498c9cb6b2051806155f22141df0d8a929c56134b166655232dfb2f8c \ + --hash=sha256:49c12af515073e9bf511e4ef736743bf70d531a643668722279314b937742ba4 \ + --hash=sha256:4a25756244bdcce3b50580baadf320fa48297f0eeb8e114ba64139a40d4d0fc8 \ + --hash=sha256:4bd024d567eca931b668978d672dba914d4b8e2628e2c3073a2ad178de8a2620 \ + --hash=sha256:4f8db54177035a2b5f717f94475b74907e12a96dc74f6d487f3966b0a4694071 \ + --hash=sha256:51ebb529fc5e8abdd55302f6c3f8943037348ec2384329a3e55677f69ae2fdfc \ + --hash=sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a \ + --hash=sha256:5933fcea5a5ba64c686f55c886a115cbfd92f2900460784a1e79909fdbafd7b6 \ + --hash=sha256:5bdb38ba220b61b4ec31dd1046dea6b016d3c6850a23f43ed8b58332b2fc668e \ + --hash=sha256:5f56499c1a74d2b862beb0c33b8016f99d095858455df9d21583bbbc1c15b582 \ + --hash=sha256:67871a13cf47275201553b536c025da777f997fa562a19eb798af4ad4b97c18f \ + --hash=sha256:67c8d44ad89fa7eb88de5d6ef6199b1e03dd24974f85a67639fc8badb801fe79 \ + --hash=sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5 \ + --hash=sha256:6bce6a29c3898191f4c9998e4d4e8f69790caeabde46e54da4bc235ce5bde683 \ + --hash=sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb \ + --hash=sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c \ + --hash=sha256:7b999816b5850a35ada08443e6e03945f1f6488144a83afe2d37b240a552aafa \ + --hash=sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0 \ + --hash=sha256:7d5e097eabd5d4915c27ac9f6e9325bb1e01a7c94d7348b5c4451d3fc30e8521 \ + --hash=sha256:7e91e97a929232cdb828889ee6ad0e48d7f40f4ec38818f4e4a8968b2b1af22e \ + --hash=sha256:7f6299e494e46253d40c34653cac369412f44ca53b5f85d848d3f95b1ed0546c \ + --hash=sha256:816752a5ef76a80484c8c441c85593b7ea9304f6231fc5776ad1fbff7e773058 \ + --hash=sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2 \ + --hash=sha256:8619685cad8efc4c38c66d3b36aad854523297c43d748b3b6f0cc03c90ba3463 \ + --hash=sha256:8bf295fe459343bc6093c8e5e0df60bfa189e0fcb775a22e2c2488fdeccc6c0d \ + --hash=sha256:8e459b613cf31f8980f584387b4fe47bf08e076e288d61aa8eba1f7fd4ddbb81 \ + --hash=sha256:8f36aa77f74b14a2103622b196402c71330e4e7cf4122ee45c854e9a01e0eecf \ + --hash=sha256:93ff9c9c3663ce23aaa5d0b6b6abac55359e2a0c06c7e30f3771829af816be63 \ + --hash=sha256:9a635068d9793c7f0d929f39f18b58f1bd86c236e8e7b64167b86af9232ebca0 \ + --hash=sha256:9dda0788a9932776a75d8bcc020076edc308ce2508b51f6739a45e3158b3fc42 \ + --hash=sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad \ + --hash=sha256:a2a14cd73d5e6c927f644b0110ee81f59c4ef506259ec9183904747f2caacc81 \ + --hash=sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c \ + --hash=sha256:a6aaa7871aebca081eb5c45f83e845bbd9712ae99fa9286dbfdcee835e63f4b4 \ + --hash=sha256:aa694c49787040943570d61c9b8fc01271bd2a2cfdd55f0d896f8aecdce1a981 \ + --hash=sha256:adb3c2124c68e480f4632d06cb7caa3b48a51678475f483b4edb1c6dee29ea43 \ + --hash=sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039 \ + --hash=sha256:bf97ba1b5542050e9b0c74e632323b6d8136cc99d64e193abebee22fe6013c76 \ + --hash=sha256:c3bc8ee0271387e0b1e3ad0ff893645990a656e79bf9c42f4f734a3642b11d51 \ + --hash=sha256:c50c80e3591e5cf9a8dfa6007d4f10732f02e32263850999286e56ccd650cfb2 \ + --hash=sha256:c6fd031333dedcad7ce3e03d244093f43504f209e86925ebdb2b868fa4037630 \ + --hash=sha256:c87a04e7f152ee4db5dbe15f0bfa3fe628a1aeedbe66b81c43b87f52c813f9ac \ + --hash=sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510 \ + --hash=sha256:d4737f50d23ddd11d6685faacbb9252887dde0bc7997127757247983d74399d6 \ + --hash=sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3 \ + --hash=sha256:d9b0a2bee3f3e03e9f29057aedb807dbf1e1d96ee1b9d0f422d9db6c8583271d \ + --hash=sha256:e65dd6e75de67b2362a4fa3e16aa627595f65054dc4ec73d64680c84d592fa61 \ + --hash=sha256:e892354a424b1e82a78ba16785822bdd40de06f19446a3d4a28047df1a4f8932 \ + --hash=sha256:e8ca8f69b7c77fa96dad99f8638c1fc4f1c0bed4acaa1baf7a3c31bdb80a0ab1 \ + --hash=sha256:e91c2b1cbeae768c98752e67e717e283d68dae45717b41f2d91eaee648e37b7d \ + --hash=sha256:e98b4f91f99b24b1da72e10621ba181f7281922384a7403094debb4199de6c00 \ + --hash=sha256:ef5fe6b7db3f501c56000ba8fe7c7e1a35ca1d45824fbeb95a67daa85cff4dbe \ + --hash=sha256:f11a3c1358bb3c68012a7b1f41b223c3db9f7bfde90b481df028cfe1c3363313 \ + --hash=sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806 \ + --hash=sha256:f7cbb7a64e7ec664775195e4f81923bc8a93d9451b963f844e59118f63147a7a \ + --hash=sha256:f9bd7d260d986f3553518c5d723544346fa48031f8aef3265d786aeb59845bc0 \ + --hash=sha256:fc481f742ccda20e9ed760b8f978dff50f2a4e9bc253ac167fb0a05b0783ef52 \ + --hash=sha256:ff3fe9eb621fbb9db4c4be33ab946f6bac5f98ab50ca8d3260503653656c961b \ + --hash=sha256:ffea6b2986a797c84b6d1d27d4f43e0b83c73fc16281a930891cd237cf0d08fe +propcache==0.5.4 \ + --hash=sha256:004e685b315646c410771836e72a44f143bbe624f29653a42687815069a303d5 \ + --hash=sha256:02c0a34f16889cf800f10f0247a564d8ce6eeab6ffcd7c87198f769067eb8432 \ + --hash=sha256:03969626faf0783a592dfa17e28eac06018bd0b44dafae6943d53b92421a7f72 \ + --hash=sha256:03b229037d25b801e7af53fd52b9fc49d9439b036fca1e087e02780631adfa97 \ + --hash=sha256:0951315a6b3142ee2167404d707743f0157c110091342b1aa0accac5cf0e4acf \ + --hash=sha256:0a095db8e15a6020db149ecbed6461939fe74f6acaa3ae8b702a1fe8c38cd983 \ + --hash=sha256:0c889f6fa84957bc7e8b4eab71fd16a0455068d5045e3aa40c733071d2b2fd77 \ + --hash=sha256:0d21d0d2c82bbfeb1677a9711f38df968f9837576102bb4add1bd449d28d88f1 \ + --hash=sha256:10ef33a68a61ce317e095fd2e202a592ea92392b90944a78c993f0d9a73ab06c \ + --hash=sha256:12682126712ddc19b70ff819debbd279e58adf1f0c8f8f8138c18ade2044b284 \ + --hash=sha256:135036c5cfc93864affb0f9af9a27e5d7a71cb7bd745e7b6dbfc2d56cc30e827 \ + --hash=sha256:13e52b6e0bde97dee98ab66552dbff2931649c96f1ac432eac299fe689ec373b \ + --hash=sha256:141fdbd73748db0cf7636035030aaac383d2efde8f34e7bc24594cc776d225b8 \ + --hash=sha256:146f48a9e4812611a7581003b1a39de56c34967046310c4171a68ef908c9a745 \ + --hash=sha256:174507f82d3594622acb1dd2dafecf2d899d6d506335494e7107767bf05f3aae \ + --hash=sha256:1783582065a1f07f9d9ee1e992e13f15d7dc8fb1eb3a7476d43eb3f2e69d26bb \ + --hash=sha256:17a7400cec0256f0a71ae71f9da398f9894c956ff6668a1c9d317b3367316320 \ + --hash=sha256:1b2f3bec4261a94019575481c726c29850f72e27907773c75b1de421e20e9f9d \ + --hash=sha256:1d759d05634f1b038fb625a66662a8c85e5a8fec912da381b5149ddac107482b \ + --hash=sha256:1df8d8561b21465c5dd56110a01caf897e026d065b4b84e98a488209094272ec \ + --hash=sha256:213bb68d9ced5cf2bf717b1071bf2b09b4b04c426256f9fe6d054c60318424c4 \ + --hash=sha256:23278f808cd81d5ada7184a76606b925fb3389c60e1077b2cd7da7b1fcf0553c \ + --hash=sha256:251c63dd46a0659bb875cb254dc4c1e79ee91a847c737cd62373295afc2235dc \ + --hash=sha256:279655a16973f1ee2bd2fe79973137681642fd9ae0d89215bba263726eb0dc3a \ + --hash=sha256:2814ecd8e818f487bee4b0f921bc4d1c176cc5fc71ac0f072d0fa67eda4ac14b \ + --hash=sha256:286867fb156488c251a3721766e380ac4495e4fd6b51aaa1403d89ce7f4359d9 \ + --hash=sha256:2dba2f02d2d5c09ef8a0e6c1a42aeaa451f4be9898cb00b04fe98717da2eb23b \ + --hash=sha256:30cc1cebaf9aef49db06357a50398323ae04d70460c0491837d026ab7d6452ea \ + --hash=sha256:31eb43ba2edc704ab2ec27815315dd8a19def0fb16215be4cfe8d32fe78ffd51 \ + --hash=sha256:350b272b2279f4135a64fc0c304a5d08e28a137c9573442c606152446638a831 \ + --hash=sha256:36c0d9db44b523ef93d03341b1c42d69ff01d673c053d1b1c6c3a363bcaa39ba \ + --hash=sha256:3af0c8642b2da4815d86e631232ac8286e17644fad907c19508aa8e7cb4ba8ad \ + --hash=sha256:3cd3a7edb6b95b9b33998135ebfa18d709da82290fb8f27c858970b5a12c8b56 \ + --hash=sha256:3d605bb239b796e82a81c6709548b2bd460ab73b4590cb0c83de8a2dd9694d0f \ + --hash=sha256:3e413d7a4a9b4866b7a761d6060d434b64d23cd35122eda3b026a0bbe8196b25 \ + --hash=sha256:3eb2e820e8e2101407da93f17c57cbb7d225461955fc60105daaba14cd421ee2 \ + --hash=sha256:3fa15757fea1dfcd5b7745cad9f4638929605531bd4018ab2adff7955f1a403d \ + --hash=sha256:3fc24f209c1b7f7f688b66b98293954f5504279760999b58920ee12dd8471c1d \ + --hash=sha256:4054acf80d40456a0537f2913b349718649d8d6458a14ab7f48d0ce28c30869d \ + --hash=sha256:40e94adb1e7d39ff28a8bd8d8b8fbd1df6b9f40976dbe379134f1ce058e532dd \ + --hash=sha256:420162a77f94eb1cf5ef7893f500016dabd548e73de956785a1dd899cc73006a \ + --hash=sha256:425f8cc86ab5018b4b8d4a23bc8e74d964bd3d757c3702e301aa79be76c53f6c \ + --hash=sha256:44149f46500a0a41b95b4d99c2e586a77319539730607b9892974a092788b111 \ + --hash=sha256:445ee3bfb46e85838387fb3c536a73cc0b994dc192b004e40e170adc54aa2a7e \ + --hash=sha256:45488d1a5f9ab5bd90aaa1ca20f50fe1922b8ffad71a2009d2adf41355897aac \ + --hash=sha256:45bebbe252550fec975ba3b62bc6f931643cfd3b5464ef47619cf3fef154e01c \ + --hash=sha256:45bf2e730ab8905d0527fe05a86500f406e64305c34cc81ebe64b4617cab9760 \ + --hash=sha256:48cb48c5346a97de792254af77715aa2529c2a1ebc5f586aa0aae44a02f1fe57 \ + --hash=sha256:4a1f4f5ffa55dce6307631f3cb2948e117e665966ea512e0d502b16c24f567e7 \ + --hash=sha256:4cfe0a92ae30151869e67a4b5f5e105e4e03ad30b3f38e5211b5bf77d0881993 \ + --hash=sha256:4d86476a935c88963d9b8e1a9a0d38188790e9622169bfbafa173046846709d3 \ + --hash=sha256:4e985382be6d15da8d0c2710a6fa7b9070fc9ecdeefb7f580e88373984ec8be3 \ + --hash=sha256:4f2d880ff60f45898f4acfa152aac8d04e3ee627d90ff4003491bf92239d5757 \ + --hash=sha256:4fbc1a15dc8cd1689508758d626b372b1f09d28d9577667feaf9e6bfcd8efcbc \ + --hash=sha256:50e337653721d20ead710da33bf44487fbe8a0db8782714b60306481e9f95b51 \ + --hash=sha256:53eaa697c4d0422ff4cb714d00231b43352064d97b944033b30c1d57cc506ec0 \ + --hash=sha256:56fc3f7599528db40b1efa0889a620116e2704144495273d66066e8164e45838 \ + --hash=sha256:58134228927cee6c047d626c08e60a81be604a20578a12ce752cc5c9a84d4826 \ + --hash=sha256:594eb4c6ec35e7179b058481f4e9f02521b56de16fa577c4b85c76fb1bf8a9f8 \ + --hash=sha256:5cacf3c9efd09df409dc33654dd077e1c245ba8fb747b0f0236ef41b7c49b589 \ + --hash=sha256:60a64cbccaa11b7760ce705a14ada17ba459e7ca9f23ba587eb013821032d7ef \ + --hash=sha256:62530ca89187827e4a4fe733f971abe81a7542eeea48ff61995f19b64d7199c8 \ + --hash=sha256:62c60aec739ed00124573cce1178138fd690c7676352d67a37328c1cf51d7468 \ + --hash=sha256:69fc35c0779522da366c563e5faf203ffc1f8ff0021d5b1337fa4efa5be73177 \ + --hash=sha256:6af4693716bfb03f1752ef1b30faa593db2c01d5272e9b8564a1549452a979ab \ + --hash=sha256:6c7599df2b57ebeea8de011b5f2f7b85de95e76037d43d34b95e328430275487 \ + --hash=sha256:6e9368e87a3efc285e559131092c5db643eb8e56de4ee42064d5baec22ef2bb5 \ + --hash=sha256:6f0093ac3e9daada202c2082439d414a625c57184727a46e112a3fb2a81cb788 \ + --hash=sha256:7177c43eddf10a0893c4fec52ebb408fdcd7f7d63962caace9180d8f81b14ece \ + --hash=sha256:720cf832eb2d0b0dfee129cb3335a26f6ce3cc45ee1187e8f0731758caa16792 \ + --hash=sha256:770e8209d018175fc0063936fa9583b6d27e88c5ad31543f3383d66080efdd62 \ + --hash=sha256:7a8d5ff04eb1f85698a78d20c62a14676e7b960dcafde09a388d60ad377d355d \ + --hash=sha256:7b9100a93b372418d8688f3f2a3e5b45c64d70ca4d6176e121aca1e3bfc1e32f \ + --hash=sha256:7cc528e760a8af06f2b13e9b9f362cd90c7c718ea61228a96dbd31ba16ed7f47 \ + --hash=sha256:7ffafcbfc7b549ab940047e505c831eabac5e67de53e1bc174adbc5285c55944 \ + --hash=sha256:87a3caecf8095e48dc72f84bfa42e23a848cf410cc9cc13031fba4869b706a21 \ + --hash=sha256:886b59c4d28ca97dd23b025fdfc50a0356be934efbbbca89ad26230067f86fe5 \ + --hash=sha256:8876b39961e33d912afe3c1bee18ee564fdad0206f873cc15d522756b7f50737 \ + --hash=sha256:897d1ddf6716e8f47200f7aad9a0efa6cc7586df66c6defa572f9eab379c078e \ + --hash=sha256:8a1fc236528c457cd739c88abe823da851b7ab645d72792f88658114cc340c12 \ + --hash=sha256:8a235f73d6e020855dc29dff012d920c02ee0feab8d73a24185a7569f4be1161 \ + --hash=sha256:8f911c395cef73c510bac566da9507bb6a43e7763d0c79138dc60ee53f11207e \ + --hash=sha256:96f7c5c15656040ddcbc51e56dc59b58aa25999d743c126abd425b9766ab43e9 \ + --hash=sha256:978f28401afbc76cdc3df9e1717b4229a06b626a1dcc75db4e1f2beb3884c3e9 \ + --hash=sha256:98914de2c4d7f0f9f4a8c6ea4bf05841f4175796941e3ef7d47eb718f22311fb \ + --hash=sha256:9a2a8a50a93dee0268a860a07fa3b4bd968f8ce4dbd794957da772f395368526 \ + --hash=sha256:9cbfff4423eef4cc6cafc021469641a2b835f610b2647a6c5281903e21b8670d \ + --hash=sha256:9e9ab13760aa8b6d0881ae7cb04fd891d8d490cd2554ea8e79bb278399169bcc \ + --hash=sha256:9f3551b8a35c1df3e7ea4d2d86edee15f0dde1bddd434a71744048683544d0ef \ + --hash=sha256:9f86f7259efe2c951f43e57d471c9b41daa5bfc7db9f67189059cf1ae6d77fd9 \ + --hash=sha256:9fb0a5be8d9aa213150e8d8148a42aca4984b285bcad1e69587dc4298edd929b \ + --hash=sha256:a219f0ac59817a9114dd2aa57c13180f993e819ba658c7ddab4b66ed1ee0d370 \ + --hash=sha256:a419ee85e654927baabda3929c03c0cc1112bf472ff0dfd6142f4e3a81ca4162 \ + --hash=sha256:a4d7a54719b67338a305dca2ce6aafe366817df94ddfd4b5514374356f5ca546 \ + --hash=sha256:a5793c7698a53f56f4a1889a4737c7eeb1b7ad0842fa6b1abca22913ff79c8c1 \ + --hash=sha256:a5e8ef588c109725dc713ba69aadcac00a1ef90c2ce9c0a8c7075128f569f47f \ + --hash=sha256:a74bfa37147cc08fb29df10bd9c16f40fa7f860cd3a6d2fff853323a94f6e17f \ + --hash=sha256:ada748108a43d29b7c328ba7db3755327cd94f028bcc1a7ee3f0addcfacd9c38 \ + --hash=sha256:ae58f361bd5dae942717c65d3413b478c70aea9c462599e7b9adad3731db3894 \ + --hash=sha256:b28f41fa3b8c6900457f858ec5b03998f3a6d535fbc1bb2edec5961ea05ec429 \ + --hash=sha256:b3083bfe87f95c756e610bd8025f26cbd1cd4aaa03a422f2d65efb7a97cd53d8 \ + --hash=sha256:b61805357d966680acf68b3b6d49772631ed9df44ebece10ff1460e117a7da8a \ + --hash=sha256:b77c313314524ca9c38fbd70f73515d04597ac58c40c939bc0e71eeb4abff680 \ + --hash=sha256:bee7d3aed13d56f54e681df38c3a23031bc9e3863f687d9d598825c9146acd7d \ + --hash=sha256:c02c0e570c5c7e077b0181a9f3cdb7d4c3617d1cda6b5c95bd5d34022923d82c \ + --hash=sha256:c174bfd1c48a1b51a3078e95586dde718374bac79719ab3541ec9e74aec40574 \ + --hash=sha256:c2ba30a89035b57b73e00475de948521602f543d79ce01db10b04b36c4c76fc8 \ + --hash=sha256:c3e98c55bde2bcf7db3c70d1aed7ae9aa8aebbf19a250c66645cde44cdb8b867 \ + --hash=sha256:c3ef2818d63bc86071e9d2989ae75a1bc32b8f7059cfd9f5abbbee70c32e2ed6 \ + --hash=sha256:c83acbce9f2b5e3f5f5eda9e53d2001fed22fcdfef81274a9e02d8fd53b70a30 \ + --hash=sha256:c9281e922c072158c91974d4589f1dbe0fee6d467f284c28e463f9f5a4d933f4 \ + --hash=sha256:cc07876cfb079b6f6f36d21ce75784ad6c2c6b563eeac0ed26c2fa2669b85df9 \ + --hash=sha256:ccf4f7a79e26bb7efb06ecd50c177833b71df05cbc748701372325e6bcc17f6f \ + --hash=sha256:cdee8205a44d0be91bbac4c41b95d86641b72dfc7aef1279400e4fda3f26a937 \ + --hash=sha256:ceb3e879afac028f93d272c957814695dc5569e4904262dbee92f6c41bd5e4a3 \ + --hash=sha256:d1f5a500bfcbb2c0ab85e98a0dcd70f5899d34efe365a0187700369a79603031 \ + --hash=sha256:d42a9a856a4a6e2f6c10f1318c07e7daa498d6593abe745c71dae4521a26ca39 \ + --hash=sha256:d83b12902eb8bce151259c86c03ba746600b2d994543de46e370cecf96c452f2 \ + --hash=sha256:d8e017eeb7482bed34cdb0d61cf2bcfc88d104bbab296a17cd16a6af8aabc70e \ + --hash=sha256:db3ae52ccc150dbc84704e9d642743897f3e1c54742ff34cacb661e52e3818a9 \ + --hash=sha256:dbab5f5ff6897c81f355d079010cdae85b02e5a0b518b5251523b8ad8ae9ac3c \ + --hash=sha256:dc4242ca653c9b30ab51c5f8193323e7bc0928f897ee9103201e59a43abcb72e \ + --hash=sha256:dcbf346a318a5e30063f547630b02bb787ce2f45b6368d5da143660b6a3835d8 \ + --hash=sha256:dd2ac8f5b643454c2cc6b6118b13da16e88f4a6434fc3ba61aca384029f04f36 \ + --hash=sha256:e1d52a05dc417279f7e5c7618c5dfbbc29923aaf9bc0a5c1802ddcebf54c61a0 \ + --hash=sha256:e6720ba44ad7e72174314d0e1fb0172494cff5c73a3a8a2159c3d2402ff15565 \ + --hash=sha256:e738ab81179510ce79b2eac9a6ecf47feffd9e76d1c72e403005dddb6e36c06c \ + --hash=sha256:e904d4d01f36bd6e197590be1533c44e06058771e0746dd073a8ebb3ef880858 \ + --hash=sha256:e9f165403b81fea7e89c932d89046a1e3d9a3a60e8d7ef2f249dccdcb0982bf5 \ + --hash=sha256:ec6a85f424afa8d23e0d9a094e5dbb6eda01da91c92b9183cd433768247ffc97 \ + --hash=sha256:ee19113bce2f3acd46432050688b70f61acd6857d75abb9ec96341b7e9ced123 \ + --hash=sha256:ef3b928d9c984322b5c44e6964d8dbc653da87d2d8ee1647fa6da43072e650a9 \ + --hash=sha256:f273dcf7149a50527c4fd1f55cfe9eac0f60753f5af544b4c9352578e20c0874 \ + --hash=sha256:f5470694918830da62fac9e69133b53d23b736d7070e587b27a4a2be37e08e68 \ + --hash=sha256:f574e460d1c8a08384a016fdb09ccf3543433263ed6b2f97104f979e64ea57c2 \ + --hash=sha256:f85915e00dcb1cd9f2f890ead064ed40a27df06f0db65be427b29482ae357572 \ + --hash=sha256:fc2461ecc45f17893f8207e73b46ea8ba93e33630e51cf4af3fbc21d47462b1a \ + --hash=sha256:ff6b113f50bc066a698db5d944d2c6dc7507168dd3341e255a8892fd0715a558 +protobuf==6.33.5 \ + --hash=sha256:3093804752167bcab3998bec9f1048baae6e29505adaf1afd14a37bddede533c \ + --hash=sha256:69915a973dd0f60f31a08b8318b73eab2bd6a392c79184b3612226b0a3f8ec02 \ + --hash=sha256:6ddcac2a081f8b7b9642c09406bc6a4290128fce5f471cddd165960bb9119e5c \ + --hash=sha256:8afa18e1d6d20af15b417e728e9f60f3aa108ee76f23c3b2c07a2c3b546d3afd \ + --hash=sha256:8f04fa32763dcdb4973d537d6b54e615cc61108c7cb38fe59310c3192d29510a \ + --hash=sha256:9b71e0281f36f179d00cbcb119cb19dec4d14a81393e5ea220f64b286173e190 \ + --hash=sha256:a3157e62729aafb8df6da2c03aa5c0937c7266c626ce11a278b6eb7963c4e37c \ + --hash=sha256:a5cb85982d95d906df1e2210e58f8e4f1e3cdc088e52c921a041f9c9a0386de5 \ + --hash=sha256:cbf16ba3350fb7b889fca858fb215967792dc125b35c7976ca4818bee3521cf0 \ + --hash=sha256:d71b040839446bac0f4d162e758bea99c8251161dae9d0983a3b88dee345153b +psutil==7.2.2 \ + --hash=sha256:0746f5f8d406af344fd547f1c8daa5f5c33dbc293bb8d6a16d80b4bb88f59372 \ + --hash=sha256:076a2d2f923fd4821644f5ba89f059523da90dc9014e85f8e45a5774ca5bc6f9 \ + --hash=sha256:11fe5a4f613759764e79c65cf11ebdf26e33d6dd34336f8a337aa2996d71c841 \ + --hash=sha256:1a571f2330c966c62aeda00dd24620425d4b0cc86881c89861fbc04549e5dc63 \ + --hash=sha256:1a7b04c10f32cc88ab39cbf606e117fd74721c831c98a27dc04578deb0c16979 \ + --hash=sha256:1fa4ecf83bcdf6e6c8f4449aff98eefb5d0604bf88cb883d7da3d8d2d909546a \ + --hash=sha256:2edccc433cbfa046b980b0df0171cd25bcaeb3a68fe9022db0979e7aa74a826b \ + --hash=sha256:7b6d09433a10592ce39b13d7be5a54fbac1d1228ed29abc880fb23df7cb694c9 \ + --hash=sha256:8c233660f575a5a89e6d4cb65d9f938126312bca76d8fe087b947b3a1aaac9ee \ + --hash=sha256:917e891983ca3c1887b4ef36447b1e0873e70c933afc831c6b6da078ba474312 \ + --hash=sha256:ab486563df44c17f5173621c7b198955bd6b613fb87c71c161f827d3fb149a9b \ + --hash=sha256:ae0aefdd8796a7737eccea863f80f81e468a1e4cf14d926bd9b6f5f2d5f90ca9 \ + --hash=sha256:b0726cecd84f9474419d67252add4ac0cd9811b04d61123054b9fb6f57df6e9e \ + --hash=sha256:b58fabe35e80b264a4e3bb23e6b96f9e45a3df7fb7eed419ac0e5947c61e47cc \ + --hash=sha256:c7663d4e37f13e884d13994247449e9f8f574bc4655d509c3b95e9ec9e2b9dc1 \ + --hash=sha256:e452c464a02e7dc7822a05d25db4cde564444a67e58539a00f929c51eddda0cf \ + --hash=sha256:e78c8603dcd9a04c7364f1a3e670cea95d51ee865e4efb3556a3a63adef958ea \ + --hash=sha256:eb7e81434c8d223ec4a219b5fc1c47d0417b12be7ea866e24fb5ad6e84b3d988 \ + --hash=sha256:ed0cace939114f62738d808fdcecd4c869222507e266e574799e9c0faa17d486 \ + --hash=sha256:eed63d3b4d62449571547b60578c5b2c4bcccc5387148db46e0c2313dad0ee00 \ + --hash=sha256:fd04ef36b4a6d599bbdb225dd1d3f51e00105f6d48a28f006da7f9822f2606d8 +pycparser==3.12 \ + --hash=sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e \ + --hash=sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6 +pydantic==2.13.5 \ + --hash=sha256:346a034f080da3755d8e9cb5e00e8b07de1d39e4f6e2c87d8ab7cafa0b269a73 \ + --hash=sha256:51a9c5f7b2f8e636f04c6cada605d9b6a3bf1348fdf945a3d8869b19bba0ee08 +pydantic-core==2.46.5 \ + --hash=sha256:013d6f3483d81e02e7c328831808f336c8596ee33b4bd4026b9ffb1e960b8942 \ + --hash=sha256:03b9666e41e35d8909852ba191a0607520f81b74eaf12ccf8737005dbb313821 \ + --hash=sha256:045ab3b6d308439e32b81cc173bba5b9018bc6ed896afd0c65b3b009b1699af5 \ + --hash=sha256:0bddb4020d8f04175865ccd17eff3040874fc11fb593f424edb452653b4b947c \ + --hash=sha256:0cdbada856a1c69a7624a64d3d9aefe79300bd6ef827b43a4f265010b9b55184 \ + --hash=sha256:0fc5be0abd4a407e200d844b404e33639a554e7bd0d448e7b9ae181be4789ac2 \ + --hash=sha256:10416c15b8839ecc4ef4d0885da76da6fd0f67333a0eb8aff6d93c4b8f2910fc \ + --hash=sha256:15f4a94963c95accac15b7b657bb177d3ad82bb90b0d0526d9a9b85079925db5 \ + --hash=sha256:18a09e1e1011b462f2e32774f25859ef1223d5c2b0546a633cf56654710721e0 \ + --hash=sha256:193375f3548919d3f0b60936ca113ada3e38f264f91b9b8e0508efaad57be931 \ + --hash=sha256:1a353f84de772f423b5ffb11d7ae352fbbef0f446f3c0b0af0f8236d7233606e \ + --hash=sha256:1e449def1945a462c464331254e5a44fca7c3b4f9aedf59ec2f50f8066dd8e25 \ + --hash=sha256:1e5aad1220a1192c42341c8fd4a8686657e73ab2a920c970bdc4de334fe3193d \ + --hash=sha256:200aa3dc9f8d54f0754f43247c0bad0999fdcfbfd2488384dd44f37279271fe6 \ + --hash=sha256:2471fd51c61c610e1dcf7de44d7299283661654d11264ab4802b303368d69c47 \ + --hash=sha256:24922243639cbdac66c75fcb6fd6495a9cb52b213d62f9a0d16f0310b1ff8038 \ + --hash=sha256:28a6a556cd3b6066bea827857f9d9cce027c96f776e512f544a581f9e42161f8 \ + --hash=sha256:2bc9419666990c06d7397831f2126a1ecc3594aaa3ff7de5bf2d066802f4e07b \ + --hash=sha256:2cbd9a5eff05e51c447c34dfa4632145b26b09120cf04bd0c871e44c1a5e1c9a \ + --hash=sha256:2d330aaba8621b1edcec8ae2c4050f63b84ccf6d98723a8f212e9684713abf0e \ + --hash=sha256:2d5d76654becf5efd62c9e51c3756c67b49498b0c9a40884934c40807adbd074 \ + --hash=sha256:337639ba62a11acde6ef3aeb08c8ea755f8ef1fe5e513356c0f36a2b0d7568b0 \ + --hash=sha256:347ec774390c87326a2e4929d58d3f7e8763a104d5d35f4cd595a4c952366433 \ + --hash=sha256:356c8368cbc321050b169595683a2e1d63413b1e0e2868b330af9fc14c616d3f \ + --hash=sha256:37ae34309d7bd8c0d61ab839668058f2a7962ea1fc51d105d2db228fe0618034 \ + --hash=sha256:37ea7b83c935e5b0d68c9449b82651accf78a10828b2c02b2f2d9e9496446c21 \ + --hash=sha256:3a3e26b6a8274211bddee2d0e4d0d42778f17a34510f49d2ec44b58abfc41736 \ + --hash=sha256:3aa166e99c4f2985407fb8714aebede877ecb5455cf321b606adca926d30d5a0 \ + --hash=sha256:3d2652072b2d774947ba5cf78a9e59644ac62ee572daf6dd2e1dfe905e15b2b7 \ + --hash=sha256:40375c2d05acec10323e45dfe2077ac44bc74659008614af5069034e2cfc781c \ + --hash=sha256:413a717a410d0c817ef5b786a059415550b3794e1d0c2abffd9efb93a3d9f7b4 \ + --hash=sha256:46c25dda9d092a06c08db76ffe0a197107904d0dfac653f7d5306bbcd6d6119c \ + --hash=sha256:49776eab08766a08dfff7012f8b422dcd7e25e43b316eedf0477c24fcfa84b7c \ + --hash=sha256:4d44cf99ddebf875f9b68cc267aa684c99b7b44fe63ee1cac4ec163807290069 \ + --hash=sha256:4dedce55295becb61921e386b99d4f2706045306e7fa52249a33004c837379fb \ + --hash=sha256:4f8507560a9284e1370bb048ed4282012fbef4e8d109875b95e884d228552061 \ + --hash=sha256:4fdc8b93a41521988916eeaa271173fcca7fa0803d62f87675aac8dcec1c8e29 \ + --hash=sha256:5086029a57366b8cf81b130a43908738095c270c21a8d7f0e8bdfdb89718e2f3 \ + --hash=sha256:52e24eacdb536cade636aa90fb851835222becff8484b7001fdc78cb0290f2aa \ + --hash=sha256:53feb344243bb9510a9dec7bf3cf1b64d88a98af5dc7872a5160465f8b198c8e \ + --hash=sha256:545f26c504b27c3758439a5e6d9349931f0a04f855668d5fe323c89e82300a38 \ + --hash=sha256:54d510bac3ee52247af28ed4bb18a1e799f040ac60fd2bf5ccd4c92f1fbe786f \ + --hash=sha256:5cb482e9e84c851f4e623fe4acc1ced89168cf1fe18f7089db4548c8f5bbb65b \ + --hash=sha256:5e81740c09e310f5aa5cbd3e434a01c154d4bef93241c7877b39f211d2b78ba8 \ + --hash=sha256:5ee239d575f80b08eca11f6e20f90c4c695de7825c67eefe6091fbf20dda648e \ + --hash=sha256:5f194189415698233dd1114a093a9b56e61e2c57e11b469be3b0506f46f0771c \ + --hash=sha256:5f93c5fe914d75fbec9a49209b00da5f08e9e467d69da2b1510c81940cfd10be \ + --hash=sha256:657b40d6240c0a7b6a64b30f22d1e3aa631c7e846c621b0c0f6d1d75e2e15ea6 \ + --hash=sha256:6d30e1a4f138b8951063e9a394752a9179b51da288ffa507b1e659222f4c1793 \ + --hash=sha256:6f7b393a8b3da82f5c1fc0751e6d01ac6c55b93c18226a60bdfba4a724efafd1 \ + --hash=sha256:701b2e04b560eeb4bddf7a25ab8ca476176e34fdbd9a0e18196f0d12d4685f0b \ + --hash=sha256:771cf63ae0b1b50dd22e5f3e3549fab5f3f4ff1635d352a9e1a97fe01c7b2e64 \ + --hash=sha256:79bdfa52f843137045b2d081cc05c120ba6665d29b7559c2c47690906f39279f \ + --hash=sha256:7ac031912d54f3d83ef3b3eb98dfabc1608802e2202263d25957eeed40b94761 \ + --hash=sha256:7b0fc826b16c55e561e5d2a0c5c77b051ba1d92808118c4e4b5390f5e0cf191d \ + --hash=sha256:7c6be839a5a8312626b32029a415644a0846b420bc8b52b95b28cd92da162168 \ + --hash=sha256:816ff0a6550ffc06c098ccd2e0698600f9aa7da192a79eaa6f9af504a35db869 \ + --hash=sha256:82a36973cf8a2ef5406f4fe2edbf8ed0c99629535d959e0b100c76a32535a111 \ + --hash=sha256:837b396ca3d7b74091ca623f6cbd8351bd42d670a79c2683e79fb089f06a2de5 \ + --hash=sha256:850a08d167dde16db8702c274f320c7be9d7da6f6dff2b58b18f9e815bd94f5b \ + --hash=sha256:8816f3d218beb4b787de5c9759c259b8fa61f9dec42dc7811f320a33771778b7 \ + --hash=sha256:892a881d5f68c2b9ea304b7a6c2c60d9343df578a311b0f86b94bc8f1ffe8129 \ + --hash=sha256:895395f8918627b04efb1ad2a4cf605387143300ba03304cd1dfa6d03f5e095e \ + --hash=sha256:8b10e3e8fd7ddc2bd915848a2768e44c15b22936f1cc54c462ad1164deb02655 \ + --hash=sha256:8e24d8f05fa2d28513d94e877e9c75ad66175376209b3977f916e240e623193c \ + --hash=sha256:8feeac04b5794e513e710af2f9c87d49f31a6dc47967bb264a1fed61a8989bec \ + --hash=sha256:9432f3598db432cb51c5b37fdbf29a60fcccc79e30d37a05022776a6bc4ab689 \ + --hash=sha256:976e1128455aa595ea04c79ccfedff1aaeab96ee013fcc916bed120c4f0ad94f \ + --hash=sha256:978e7b97d4824b5be09c69fb70507cbde3b0323fc147332ca40a94d9a6a0ebbf \ + --hash=sha256:97bf8de4d541598c94a59344eeb988a94c08ff76b5723c41f6567ec18c7892ea \ + --hash=sha256:97cf3eb53a8cccacf9d46686a0926186c9bfb5574f2ed66d3639d5fe117cd3a9 \ + --hash=sha256:9b68938dd5b0c783d88ff8e2dcc69451b5eb936fe212d516b21b9d5567f6d464 \ + --hash=sha256:9c4b71f10dd532fb7a5cbc8f58707779e64f03a258c2bf8bfbaecfcd9970b519 \ + --hash=sha256:9f47b8a949e60f027f0aa0a6f6c7b7e9c55cbf4380d10b344e282fa4e7ab1e1b \ + --hash=sha256:a1dee1b804ff4d11c663636cf15d2ea47e9f79cd56c033fb1cbf08924842a48f \ + --hash=sha256:a2468d93d181667a7abd66e1b64bb9f76f361b0fef8faddf687456453576f5ee \ + --hash=sha256:a2a5e1d0ff29adddc9f6d6821a66302e4493f8ca898b715b6b1182c2c201ea0a \ + --hash=sha256:a39ac25a9a2fa4072efdb429833c4a4c8009a51ff9eea3eeae131713cd27991e \ + --hash=sha256:a445486499897b88a7d6c310c88ed64dd37b1b59bfd7ae9107490bbb362f47d6 \ + --hash=sha256:a91c17edf6eea2402cb5457b4c89e99bc5ed1004aa34c4adf1d4258c1a5c22c2 \ + --hash=sha256:ab4b66edffb32d9e951efb3814bd104b8367a7501b81b955cacb5726d897389f \ + --hash=sha256:aca6c767f552b21b10f774aeac128e828eafb796adfa1b666a18bf6321453c3a \ + --hash=sha256:acf8a67ba51f4ca9ddbd0e6b3000a65ac51ab734661778b3e7ba64d99a710f2f \ + --hash=sha256:b10ec717381bdbfafef34607824db4c91de69ff085e4fca3b2af91b4fa17e68a \ + --hash=sha256:b49924c73a235e969511bf2aabdff3beebf9820931f646c80274d5d780010c47 \ + --hash=sha256:b6acfb46a814762367fb7ba0828b0a17d441b92ce249a0e007474c9072662dda \ + --hash=sha256:b7ca9034437b6022f941f4857459562ee00a560b97e7cce8a0ec5a74fc6766e0 \ + --hash=sha256:b98134087d9de723658d17a42c7d0da8d6e2ef08015dee7dc93889047315f5e4 \ + --hash=sha256:b9fe6fb92520e3fd61f2e49000b6911b188824f089b75973ea06d6267f0b476d \ + --hash=sha256:bce57638e08ac148e5778cce7feb968307a727d66f8e2274a543d0cf0c9ad6a3 \ + --hash=sha256:c14ad3bdc85ee7f318742c457ca3968a92126d144b15721c759033bfb06296c2 \ + --hash=sha256:c1c43ad4339643d70ebb8124e1305a7dab423001eff58bb41a0f731adbc98355 \ + --hash=sha256:c3471e5c4a949c26ec00a77f01df59096aa9495877de76fd60a980f8ee6be461 \ + --hash=sha256:c583b927a8838dab890706a6fa7573fbb8b70e24000ef9f7238e2d6f6435a5ed \ + --hash=sha256:c76fe65e607be28c7fd4d56fc3c42b1583aa058ce3408b7ad0fd540171d31f9f \ + --hash=sha256:c7ea57fc63aa7da93a1bd2d644e6577befae10c52c4e36377635eea1056a74f5 \ + --hash=sha256:cd5214352ae68f3b5e9af7768bdc5253695ee069675db3480518420b3be881f2 \ + --hash=sha256:cdbb78909f52b981d3b2d56b97328d71eb0b974c36bd77c920123a7ebb192829 \ + --hash=sha256:cdc8b74ecc48c0cb1e9607a05ec4e9e88db60a19ffcc9a1d5f9088ede40c8dc0 \ + --hash=sha256:d0a24b40877af2de4950252be9d21eaf7fb07660f3c2cae1f56c6b599ada5266 \ + --hash=sha256:d22a945598fb91236b4dd793a6e42e4f3dd7740bb5aace5ebd7d4c08d13bb575 \ + --hash=sha256:d2f9fc07a8042a8f95925b35c4f04f469707c981fc33245b6ca187cf5d2dd290 \ + --hash=sha256:d625a186a65201c23a9e3b8ed9c47e90a026e03256608cc91851c6709096844f \ + --hash=sha256:d925f3d9afd05a8c0fb3a1031463a8d59ebe5e2afad297e29c78be19e13b4e62 \ + --hash=sha256:e64e88d5585bea9ce95861079de72006c7fa6d3df4e3a3b65ba31eb979c15c9f \ + --hash=sha256:e652ab17569c94bff5475520f907b7148b8c24036a8ebbe5cf7cf7493d28579a \ + --hash=sha256:e7b891faeedeafba41b2983e5001a81b6a915b69544c7e7570d1989ce1c36ac7 \ + --hash=sha256:e80675d75ae2cd14372cb65cad5400d9347a3d3f6c13000183f22dfd027283ed \ + --hash=sha256:e9c134bb666dd54b778b9fc0d2b50cbb7f979b9e3716f26a88c9ab3b6fc1dd0f \ + --hash=sha256:eb7d8d0e5886a89a55d2eef490e272fa965a9d57c6b29a5b5088a7997ec2cad1 \ + --hash=sha256:ecb42011e12ee19cafbc312887cbf3546959fe02fbad44f272d4be5baa997615 \ + --hash=sha256:ef3fbbf161dc9351a2fe0422e51b129f9e97e42385bd0320b309c15f7d287dd8 \ + --hash=sha256:efd62a42486f1bda5d24cb4f63d15a3c7768375fe83d36f9417b4ad7a2fb20b3 \ + --hash=sha256:f077d0b97ab11fa7dcc633fca53515f290bca8a8a633e966d5b6d1879d9ed01a \ + --hash=sha256:f332f0e72a5a0400141f830744e141bf9f97917878dbe968669e8a7fefea78ff \ + --hash=sha256:f7b0ec93a2893de856652154d73b7ba622f26fa97726487dcac373de5f4c6084 \ + --hash=sha256:fa10ef4112775900e7a0661068635eb67b2ab824fbde764de6e0e21982a93db0 \ + --hash=sha256:fc5d783bd4a2387e97b8a2d5ec781cfb92b3d893bf82370548e99db5915935d3 \ + --hash=sha256:fc8515076c11f3cfdf4fb142dcca0fe384b1230a3b5415458ac84f3e0903ec13 \ + --hash=sha256:ff218293c9c806138dca139765e3b067621be52bcd93cdc14c7711be7ddc90a9 +pygments==2.21.0 \ + --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \ + --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c +pyparsing==3.3.2 \ + --hash=sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d \ + --hash=sha256:c777f4d763f140633dcb6d8a3eda953bf7a214dc4eff598413c070bcdc117cbc +python-dateutil==2.9.0.post0 \ + --hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \ + --hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427 +pytorch-lightning==2.6.6 \ + --hash=sha256:52c52b20522dd3d3feb3bb3aae2dbe3f291e8e836d4111a74cfd72e9df018834 \ + --hash=sha256:71f95c7b22f25c4f91cc659e1734bcdc6c69c8b66543f2ed2d78dbe29ce2f167 +pyyaml==6.0.3 \ + --hash=sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c \ + --hash=sha256:0150219816b6a1fa26fb4699fb7daa9caf09eb1999f3b70fb6e786805e80375a \ + --hash=sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3 \ + --hash=sha256:02ea2dfa234451bbb8772601d7b8e426c2bfa197136796224e50e35a78777956 \ + --hash=sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6 \ + --hash=sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c \ + --hash=sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65 \ + --hash=sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a \ + --hash=sha256:1ebe39cb5fc479422b83de611d14e2c0d3bb2a18bbcb01f229ab3cfbd8fee7a0 \ + --hash=sha256:214ed4befebe12df36bcc8bc2b64b396ca31be9304b8f59e25c11cf94a4c033b \ + --hash=sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1 \ + --hash=sha256:22ba7cfcad58ef3ecddc7ed1db3409af68d023b7f940da23c6c2a1890976eda6 \ + --hash=sha256:27c0abcb4a5dac13684a37f76e701e054692a9b2d3064b70f5e4eb54810553d7 \ + --hash=sha256:28c8d926f98f432f88adc23edf2e6d4921ac26fb084b028c733d01868d19007e \ + --hash=sha256:2e71d11abed7344e42a8849600193d15b6def118602c4c176f748e4583246007 \ + --hash=sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310 \ + --hash=sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4 \ + --hash=sha256:3c5677e12444c15717b902a5798264fa7909e41153cdf9ef7ad571b704a63dd9 \ + --hash=sha256:3ff07ec89bae51176c0549bc4c63aa6202991da2d9a6129d7aef7f1407d3f295 \ + --hash=sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea \ + --hash=sha256:418cf3f2111bc80e0933b2cd8cd04f286338bb88bdc7bc8e6dd775ebde60b5e0 \ + --hash=sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e \ + --hash=sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac \ + --hash=sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9 \ + --hash=sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7 \ + --hash=sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35 \ + --hash=sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb \ + --hash=sha256:5cf4e27da7e3fbed4d6c3d8e797387aaad68102272f8f9752883bc32d61cb87b \ + --hash=sha256:5e0b74767e5f8c593e8c9b5912019159ed0533c70051e9cce3e8b6aa699fcd69 \ + --hash=sha256:5ed875a24292240029e4483f9d4a4b8a1ae08843b9c54f43fcc11e404532a8a5 \ + --hash=sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b \ + --hash=sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c \ + --hash=sha256:6344df0d5755a2c9a276d4473ae6b90647e216ab4757f8426893b5dd2ac3f369 \ + --hash=sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd \ + --hash=sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824 \ + --hash=sha256:66291b10affd76d76f54fad28e22e51719ef9ba22b29e1d7d03d6777a9174198 \ + --hash=sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065 \ + --hash=sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c \ + --hash=sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c \ + --hash=sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764 \ + --hash=sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196 \ + --hash=sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b \ + --hash=sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00 \ + --hash=sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac \ + --hash=sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8 \ + --hash=sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e \ + --hash=sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28 \ + --hash=sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3 \ + --hash=sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5 \ + --hash=sha256:9c57bb8c96f6d1808c030b1687b9b5fb476abaa47f0db9c0101f5e9f394e97f4 \ + --hash=sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b \ + --hash=sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf \ + --hash=sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5 \ + --hash=sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702 \ + --hash=sha256:b30236e45cf30d2b8e7b3e85881719e98507abed1011bf463a8fa23e9c3e98a8 \ + --hash=sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788 \ + --hash=sha256:b865addae83924361678b652338317d1bd7e79b1f4596f96b96c77a5a34b34da \ + --hash=sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d \ + --hash=sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc \ + --hash=sha256:bdb2c67c6c1390b63c6ff89f210c8fd09d9a1217a465701eac7316313c915e4c \ + --hash=sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba \ + --hash=sha256:c2514fceb77bc5e7a2f7adfaa1feb2fb311607c9cb518dbc378688ec73d8292f \ + --hash=sha256:c3355370a2c156cffb25e876646f149d5d68f5e0a3ce86a5084dd0b64a994917 \ + --hash=sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5 \ + --hash=sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26 \ + --hash=sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f \ + --hash=sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b \ + --hash=sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be \ + --hash=sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c \ + --hash=sha256:efd7b85f94a6f21e4932043973a7ba2613b059c4a000551892ac9f1d11f5baf3 \ + --hash=sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6 \ + --hash=sha256:fa160448684b4e94d80416c0fa4aac48967a969efe22931448d853ada8baf926 \ + --hash=sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0 +regex==2026.1.15 \ + --hash=sha256:0057de9eaef45783ff69fa94ae9f0fd906d629d0bd4c3217048f46d1daa32e9b \ + --hash=sha256:008b185f235acd1e53787333e5690082e4f156c44c87d894f880056089e9bc7c \ + --hash=sha256:05d75a668e9ea16f832390d22131fe1e8acc8389a694c8febc3e340b0f810b93 \ + --hash=sha256:069f56a7bf71d286a6ff932a9e6fb878f151c998ebb2519a9f6d1cee4bffdba3 \ + --hash=sha256:0751a26ad39d4f2ade8fe16c59b2bf5cb19eb3d2cd543e709e583d559bd9efde \ + --hash=sha256:08df9722d9b87834a3d701f3fca570b2be115654dbfd30179f30ab2f39d606d3 \ + --hash=sha256:0bda75ebcac38d884240914c6c43d8ab5fb82e74cde6da94b43b17c411aa4c2b \ + --hash=sha256:0bf065240704cb8951cc04972cf107063917022511273e0969bdb34fc173456c \ + --hash=sha256:0bf650f26087363434c4e560011f8e4e738f6f3e029b85d4904c50135b86cfa5 \ + --hash=sha256:0dcd31594264029b57bf16f37fd7248a70b3b764ed9e0839a8f271b2d22c0785 \ + --hash=sha256:0f0c7684c7f9ca241344ff95a1de964f257a5251968484270e91c25a755532c5 \ + --hash=sha256:124dc36c85d34ef2d9164da41a53c1c8c122cfb1f6e1ec377a1f27ee81deb794 \ + --hash=sha256:164759aa25575cbc0651bef59a0b18353e54300d79ace8084c818ad8ac72b7d5 \ + --hash=sha256:166551807ec20d47ceaeec380081f843e88c8949780cd42c40f18d16168bed10 \ + --hash=sha256:1704d204bd42b6bb80167df0e4554f35c255b579ba99616def38f69e14a5ccb9 \ + --hash=sha256:18388a62989c72ac24de75f1449d0fb0b04dfccd0a1a7c1c43af5eb503d890f6 \ + --hash=sha256:194312a14819d3e44628a44ed6fea6898fdbecb0550089d84c403475138d0a09 \ + --hash=sha256:1ae6020fb311f68d753b7efa9d4b9a5d47a5d6466ea0d5e3b5a471a960ea6e4a \ + --hash=sha256:1cb740d044aff31898804e7bf1181cc72c03d11dfd19932b9911ffc19a79070a \ + --hash=sha256:1e1808471fbe44c1a63e5f577a1d5f02fe5d66031dcbdf12f093ffc1305a858e \ + --hash=sha256:1e8cd52557603f5c66a548f69421310886b28b7066853089e1a71ee710e1cdc1 \ + --hash=sha256:21ca32c28c30d5d65fc9886ff576fc9b59bbca08933e844fa2363e530f4c8218 \ + --hash=sha256:2748c1ec0663580b4510bd89941a31560b4b439a0b428b49472a3d9944d11cd8 \ + --hash=sha256:27618391db7bdaf87ac6c92b31e8f0dfb83a9de0075855152b720140bda177a2 \ + --hash=sha256:2a8d7b50c34578d0d3bf7ad58cde9652b7d683691876f83aedc002862a35dc5e \ + --hash=sha256:2b091aefc05c78d286657cd4db95f2e6313375ff65dcf085e42e4c04d9c8d410 \ + --hash=sha256:2c2b80399a422348ce5de4fe40c418d6299a0fa2803dd61dc0b1a2f28e280fcf \ + --hash=sha256:2f2775843ca49360508d080eaa87f94fa248e2c946bbcd963bb3aae14f333413 \ + --hash=sha256:3038a62fc7d6e5547b8915a3d927a0fbeef84cdbe0b1deb8c99bbd4a8961b52a \ + --hash=sha256:32655d17905e7ff8ba5c764c43cb124e34a9245e45b83c22e81041e1071aee10 \ + --hash=sha256:343db82cb3712c31ddf720f097ef17c11dab2f67f7a3e7be976c4f82eba4e6df \ + --hash=sha256:3601ffb5375de85a16f407854d11cca8fe3f5febbe3ac78fb2866bb220c74d10 \ + --hash=sha256:3d6ce5ae80066b319ae3bc62fd55a557c9491baa5efd0d355f0de08c4ba54e79 \ + --hash=sha256:3d7d92495f47567a9b1669c51fc8d6d809821849063d168121ef801bbc213846 \ + --hash=sha256:40c86d8046915bb9aeb15d3f3f15b6fd500b8ea4485b30e1bbc799dab3fe29f8 \ + --hash=sha256:4161d87f85fa831e31469bfd82c186923070fc970b9de75339b68f0c75b51903 \ + --hash=sha256:41aef6f953283291c4e4e6850607bd71502be67779586a61472beacb315c97ec \ + --hash=sha256:453078802f1b9e2b7303fb79222c054cb18e76f7bdc220f7530fdc85d319f99e \ + --hash=sha256:492534a0ab925d1db998defc3c302dae3616a2fc3fe2e08db1472348f096ddf2 \ + --hash=sha256:4c5ef43b5c2d4114eb8ea424bb8c9cec01d5d17f242af88b2448f5ee81caadbc \ + --hash=sha256:4c8fcc5793dde01641a35905d6731ee1548f02b956815f8f1cab89e515a5bdf1 \ + --hash=sha256:4def140aa6156bc64ee9912383d4038f3fdd18fee03a6f222abd4de6357ce42a \ + --hash=sha256:4e3dd93c8f9abe8aa4b6c652016da9a3afa190df5ad822907efe6b206c09896e \ + --hash=sha256:505831646c945e3e63552cc1b1b9b514f0e93232972a2d5bedbcc32f15bc82e3 \ + --hash=sha256:5170907244b14303edc5978f522f16c974f32d3aa92109fabc2af52411c9433b \ + --hash=sha256:55b4ea996a8e4458dd7b584a2f89863b1655dd3d17b88b46cbb9becc495a0ec5 \ + --hash=sha256:55e9d0118d97794367309635df398bdfd7c33b93e2fdfa0b239661cd74b4c14e \ + --hash=sha256:56a5595d0f892f214609c9f76b41b7428bed439d98dc961efafdd1354d42baae \ + --hash=sha256:57e7d17f59f9ebfa9667e6e5a1c0127b96b87cb9cede8335482451ed00788ba4 \ + --hash=sha256:5ef19071f4ac9f0834793af85bd04a920b4407715624e40cb7a0631a11137cdf \ + --hash=sha256:5ff818702440a5878a81886f127b80127f5d50563753a28211482867f8318106 \ + --hash=sha256:619843841e220adca114118533a574a9cd183ed8a28b85627d2844c500a2b0db \ + --hash=sha256:621f73a07595d83f28952d7bd1e91e9d1ed7625fb7af0064d3516674ec93a2a2 \ + --hash=sha256:693b465171707bbe882a7a05de5e866f33c76aa449750bee94a8d90463533cc9 \ + --hash=sha256:6bfc31a37fd1592f0c4fc4bfc674b5c42e52efe45b4b7a6a14f334cca4bcebe4 \ + --hash=sha256:6d220a2517f5893f55daac983bfa9fe998a7dbcaee4f5d27a88500f8b7873788 \ + --hash=sha256:6e42844ad64194fa08d5ccb75fe6a459b9b08e6d7296bd704460168d58a388f3 \ + --hash=sha256:726ea4e727aba21643205edad8f2187ec682d3305d790f73b7a51c7587b64bdd \ + --hash=sha256:74f45d170a21df41508cb67165456538425185baaf686281fa210d7e729abc34 \ + --hash=sha256:7dcc02368585334f5bc81fc73a2a6a0bbade60e7d83da21cead622faf408f32c \ + --hash=sha256:7e1e28be779884189cdd57735e997f282b64fd7ccf6e2eef3e16e57d7a34a815 \ + --hash=sha256:7ef7d5d4bd49ec7364315167a4134a015f61e8266c6d446fc116a9ac4456e10d \ + --hash=sha256:8050ba2e3ea1d8731a549e83c18d2f0999fbc99a5f6bd06b4c91449f55291804 \ + --hash=sha256:82345326b1d8d56afbe41d881fdf62f1926d7264b2fc1537f99ae5da9aad7913 \ + --hash=sha256:8355ad842a7c7e9e5e55653eade3b7d1885ba86f124dd8ab1f722f9be6627434 \ + --hash=sha256:86c1077a3cc60d453d4084d5b9649065f3bf1184e22992bd322e1f081d3117fb \ + --hash=sha256:87adf5bd6d72e3e17c9cb59ac4096b1faaf84b7eb3037a5ffa61c4b4370f0f13 \ + --hash=sha256:8db052bbd981e1666f09e957f3790ed74080c2229007c1dd67afdbf0b469c48b \ + --hash=sha256:8dd16fba2758db7a3780a051f245539c4451ca20910f5a5e6ea1c08d06d4a76b \ + --hash=sha256:8e32f7896f83774f91499d239e24cebfadbc07639c1494bb7213983842348337 \ + --hash=sha256:91c5036ebb62663a6b3999bdd2e559fd8456d17e2b485bf509784cd31a8b1705 \ + --hash=sha256:9250d087bc92b7d4899ccd5539a1b2334e44eee85d848c4c1aef8e221d3f8c8f \ + --hash=sha256:9479cae874c81bf610d72b85bb681a94c95722c127b55445285fb0e2c82db8e1 \ + --hash=sha256:968c14d4f03e10b2fd960f1d5168c1f0ac969381d3c1fcc973bc45fb06346599 \ + --hash=sha256:97499ff7862e868b1977107873dd1a06e151467129159a6ffd07b66706ba3a9f \ + --hash=sha256:99ad739c3686085e614bf77a508e26954ff1b8f14da0e3765ff7abbf7799f952 \ + --hash=sha256:9d787e3310c6a6425eb346be4ff2ccf6eece63017916fd77fe8328c57be83521 \ + --hash=sha256:a1774cd1981cd212506a23a14dba7fdeaee259f5deba2df6229966d9911e767a \ + --hash=sha256:a30a68e89e5a218b8b23a52292924c1f4b245cb0c68d1cce9aec9bbda6e2c160 \ + --hash=sha256:adc97a9077c2696501443d8ad3fa1b4fc6d131fc8fd7dfefd1a723f89071cf0a \ + --hash=sha256:b0d190e6f013ea938623a58706d1469a62103fb2a241ce2873a9906e0386582c \ + --hash=sha256:b10e42a6de0e32559a92f2f8dc908478cc0fa02838d7dbe764c44dca3fa13569 \ + --hash=sha256:b2a13dd6a95e95a489ca242319d18fc02e07ceb28fa9ad146385194d95b3c829 \ + --hash=sha256:b30bcbd1e1221783c721483953d9e4f3ab9c5d165aa709693d3f3946747b1aea \ + --hash=sha256:b325d4714c3c48277bfea1accd94e193ad6ed42b4bad79ad64f3b8f8a31260a5 \ + --hash=sha256:b5a28980a926fa810dbbed059547b02783952e2efd9c636412345232ddb87ff6 \ + --hash=sha256:b5f7d8d2867152cdb625e72a530d2ccb48a3d199159144cbdd63870882fb6f80 \ + --hash=sha256:bfb0d6be01fbae8d6655c8ca21b3b72458606c4aec9bbc932db758d47aba6db1 \ + --hash=sha256:bfd876041a956e6a90ad7cdb3f6a630c07d491280bfeed4544053cd434901681 \ + --hash=sha256:c08c1f3e34338256732bd6938747daa3c0d5b251e04b6e43b5813e94d503076e \ + --hash=sha256:c243da3436354f4af6c3058a3f81a97d47ea52c9bd874b52fd30274853a1d5df \ + --hash=sha256:c32bef3e7aeee75746748643667668ef941d28b003bfc89994ecf09a10f7a1b5 \ + --hash=sha256:c661fc820cfb33e166bf2450d3dadbda47c8d8981898adb9b6fe24e5e582ba60 \ + --hash=sha256:c6c4dcdfff2c08509faa15d36ba7e5ef5fcfab25f1e8f85a0c8f45bc3a30725d \ + --hash=sha256:c6c565d9a6e1a8d783c1948937ffc377dd5771e83bd56de8317c450a954d2056 \ + --hash=sha256:c8a154cf6537ebbc110e24dabe53095e714245c272da9c1be05734bdad4a61aa \ + --hash=sha256:c9c08c2fbc6120e70abff5d7f28ffb4d969e14294fb2143b4b5c7d20e46d1714 \ + --hash=sha256:ca89c5e596fc05b015f27561b3793dc2fa0917ea0d7507eebb448efd35274a70 \ + --hash=sha256:cc7cd0b2be0f0269283a45c0d8b2c35e149d1319dcb4a43c9c3689fa935c1ee6 \ + --hash=sha256:cda1ed70d2b264952e88adaa52eea653a33a1b98ac907ae2f86508eb44f65cdc \ + --hash=sha256:cf8ff04c642716a7f2048713ddc6278c5fd41faa3b9cab12607c7abecd012c22 \ + --hash=sha256:cfecdaa4b19f9ca534746eb3b55a5195d5c95b88cac32a205e981ec0a22b7d31 \ + --hash=sha256:d426616dae0967ca225ab12c22274eb816558f2f99ccb4a1d52ca92e8baf180f \ + --hash=sha256:d5eaa4a4c5b1906bd0d2508d68927f15b81821f85092e06f1a34a4254b0e1af3 \ + --hash=sha256:d639a750223132afbfb8f429c60d9d318aeba03281a5f1ab49f877456448dcf1 \ + --hash=sha256:d920392a6b1f353f4aa54328c867fec3320fa50657e25f64abf17af054fc97ac \ + --hash=sha256:d991483606f3dbec93287b9f35596f41aa2e92b7c2ebbb935b63f409e243c9af \ + --hash=sha256:d9ea2604370efc9a174c1b5dcc81784fb040044232150f7f33756049edfc9026 \ + --hash=sha256:dbaf3c3c37ef190439981648ccbf0c02ed99ae066087dd117fcb616d80b010a4 \ + --hash=sha256:dca3582bca82596609959ac39e12b7dad98385b4fefccb1151b937383cec547d \ + --hash=sha256:e3174a5ed4171570dc8318afada56373aa9289eb6dc0d96cceb48e7358b0e220 \ + --hash=sha256:e43a55f378df1e7a4fa3547c88d9a5a9b7113f653a66821bcea4718fe6c58763 \ + --hash=sha256:e69d0deeb977ffe7ed3d2e4439360089f9c3f217ada608f0f88ebd67afb6385e \ + --hash=sha256:e85dc94595f4d766bd7d872a9de5ede1ca8d3063f3bdf1e2c725f5eb411159e3 \ + --hash=sha256:e90b8db97f6f2c97eb045b51a6b2c5ed69cedd8392459e0642d4199b94fabd7e \ + --hash=sha256:e9bf3f0bbdb56633c07d7116ae60a576f846efdd86a8848f8d62b749e1209ca7 \ + --hash=sha256:ea4e6b3566127fda5e007e90a8fd5a4169f0cf0619506ed426db647f19c8454a \ + --hash=sha256:ec94c04149b6a7b8120f9f44565722c7ae31b7a6d2275569d2eefa76b83da3be \ + --hash=sha256:eddf73f41225942c1f994914742afa53dc0d01a6e20fe14b878a1b1edc74151f \ + --hash=sha256:ee6854c9000a10938c79238de2379bea30c82e4925a371711af45387df35cab8 \ + --hash=sha256:ef71d476caa6692eea743ae5ea23cde3260677f70122c4d258ca952e5c2d4e84 \ + --hash=sha256:f052d1be37ef35a54e394de66136e30fa1191fab64f71fc06ac7bc98c9a84618 \ + --hash=sha256:f1862739a1ffb50615c0fde6bae6569b5efbe08d98e59ce009f68a336f64da75 \ + --hash=sha256:f192a831d9575271a22d804ff1a5355355723f94f31d9eef25f0d45a152fdc1a \ + --hash=sha256:f42e68301ff4afee63e365a5fc302b81bb8ba31af625a671d7acb19d10168a8c \ + --hash=sha256:f7792f27d3ee6e0244ea4697d92b825f9a329ab5230a78c1a68bd274e64b5077 \ + --hash=sha256:f82110ab962a541737bd0ce87978d4c658f06e7591ba899192e2712a517badbb \ + --hash=sha256:f9ca1cbdc0fbfe5e6e6f8221ef2309988db5bcede52443aeaee9a4ad555e0dac \ + --hash=sha256:fd65af65e2aaf9474e468f9e571bd7b189e1df3a61caa59dcbabd0000e4ea839 \ + --hash=sha256:fe2fda4110a3d0bc163c2e0664be44657431440722c5c5315c65155cab92f9e5 \ + --hash=sha256:febd38857b09867d3ed3f4f1af7d241c5c50362e25ef43034995b77a50df494e +requests==2.34.2 \ + --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \ + --hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed +rich==14.3.1 \ + --hash=sha256:b8c5f568a3a749f9290ec6bddedf835cec33696bfc1e48bcfecb276c7386e4b8 \ + --hash=sha256:da750b1aebbff0b372557426fb3f35ba56de8ef954b3190315eb64076d6fb54e +safetensors==0.8.0 \ + --hash=sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358 \ + --hash=sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f \ + --hash=sha256:2ddf52eac562eda224f99acfa7889d02968c1fd59a5b011ae7d8137c37e9c02d \ + --hash=sha256:3ae091f16662658bdc019a4ff6cb4c085bb7d725eb5978b183ffd265863b6d2d \ + --hash=sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0 \ + --hash=sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc \ + --hash=sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235 \ + --hash=sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98 \ + --hash=sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4 \ + --hash=sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846 \ + --hash=sha256:8e9f537aa183a38ace122d27303dcd986b26bd2a7591f9181d7f0c396f4677ca \ + --hash=sha256:c554f85858e05226d3c2828e32395e677434685d6d94594a41643361c5e837f0 \ + --hash=sha256:c80201d22cbf405b80647a60ada77bba06c8fba2da2743ba1e89cdcc39a81f25 \ + --hash=sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452 \ + --hash=sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d \ + --hash=sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78 \ + --hash=sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774 +scipy==1.17.0 \ + --hash=sha256:00fb5f8ec8398ad90215008d8b6009c9db9fa924fd4c7d6be307c6f945f9cd73 \ + --hash=sha256:031121914e295d9791319a1875444d55079885bbae5bdc9c5e0f2ee5f09d34ff \ + --hash=sha256:0937a0b0d8d593a198cededd4c439a0ea216a3f36653901ea1f3e4be949056f8 \ + --hash=sha256:0cf46c8013fec9d3694dc572f0b54100c28405d55d3e2cb15e2895b25057996e \ + --hash=sha256:0d5018a57c24cb1dd828bcf51d7b10e65986d549f52ef5adb6b4d1ded3e32a57 \ + --hash=sha256:130d12926ae34399d157de777472bf82e9061c60cc081372b3118edacafe1d00 \ + --hash=sha256:13c4096ac6bc31d706018f06a49abe0485f96499deb82066b94d19b02f664209 \ + --hash=sha256:13e861634a2c480bd237deb69333ac79ea1941b94568d4b0efa5db5e263d4fd1 \ + --hash=sha256:1f9586a58039d7229ce77b52f8472c972448cded5736eaf102d5658bbac4c269 \ + --hash=sha256:1ff269abf702f6c7e67a4b7aad981d42871a11b9dd83c58d2d2ea624efbd1088 \ + --hash=sha256:255c0da161bd7b32a6c898e7891509e8a9289f0b1c6c7d96142ee0d2b114c2ea \ + --hash=sha256:2591060c8e648d8b96439e111ac41fd8342fdeff1876be2e19dea3fe8930454e \ + --hash=sha256:272a9f16d6bb4667e8b50d25d71eddcc2158a214df1b566319298de0939d2ab7 \ + --hash=sha256:2abd71643797bd8a106dff97894ff7869eeeb0af0f7a5ce02e4227c6a2e9d6fd \ + --hash=sha256:2b531f57e09c946f56ad0b4a3b2abee778789097871fc541e267d2eca081cff1 \ + --hash=sha256:30509da9dbec1c2ed8f168b8d8aa853bc6723fede1dbc23c7d43a56f5ab72a67 \ + --hash=sha256:33af70d040e8af9d5e7a38b5ed3b772adddd281e3062ff23fec49e49681c38cf \ + --hash=sha256:357ca001c6e37601066092e7c89cca2f1ce74e2a520ca78d063a6d2201101df2 \ + --hash=sha256:3625c631a7acd7cfd929e4e31d2582cf00f42fcf06011f59281271746d77e061 \ + --hash=sha256:363ad4ae2853d88ebcde3ae6ec46ccca903ea9835ee8ba543f12f575e7b07e4e \ + --hash=sha256:40052543f7bbe921df4408f46003d6f01c6af109b9e2c8a66dd1cf6cf57f7d5d \ + --hash=sha256:423ca1f6584fc03936972b5f7c06961670dbba9f234e71676a7c7ccf938a0d61 \ + --hash=sha256:474da16199f6af66601a01546144922ce402cb17362e07d82f5a6cf8f963e449 \ + --hash=sha256:4e00562e519c09da34c31685f6acc3aa384d4d50604db0f245c14e1b4488bfa2 \ + --hash=sha256:5194c445d0a1c7a6c1a4a4681b6b7c71baad98ff66d96b949097e7513c9d6742 \ + --hash=sha256:5fb10d17e649e1446410895639f3385fd2bf4c3c7dfc9bea937bddcbc3d7b9ba \ + --hash=sha256:65ec32f3d32dfc48c72df4291345dae4f048749bc8d5203ee0a3f347f96c5ce6 \ + --hash=sha256:6680f2dfd4f6182e7d6db161344537da644d1cf85cf293f015c60a17ecf08752 \ + --hash=sha256:6e886000eb4919eae3a44f035e63f0fd8b651234117e8f6f29bad1cd26e7bc45 \ + --hash=sha256:7204fddcbec2fe6598f1c5fdf027e9f259106d05202a959a9f1aecf036adc9f6 \ + --hash=sha256:819fc26862b4b3c73a60d486dbb919202f3d6d98c87cf20c223511429f2d1a97 \ + --hash=sha256:8547e7c57f932e7354a2319fab613981cde910631979f74c9b542bb167a8b9db \ + --hash=sha256:85b0ac3ad17fa3be50abd7e69d583d98792d7edc08367e01445a1e2076005379 \ + --hash=sha256:87b411e42b425b84777718cc41516b8a7e0795abfa8e8e1d573bf0ef014f0812 \ + --hash=sha256:88c22af9e5d5a4f9e027e26772cc7b5922fab8bcc839edb3ae33de404feebd9e \ + --hash=sha256:9244608d27eafe02b20558523ba57f15c689357c85bdcfe920b1828750aa26eb \ + --hash=sha256:979c3a0ff8e5ba254d45d59ebd38cde48fce4f10b5125c680c7a4bfe177aab07 \ + --hash=sha256:9eeb9b5f5997f75507814ed9d298ab23f62cf79f5a3ef90031b1ee2506abdb5b \ + --hash=sha256:9fad7d3578c877d606b1150135c2639e9de9cecd3705caa37b66862977cc3e72 \ + --hash=sha256:a38c3337e00be6fd8a95b4ed66b5d988bac4ec888fd922c2ea9fe5fb1603dd67 \ + --hash=sha256:aabf057c632798832f071a8dde013c2e26284043934f53b00489f1773b33527e \ + --hash=sha256:c17514d11b78be8f7e6331b983a65a7f5ca1fd037b95e27b280921fe5606286a \ + --hash=sha256:c5e8647f60679790c2f5c76be17e2e9247dc6b98ad0d3b065861e082c56e078d \ + --hash=sha256:cacbaddd91fcffde703934897c5cd2c7cb0371fac195d383f4e1f1c5d3f3bd04 \ + --hash=sha256:d7425fcafbc09a03731e1bc05581f5fad988e48c6a861f441b7ab729a49a55ea \ + --hash=sha256:dac97a27520d66c12a34fd90a4fe65f43766c18c0d6e1c0a80f114d2260080e4 \ + --hash=sha256:dbf133ced83889583156566d2bdf7a07ff89228fe0c0cb727f777de92092ec6b \ + --hash=sha256:e8c0b331c2c1f531eb51f1b4fc9ba709521a712cce58f1aa627bc007421a5306 \ + --hash=sha256:eb2651271135154aa24f6481cbae5cc8af1f0dd46e6533fb7b56aa9727b6a232 \ + --hash=sha256:ebb7446a39b3ae0fe8f416a9a3fdc6fba3f11c634f680f16a239c5187bc487c0 \ + --hash=sha256:ec0827aa4d36cb79ff1b81de898e948a51ac0b9b1c43e4a372c0508c38c0f9a3 \ + --hash=sha256:edce1a1cf66298cccdc48a1bdf8fb10a3bf58e8b58d6c3883dd1530e103f87c0 \ + --hash=sha256:eec3842ec9ac9de5917899b277428886042a93db0b227ebbe3a333b64ec7643d \ + --hash=sha256:ef28d815f4d2686503e5f4f00edc387ae58dfd7a2f42e348bb53359538f01558 \ + --hash=sha256:f2a4942b0f5f7c23c7cd641a0ca1955e2ae83dedcff537e3a0259096635e186b \ + --hash=sha256:f3cd947f20fe17013d401b64e857c6b2da83cae567adbb75b9dcba865abc66d8 \ + --hash=sha256:f603d8a5518c7426414d1d8f82e253e454471de682ce5e39c29adb0df1efb86b \ + --hash=sha256:f7df7941d71314e60a481e02d5ebcb3f0185b8d799c70d03d8258f6c80f3d467 \ + --hash=sha256:f9eb55bb97d00f8b7ab95cb64f873eb0bf54d9446264d9f3609130381233483f \ + --hash=sha256:fc02c37a5639ee67d8fb646ffded6d793c06c5622d36b35cfa8fe5ececb8f042 \ + --hash=sha256:fe508b5690e9eaaa9467fc047f833af58f1152ae51a0d0aed67aa5801f4dd7d6 +sentencepiece==0.2.3 \ + --hash=sha256:016218e381da4c492323f2d7959012338795a2fb2dfccf14a2bc421c1b040612 \ + --hash=sha256:01e62cf99d3af7950cff04986c7e58dd4cd376fcf2367cd1c5314182d5f4adc5 \ + --hash=sha256:0d1235ccd36c3e8c2021355258b47866c694a55003a89f00701c513eac1aef06 \ + --hash=sha256:0ef20da5e56faff98bfcd1eb78c9abedc10253035051ab34e0c4be22734390ef \ + --hash=sha256:141dc0bef1e28a5cf7e41c8354ad6cc14525758278045286dcb5429b9906d39f \ + --hash=sha256:21618ad31f0453a1ebf5ec58defed99758d54af0b670546ecac639ddd8b86fbd \ + --hash=sha256:21cb90585b2d9a1cf78c5e889af0a12b35536dc65e2f0ba2daf540c60d431c87 \ + --hash=sha256:22dce81a65b8a1819eef9fef4970d6581ea0cbde7f58fbbbb42521535eba15e2 \ + --hash=sha256:2b79f0bbd03ca46ae117595c830eef17bc31a00c566f3b7be3b5f03d51efda3a \ + --hash=sha256:2e39d12eead4e417a6a2e852305f890fd7f09bf48b2577a4e336285ae24439ab \ + --hash=sha256:39ce776c5564192c4361085f10cfe3f1bcc0749feab314060b2bbb4244266dec \ + --hash=sha256:4d82f2a0f704f5d0cf027bc8cc5ad49e23c11a9cc0b5bd08ca51985917963bf5 \ + --hash=sha256:51ae35f32ddc832b8ff5f57dd69dae5a814ab6b6e027c83e6f5632335bf21e98 \ + --hash=sha256:5b280042f92596dbbfeae01759578897b49fdf1ac1a24ec8ddd6a3de1f6a996d \ + --hash=sha256:5ea5e9c9b40bb7e9ff64151071ab04365890da2e1edaa1d7e1a131ffdb735509 \ + --hash=sha256:61993a60493c44f8c99a773d2b0f1162cbbab319989ce3fe04ef4130b740397a \ + --hash=sha256:65f26939063414c5f57a46a625789e9b32f952a800490d5cce6d4c4ad0094fff \ + --hash=sha256:6b94ccd8554338970e1d73959a7e3ed4d110a60dab95d459990b30a508fa0998 \ + --hash=sha256:7e9cd3b7229da250c8988e46dc29ae339147d463ab50e1fb697bc59d02880cc1 \ + --hash=sha256:80fe42d6ecd3860ee43327de31687f222af8e93f7d66e248d241cf9a0466eb73 \ + --hash=sha256:821cd46446d0791df174e7f9e463aa3fc5a923286b98f3509f79bda9992e51cb \ + --hash=sha256:84e9def430ca8cc848b84adb304ffb77bff151cfc7dc66eb881f0385258f536b \ + --hash=sha256:855b047e02fb9c7aae2f673f5c1adbd42a4a0e8ce77e5090d14ff26f9282749d \ + --hash=sha256:901f38530a93e14505bfa3279c8a4705158f30af406bc2721cf3ffd7175170c2 \ + --hash=sha256:972af959c63cde446210a8935524806820c253afa4b0a97d83c206b857085f44 \ + --hash=sha256:9b39b16b889c9d3be4f00f1a0a4283ee81ad8af745d48023e5ab18c724019c08 \ + --hash=sha256:9f77802993eb51a08e856278f73894615b9a6cc3244857fcf962bc657578f591 \ + --hash=sha256:a01e76cf49a0c1abc527c4e5fd6d3a87a3139a1d3ad2d5761567179a70805cce \ + --hash=sha256:a0a75095caa5d4ac208dd8d1c051dd78fa7dbdb3b62d2aae86986b678324f759 \ + --hash=sha256:a6b735a8027b998c163e540fdde66ac0bb95fc471f6f4165c8df35fb45385116 \ + --hash=sha256:b3dcda6a6eaa297db9e595d1d59a0ca4127ff01af573a24f2665a938c14b9e2a \ + --hash=sha256:ba4dfdbb2972e42d01ad32fe03788717e94d92830f981b7895835e65bfe92b2c \ + --hash=sha256:cc3189b79c1ffda767f71b04238c27ac746f3b7abc263eab9a41c4cf46aee49e \ + --hash=sha256:ceaf9a73f7e1672990547e8efe5bb79ea61884a8fe24600662d12e3a8aaf1a5b \ + --hash=sha256:d8dd43abf868aa70508d463709812250266aa3f2e4bd4c3d524a5f7d8c18856e \ + --hash=sha256:dc4d17ad8728f47062496a7c03e000bb37de9c6741f8423b822d51e4f2f86fcf \ + --hash=sha256:deba7b85448bf4cfabf2e097f3d42e51a45ba5d531421f28fefecf542e0aa9d5 \ + --hash=sha256:dfc31f9f133a2712d396efa94d666c2ad83d5611ce34f11339429c6831253014 \ + --hash=sha256:e55cea81a9e68ee3bd119ca530225cbf1f4ac46bf35604c8aa677bfd5055bc7c \ + --hash=sha256:e64c49a30001245702035aba15ff3833895d3598228dd9f980df3d146dc4fd33 \ + --hash=sha256:ec5c6a53f9f7adfe6e7f62b12696280632c0da2352a696b436ae4152f72ff706 +setuptools==84.2.1 \ + --hash=sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc \ + --hash=sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2 +shellingham==1.5.4 \ + --hash=sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686 \ + --hash=sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de +six==1.17.0 \ + --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \ + --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81 +soundfile==0.13.1 \ + --hash=sha256:03267c4e493315294834a0870f31dbb3b28a95561b80b134f0bd3cf2d5f0e618 \ + --hash=sha256:1e70a05a0626524a69e9f0f4dd2ec174b4e9567f4d8b6c11d38b5c289be36ee9 \ + --hash=sha256:743f12c12c4054921e15736c6be09ac26b3b3d603aef6fd69f9dde68748f2593 \ + --hash=sha256:82dc664d19831933fe59adad199bf3945ad06d84bc111a5b4c0d3089a5b9ec33 \ + --hash=sha256:9c9e855f5a4d06ce4213f31918653ab7de0c5a8d8107cd2427e44b42df547deb \ + --hash=sha256:a23c717560da2cf4c7b5ae1142514e0fd82d6bbd9dfc93a50423447142f2c445 \ + --hash=sha256:b2c68dab1e30297317080a5b43df57e302584c49e2942defdde0acccc53f0e5b \ + --hash=sha256:c734564fab7c5ddf8e9be5bf70bab68042cd17e9c214c06e365e20d64f9a69d5 +sympy==1.14.0 \ + --hash=sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517 \ + --hash=sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5 +tokenizers==0.23.3 \ + --hash=sha256:114e2b55ed177179d59f4ab98200a4471e11e78f9e4b5a922d146740f96fcf52 \ + --hash=sha256:1554a6eed34d9d6a78d23360f4e06df8dffab1ae08c7e8488e0b3e3b36cc266f \ + --hash=sha256:1ebf28794e7e4954e20a7f70fbea410b2d1f0418f7dbbca97ca384fcfef38c25 \ + --hash=sha256:1f0823bb00c5fdc98e487354d54dd55a03848d61a1a0bf29a68c77f24f3b26c3 \ + --hash=sha256:2a89614730d7b80940a5d2ed9320e1ec8add5a745c6151d8d05071b7215505b6 \ + --hash=sha256:376851d22bcf9d650a5c3090bb83e6cf9e895fbf0595369fa4cd43c1f69b5f87 \ + --hash=sha256:5cc24bb457dd4a8af89c8fcb40074d570129ec473df2a866c276ee55db4749d7 \ + --hash=sha256:68649e97d5b43c44c031d8d848874a6eecae8f8fe40ea989aa777a5a83aca716 \ + --hash=sha256:7e48734d2de9260d86f03ab056d2cfeeff3869f61dbd49aaa15a2793b5f3458b \ + --hash=sha256:82eb480f6f1c21cea3349dec32cf1a6384c6c1e775f00f83b0d51197bc013687 \ + --hash=sha256:84513ef0aeb8bf8f4ea11a2e8a7ac163ec5288aa115e649a59b470ac5c3107df \ + --hash=sha256:9d2b5c97daf61688c2ad1803ca851800feaba50fb68d5821779e9ea5880d968c \ + --hash=sha256:a4fbb3662f9f59d199d61338e54b4bcc11d07ebbb1aeb3540dacb2be9c521cb7 \ + --hash=sha256:acd5c57b4bd3e56e246e2731a3a3a6825a7a7d89b7e3b761ba80bc521710f04b \ + --hash=sha256:bf501c40b72d2d5c8623620210430e9cac1ce47a46e45b34107b70a1557d46b0 \ + --hash=sha256:c64a0713180ff16829d4e7f39a658b77ea11443af4e1aa46523692943c9b1414 \ + --hash=sha256:cded33237c77caeef62944d32aa9a7ef42bdce2b3497e18d137e072a8c4be438 \ + --hash=sha256:d3407fb7b9c4d75dd68850ffd7180bc0a5d2dbaf0762d888e612f31fec3f9c6b \ + --hash=sha256:ddedfd4b3b4be6be24ff6ca645c4a37fddfd305f6f3e354c54cf10b715c48215 \ + --hash=sha256:de536665495cb4b409d25bade41963f801aff4225c19a6b804b048f7d14e34c7 \ + --hash=sha256:e05ab7baf7f47b406a95fea6f3b0a484b2ddcd9e1d14b68844c457eb755085a3 \ + --hash=sha256:e88646b8580c5ad7f4361477f1298e9cc01771a1ee9aecfe32c47b8ff614cc38 \ + --hash=sha256:ec82e80e65a862275b97c3d90b7a523df8d9519ee48aeb4e9625b2cc909274e0 \ + --hash=sha256:efa3d7318406b4d115dce61ad5061953f1f44b128e79c020ce4615d763e23b6e +toml==0.10.2 \ + --hash=sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b \ + --hash=sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f +torch==2.14.1 \ + --hash=sha256:06c3ec25f3b497f9a73dc0c36f293f295cfe8d5584fd446238d9a501b30a66d5 \ + --hash=sha256:0b13acde294b401509830d85a8906cbf2fc97425a12a66cce1d9fa13c5106a2a \ + --hash=sha256:0bd2fb0c4098856bc5af59fe5988bf38bdbcdb6550b44273c12ae425cb8ec17e \ + --hash=sha256:1d4df07be7338bbcc4d54085adee21363c91314702b9bd4d78ef72ffac9465ba \ + --hash=sha256:1fee6b20869a90ccec05e35559a706338ac8aab40a9c4fb58f16667e93af36ae \ + --hash=sha256:23011fe29a99b591eabb3a31a25080c62e2c2f0690a3c798744e5489dae50451 \ + --hash=sha256:305a61f61f35f128579f299c5bd33d475f6a01c6307336139632e30856c4854d \ + --hash=sha256:38bee9f2a2ccfc6898172a5075e4ba52522fbe143eeb099674fc67ab390e858d \ + --hash=sha256:420dbf314c180ee4b86e9bc00aee5746a7d6e5bacdd7df925af671ed393f0b2e \ + --hash=sha256:6d530bd11479fb574567af3a1f384af9a77bf5bb9550cde8080b356ca7220d5a \ + --hash=sha256:711713391d26a1ce5e9fbc6c996d954a8c12e8825374cc77b809a6af29539b8c \ + --hash=sha256:9113f94f70429f9f302bf55b090b5411269083e8a72a5d015ffcc5a7f83f2c69 \ + --hash=sha256:957df236525bcd940ccd9ca59074e9821182171253417c0d98e7b82647254799 \ + --hash=sha256:9ee7d50ec80ae5b4258cafc0ea108711988d961f21d0a68cf685650da2812e5f \ + --hash=sha256:b6074b130fd26bc50f5d171f07dfed70db22dd0c354ab34767729249f9e0f042 \ + --hash=sha256:c8f71aabc67bcbfc9373dc131537a5968d04edce73e88add21354a7cd0a76985 \ + --hash=sha256:cee091caf2a6229e248daf41d18ceebf590ba02d9179205610062c64ee5fef03 \ + --hash=sha256:d02a4c48a2ca5fb7654e36e71f710f74494d83f1f10aaff8e059dd554adca956 \ + --hash=sha256:dbe359d705f4d67236743794c296c6dee93a922fd8117eff8c3e880d7d0fb2b9 \ + --hash=sha256:e07306caa1de2a4ac1467e11ecfc92fc44f523dd6a521145039aef46d913963c \ + --hash=sha256:e24b9815001d18e73e76eae1ea25f8ef908c6103e857378ad20f8f6cf5c954f5 \ + --hash=sha256:e65d5fe136e533b23c2d134377f7f126721c7c78dd75b3dbb735af082a8aeb85 \ + --hash=sha256:ef1276fd07adb8d463ac402a24ea7482e45c9a42df8ebdac211aa757779200ba \ + --hash=sha256:f68f5476e2bc0e8f60b74f7ca21acda885c4477af6392f8977e4f0d1ea1aa162 +torchao==0.18.0 \ + --hash=sha256:5c2b4485341bf28b7fed2c4fc95b9f298e209f41685350f067de85527a05585e \ + --hash=sha256:6540b148e40ba81cbd4de86392225a076a1591146e9cebb099b3b234ba9feebe +torchaudio==2.11.1 \ + --hash=sha256:0173b5b51e1368aa88de3cbe4e98508b5e9df4d8d59356c4e1fbc830c96191ef \ + --hash=sha256:46ea71634d181f797370f046075ea982043c228b38d674fd7d9fc1c855a37b6a \ + --hash=sha256:917667ab3e357d286b0e2405a33dc538e4344d554b72e1b2b03382a4352ca857 \ + --hash=sha256:ad1175202b5cdb7585a38c1330845430e128c4ed8ceb770639318aa40fc1994b +torchcodec==0.17.0 \ + --hash=sha256:0771bc114ff75a30f0ea8aa82cc7b259c518214eafe73fee2e606d745d77942b \ + --hash=sha256:0ab2f00d849ba7b24e1ddcc4ed575d988fe4ed54f39c6a55575a1a47674eff9c \ + --hash=sha256:0af78216e6b2d13e33ecaa7b49bb06d6795cab39515449d40d2193cf1fa3e447 \ + --hash=sha256:3d69d30fbd2d5f9cc6d63c6d970acb5fa3aeddb5524a059f0ca538a83972f65c \ + --hash=sha256:509558ec5d4f431fe2411d8f57e8e4fd6772f799bd44e570946b66989853c402 \ + --hash=sha256:645ea2b33596d3f1463a8a70a907fd793e6c40ad81404732b277d5eb449f8860 \ + --hash=sha256:7c6004dbeb27a9e58bad0b3d10b4d7f7cda4407c0f10ba45a5a2ebd60aa33dbe \ + --hash=sha256:7d58e5211ed6f04aca2bd57e6a6104f9993ceb36a290db31de3f4e6096148f0b \ + --hash=sha256:81655cf25e168e74f27aee29db9fc16e37a9f5b2a188a0f7fe25cdfaab2ddd2e \ + --hash=sha256:8806e967d598d0d8ff0214837d9fb7565f06c7676f56ec172d5c57574e59d5b8 \ + --hash=sha256:916ff04f0accda465b6b33a9926d1b9daae6414e81abed5987b78c87374e6e8a \ + --hash=sha256:9267dc578c4de6710d4686d52bb2e8dc9a44ad404e775957f4428375311ebc60 \ + --hash=sha256:94f3391db6a35b1fe4f1c41f02e6fb3950ba62020f2812b67d317bc3d2cb8966 \ + --hash=sha256:9567427ba28cee36704104f66bbaebfc210b89204fceb3063ca09a3fdeb0ac02 \ + --hash=sha256:9eb27bc90ad1d60fbded1415e8106961d5f9e4bc80b3010217cfe6a08ad967ce \ + --hash=sha256:aa5cf864c6a3ee42fa45961ec469ae359fbca448fb3440b86c84c9f77dd130aa \ + --hash=sha256:b387f1d935d5a60ebad6de0144d728f5802de9253a65fb1570a6f2ad646c9d3b \ + --hash=sha256:b7a2a30f0372f4b0caae71a598c20e6d5ef7bf55dae2576003d6a6ffeccb9153 \ + --hash=sha256:ba26d900b3941eac8176b5c42bed0e2315cc154f07037a385e211ec39af989bf \ + --hash=sha256:d9e682f91bc70a34a8c7ea3d302b3d6f52970b97c5b81aa098478197abf17fc6 \ + --hash=sha256:defd5f0901999c9e981f6465a0f4aac8b5a5147e38e539b77c0711c015cf5349 \ + --hash=sha256:fc7021f10d38debd4fd47b4620da50d8cead981752bb359f7e3a615bbca2b7d3 +torchmetrics==1.8.2 \ + --hash=sha256:08382fd96b923e39e904c4d570f3d49e2cc71ccabd2a94e0f895d1f0dac86242 \ + --hash=sha256:cf64a901036bf107f17a524009eea7781c9c5315d130713aeca5747a686fe7a5 +torchvision==0.29.2 \ + --hash=sha256:0875f7a23bd298813240f716c56df44ce72ddb45146589442a38edd0e1f59637 \ + --hash=sha256:5812c312d4401c3587a045fa4c6228d982ebc4faa9b472275d11afe5852e24f9 \ + --hash=sha256:a47f8f586df22d9e8e436854f9f613448e36788af8fb2e0eba91516034df2189 \ + --hash=sha256:d412494ff011f24c884a3cffd33eba1cb45a0299d4e26c1e175113f9d3b3ebc7 +tqdm==4.67.1 \ + --hash=sha256:26445eca388f82e72884e0d580d5464cd801a3ea01e63e5601bdff9ba6a48de2 \ + --hash=sha256:f8aef9c52c08c13a65f30ea34f4e5aac3fd1a34959879d7e59e63027286627f2 +transformers==5.18.0 \ + --hash=sha256:d79e5a515a572ee3deb33eb0d578be47d91e70c75d54cf21bf6eede6edef14a9 \ + --hash=sha256:d89c206e42e841af7cd314b3d2b21c03e977d819cdb4aef65ada048769a644df +typer==0.29.1 \ + --hash=sha256:00dbc549c13428bec1be55fe1f4d0fb8c6637a310e4f178ef14abe9534ee7b58 \ + --hash=sha256:ab6eb3880bf67ce96147734717f9ec333c06f66e361f3ea947d0be43da39f242 +typing-extensions==4.15.0 \ + --hash=sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466 \ + --hash=sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548 +typing-inspection==0.4.5 \ + --hash=sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7 \ + --hash=sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39 +urllib3==2.8.0 \ + --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \ + --hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63 +vector-quantize-pytorch==1.27.20 \ + --hash=sha256:ab85fb622e900edf1317c7c77b3a23dd95995e0ce17a123b4ba6178c1c678335 \ + --hash=sha256:e3ac6eb4ca05f192814b93bd59b537ad6fbfe5a5abb5c84ebb75c0a5c17b7f23 +yarl==1.25.1 \ + --hash=sha256:0136d640dfa9b0523853e411430a99f8a91eca85774c6420285a33b755bc6de3 \ + --hash=sha256:03dd38de09bc213e9a8b29761eec33ee1d5318dac0e49d8af36e4d27830e23a7 \ + --hash=sha256:0a191bfdb30a79b98e5d175d75285f9fcb78bf0e46ba5efda042e1c72071a0de \ + --hash=sha256:0a66db89ea473abeac4b70523cafd94db3772380e565f9d28af7a179b7af71fa \ + --hash=sha256:0ae12ff2b805fa02c4dab838005caef735e39986322698c48588d3beacb65c62 \ + --hash=sha256:0f12afda4eea8c8994a76d4df1875c765194f5fbe8a9d197929ea303caee29ec \ + --hash=sha256:10b2fd95332f0d716d5eee3c9fb2ce8eada19082de7fee83d32e37992fd75c26 \ + --hash=sha256:126a2533570c554719ca40a1288fdee1700b6bc82e7131aa69fa85252d92e651 \ + --hash=sha256:12b6bc4906e11f5e1a1cdcb12296e7afbd366c783cc8073403cd2fb74334e453 \ + --hash=sha256:142c06c4d6a35ee3ec5da08499805e879cb3ca7c1fbfbecb0140fe72403818d6 \ + --hash=sha256:14b79a30a93a3ce2e8832603fd0ab780ada281b0ba5110b519a634f2d7d7d1fc \ + --hash=sha256:17c9877a89fb6e2bca6f9087eb24cd7fb434653946ef5075e470d23d49b52287 \ + --hash=sha256:192a866877a49993949ef1975864ad8728bea28ee810f6abe1a0729c2b500426 \ + --hash=sha256:1ab7618921a93767387a4b83776f751588f5b5ae9bb5bc96620e2e2e00bca868 \ + --hash=sha256:1e80dcf1446e1b080b1932b0d103c464a04112f5bc31f0f983ad418172063cde \ + --hash=sha256:1f51020b2eb8a003c84925638ec63c21a750a4bddd3a22ec8eac6a742dadf1b9 \ + --hash=sha256:1fb2a01ba8cd9c5d2c5dc1ec35e0fc951d04b4f037541d4ac090c993ce58b3d7 \ + --hash=sha256:2239a02249d9326655419e0168a28ca9008938eaab31dc29fc875c217927a6c0 \ + --hash=sha256:23bf5b403c879a54964e0feac7285688e04bb220074878d737d331522da0a5bf \ + --hash=sha256:24ce942011a61953e7d313438038f4d32ff21387b775f58a957f7a07dd55ef95 \ + --hash=sha256:25868beca8b6765f8f7d0e11fe6dd7c66dd4b0793b9500286d20cc92352126a5 \ + --hash=sha256:287e99ff5aa4dc1c7630bfc683ded6f106d756c99dec432a2d7f197a784f51c6 \ + --hash=sha256:29273edf1530e397bd07cb784db1fbe0d2590b77569f2e24679a9c0a2d763b94 \ + --hash=sha256:2b49375d22299b0a834c2bca72f39aaecc270d96fb24c30424899676f487b22a \ + --hash=sha256:30eec96e8a91bd588ce897c9543f6d5d8d34b28fbcba28a4dedf20ebeae9fe57 \ + --hash=sha256:319e070a01db9920fb63761843f96a104c8e2b9427266731810dc1e22595b17c \ + --hash=sha256:35dcbea443fafb3eece757ad4e514560ddeb6c34cfae1582c620d7b293d7feee \ + --hash=sha256:3f4d48a6112712973e676bd792121fee470e432d749177162d9949d5c9460a1b \ + --hash=sha256:3feb99222553a8cbedfa52c2f59dd84c3f50d5b582c728d522caf8d72769a54b \ + --hash=sha256:419f392a1da624877975709e3864dfe833af6cc7671b39318086d456e288380c \ + --hash=sha256:42a66563d8cc056ee32e6191e05097a7b2b3bc302e0bc3133daf8710eb18bd26 \ + --hash=sha256:48796ea00a303961507dc6c8437c4b325a6fc3f95f7c36c71b91ea9a8150963c \ + --hash=sha256:4bd6340d20ae2c7ca719b87b426e808e90743b676d05d4c26c4fb5ca71f41184 \ + --hash=sha256:4ca89e4e21854ed27ec753297dde84b16c9f8e53b14a4866fb44457d643c19f8 \ + --hash=sha256:4d781294bb815ecb5ea57ff6bbf8038e0a31a95fdf3e1788f66e0dc100d64b58 \ + --hash=sha256:4f1c91f5a5980a937ff8e238e98e6897e1ad74a4b1e2c0d68c73b5ffbb3f5c0b \ + --hash=sha256:564fdc7085d2245ab84f88882fdb1d6ac0723124bff6ded35bfb1c00f812630d \ + --hash=sha256:59ba3a6e1aa8cfe5adf4bd270fd965db21955401b7ca6f1696010c55ed4daec2 \ + --hash=sha256:5df89f769cc8ff94c3d7e7603386fba309d25ce5240132d26c15baa8d0e96c4c \ + --hash=sha256:632da579b2d879f6bad20f2cfa35ded1efe2f4f77f8abb26a6234a5b236acd2f \ + --hash=sha256:65b5b2066651b7432d389e9799d979c703bcc6ef44266bb8153ef54e91e4aab3 \ + --hash=sha256:664ec6a520b74a1df2810666eb67695fcb77fa663e6ea0a25aaf2e529cb24dfa \ + --hash=sha256:681c758b0490f9e96b78e5fa8e8dc6e648e9185bb6eaebe73183c33ea0c445f3 \ + --hash=sha256:683e362b8ba453080f7489c66f4ea794e751c35b72e7eab3575ef784c2fbc7fb \ + --hash=sha256:68782fdb4027b8d1eee25ec35e9a6db05e863b899eb0310b3a33b6c3fef55707 \ + --hash=sha256:6efaf45df6a849cef613a03a94c845647456662f85438c886bb67a9c027c8c2c \ + --hash=sha256:71f42c5b9a948c113bbdebfa544598321431d064ff959d32e99b1feb61d68345 \ + --hash=sha256:72849d892954be4d09e569b8b831ac39ce58417fedc767d4308a0fe542018a40 \ + --hash=sha256:72c34ac7ad4314c19362d5ce27626dcc8429bd30bbf8c179f4234078851f9492 \ + --hash=sha256:734f6e5400352ac4254456003d462866c684703570929cff7a7bde015d0cb371 \ + --hash=sha256:75baa6cf9b6d1c52f3e111a130e202fd8cf0a5b3a066c3f73d615e885092e4ec \ + --hash=sha256:77716e245c90f058466a05e6a465bb8600f767a8f4b18b4d40f3aff958e5f73c \ + --hash=sha256:77e5099b99b37f3cf79c246998ca9f7313a78054cd1809ec46bc1afad47e1c4c \ + --hash=sha256:783dd1467083f4d3f7722ad6a313f24c173e7571372738fcb7a6e6d1ba48df25 \ + --hash=sha256:7a5c3115595995779ee21f2567035793911c3802a43c74f3fbb0314929ec67ac \ + --hash=sha256:7c88edaec8c349ad4c5ad4c486a3defcc4b80ceb2f074436ffa0a87caf5e76a6 \ + --hash=sha256:7cb414a73e21a7ab58254926073f2930cb22f5b4314ea4260a687e2b3fd4dce3 \ + --hash=sha256:7d42e7e3ca399555578b4d617e3a6ecf13371b3743a115995fa010c7bf341459 \ + --hash=sha256:7d575b54cb3863ef9bc290ea4b009999d55dc237326131e4853cf33e888fee03 \ + --hash=sha256:7e4de3ac4adbad3d0bc7c6f4360a7dbff5de2f15e3b723be3198074e17fd9c40 \ + --hash=sha256:7efc9f082dfed77c316edffa9deb52888e1bc6789171887cc1f68e06d65465c8 \ + --hash=sha256:80a063f8297fc796296f00f100be520f209b23dc98f93ce8eba6ee7122598209 \ + --hash=sha256:80e47012e730da131c9f059c80936783f9659aae22dc31c03c0595590d11ed54 \ + --hash=sha256:83d4a37e4b95da4d8bda930d6d35b75b4cdadbacbb4980cae290ea3100b5d51d \ + --hash=sha256:83e9f4a25085bd4b7214701a0794ff1f50fc633ffb8bdfebf07abdd81c2db126 \ + --hash=sha256:85a18376073f8a39aa07be34f9fc77e2869aa72c55c441efdd2cf79a0407504d \ + --hash=sha256:87796fedc3ba97ec14fab55acb48584276e6c1e4c1e89c422bda62c838e754a9 \ + --hash=sha256:882569ff613758cac762a457a5d72d6e211b28d4bcfea89d1d71ea942b02eac0 \ + --hash=sha256:8ce4d6ccafb33d39bd78444612d14938ead674c25702ded2ee9c54a47735d225 \ + --hash=sha256:8e7d98cdbb6d71e726f7d525952867096053d1f290dd4e3c50d7d313a136f414 \ + --hash=sha256:8ee202350cf57abf0e9502a41601841019c25d3db7ff52d980aaf31446254059 \ + --hash=sha256:8fb0eb4955adf0579001581f2f71a126e8781ba61bcd120f127b0401163c6c2d \ + --hash=sha256:90c30ed53546da833c700115c0064c22120d1b1560f474699fd31f22dd668233 \ + --hash=sha256:9489e6abf47ba37f332075a91444c7cfedb03e6ce99fbb2f116bfe1ce810da3b \ + --hash=sha256:94d7aa6debf92a1dd14cb5280b083a764169a13cfb23a452111160274ed989f4 \ + --hash=sha256:98d370568f393215d605304cdb77b3d5539bd192c75b623c7304c42c8d6d8273 \ + --hash=sha256:9b1bdaae98bc016825dd3c9d8ee1832f829b3341f9cc6ebd1a1b0a7fef7367cc \ + --hash=sha256:9d693bf4bf534e9ba3ae2780cfd577f5135629f7b5ac653490859d0b77864865 \ + --hash=sha256:9d6ed3d17bccce4c05343e1ca8da13bc5c02c812a4e7282ddd05e8769322d3fc \ + --hash=sha256:9e23c82b63cd7652fc24d33ed6cc17099d607aa3b4fc4ddc75e95062f3d82df4 \ + --hash=sha256:a1daf47cd95a7c3a63456336bc5aaa8c86dd3a47d07ed3d0e76132ae4666a5a1 \ + --hash=sha256:a1e32763e641a1566507d90a8d3b19bfc3cc04a9d4e5ae3e32189874ed4b58a3 \ + --hash=sha256:a2059a2d891bd156bc5184e7ab7a56e78a84dfcfdeac8c501b552533ad1c36ee \ + --hash=sha256:a2ed0ba415ccdf08f14bf544cb78346d0f76086707ffee24921a2c84dbf1305a \ + --hash=sha256:a3faadac7d812ddac258feb57b9846b60c1b437c4f4b9ad42595c6f6fe4390df \ + --hash=sha256:a5877f2255aab518ebe528289037699201d5dc5f045f2396cb30aa02db22f57f \ + --hash=sha256:a78b50b4f7918a3de71105d5c0b93bbc57bb8339a4d03a9dfd449f9068e76f3d \ + --hash=sha256:a8c2b841478068440d8b733005d13a5ef535b9928cbc05f17182d410f32ba449 \ + --hash=sha256:a9ca696eb02e5c02a8afd872ada510eba9b7fe6e68b9572c2e9a9b1941e31e2e \ + --hash=sha256:aa4ed3dd308548f9e707d9caaf005d2d7f8c1e7868f858dfeb47fe76e16b391d \ + --hash=sha256:ab2054c5531af2a9ba7b69b8ec91e4f884420e83a8c5e579b013084cb57e5e5d \ + --hash=sha256:abb1384477f5901d436b5d2e5465954de46ea6098f59163d243660b5c4461d35 \ + --hash=sha256:acae6b45d1ace09b6ba3876da43b88366ef368f73b988c7f57e14231753d4420 \ + --hash=sha256:acfa7e22aa6c6e7a5996a41d275bfa01efa7ea56ab890590280e9063e2cf5c1b \ + --hash=sha256:af4ea5b37403ef4e30f3927eaed540db942bde01d8d3ff083527c0704d1c9c68 \ + --hash=sha256:b10dd0557ba422715b5206b3743192135a6022acca8baec51aa127d0a75db8fe \ + --hash=sha256:b13b88747769537f3d32e89e3a735da10c0a9e35d7322928c701b5f93d3afffd \ + --hash=sha256:b51c159a9794633f5e0db7ecec7b2b6e3734eca1f5d17dc989ff3552a43ff78b \ + --hash=sha256:b5402a340723fa7da00b5cff987ddab61276be6d11251ea71ae02bcac54890d8 \ + --hash=sha256:b7abffdf37af1cec6a2ad69b827aa84320db5894791bc8ed932dc93fb274b7e9 \ + --hash=sha256:b8075fe90bc08e40b8b8a1874fab42ee4c7b56af05c5886e9cc841397f916908 \ + --hash=sha256:bc3ac7bf569f6b64dad04dd7808c7872dae8a97df657856eac05e9b7e3614a85 \ + --hash=sha256:bd0912757081f89b107d6c00b2ff8a194401b0b87eadcf4481de2b865a8fd44f \ + --hash=sha256:bdc8d8b8c22e9e43ac68316b5e6cf083dec537f4ec213cb4aa967b583bc3fa64 \ + --hash=sha256:be80550d9bfe83d9b62398a37081a90434e6df2d978ec345c3d2820de6beddab \ + --hash=sha256:c6f117789d22dce188e5754e8bc65b7e6ebf8cb73963b9fa761f672a5883769d \ + --hash=sha256:ca32926d7d77bcc8838425c4c95e040a3ace1cb7dfdae599013458dcda2607ca \ + --hash=sha256:cce0727fd5ac04d372fa9bbfde9febc2bcf209aadfcf0468e45dec72719895d1 \ + --hash=sha256:d0f1489233a254bb3643d2f05de7d59019254d81daeca6b9162fe9edef57e0c7 \ + --hash=sha256:d1c557dfd5e3db046053a0bdc72261ade790ebe8e2c7a41b36b0ca1f14cb95f3 \ + --hash=sha256:d21f0fa80a02d05299207eeaafef345d812ace96d5306e4ef265e1d419a615fa \ + --hash=sha256:d45673badd08456d0340e9364eddafe1c53a9d2896424294de4d7dd71ad3ee57 \ + --hash=sha256:d5add7b4ca7afeea91d52e4d4e4db3b1fe9885b71f07054560d8c4296b7441a2 \ + --hash=sha256:d5f90e44653c4e0f78501ed9bb7d3fce835a8d62b7c6ed0cb16557534087e743 \ + --hash=sha256:d7306dee25b8a0e737363f347362b875094b4dc4e367311470656ae420fdbf8e \ + --hash=sha256:dbcef5a9119ef653653132cccaf999b30a0af6f33bb0a4ba80bec30056868487 \ + --hash=sha256:def538065f9e4d4cf1ae164bd59aba00dfa84f03923e0de4c3788f252d6bcd17 \ + --hash=sha256:df23df54b5114a17c2d0ef192433e2e5a9f0c5178c32375e90b7cfc965f349d0 \ + --hash=sha256:dfbf531053a0935f2e871bcd4753f90313688772ff8c017f5ea402e315a78c1f \ + --hash=sha256:e029648f9c951db30e98a7d7ec90835db88ec4b32820efe2a9bdc2287e032eb6 \ + --hash=sha256:e07595c7d6f4db270ceede356a1bd1c07a34f1c26f958d1ed0cd7b48e0d2bba3 \ + --hash=sha256:e12c538e00e7c1b286a07061046b90e8124e6a9793efae2c70db6a4aad07faad \ + --hash=sha256:e546fe1d4a93ebc2910f0d768baff19faa09843ab3f2036a67ed6e69fae4419d \ + --hash=sha256:e5637ca8d0bd7fb72648a6c7934af4baaccb697657f7438c9d264fc2abb8b0b1 \ + --hash=sha256:e636b64d24fd9c38053c5e389a1174c66361fa49dcfd220f4dd35b4abde7cb89 \ + --hash=sha256:e7011b8fb8c4054bf0c12e5edc6cd83778b0028e99ce59b18586ed036f92cfdc \ + --hash=sha256:e80f557716fd765439577131e526b8942ffc2c07bdbc5e39fa62f660ba1e963f \ + --hash=sha256:e92b6bcc741b86d67606c40d3cb9c7cc8e6c737f81e31f4a94efc204456c92e3 \ + --hash=sha256:eb96ed1ae6c7d072d60840c0434aef07a2df611812810807fbc54263a6053e9a \ + --hash=sha256:eda19ea5ee88742f47a2340816e6f2d40b53bed3ab5b69794769f36af9f35bb4 \ + --hash=sha256:ef74070ac553c59eb4f04258722066d6c6135b7baa03b2e9f2da65c096e96d98 \ + --hash=sha256:efb01a106f971cb3752856bca2318bbdf7f01bd8823779c461586cbe5ffd5258 \ + --hash=sha256:f074e8d4aa0a5798920ddb6de3d08b228c614ff3724c3e8bd7577f4bafea867b \ + --hash=sha256:f38a70074041d3b7e138e452799f5174198bae5bd5ab2000917badf403908c5f \ + --hash=sha256:f41753a76f4f63927d03a0d8ba8f5ce0f2083bec29a8cfaccc55371b1564b96b \ + --hash=sha256:f53dcd26694f148f738edc052b5a69234833e739f10f4c3287bdfd8ec0f7b326 \ + --hash=sha256:f61964f235a43738bfac50da46fc4254943a7eea3051aeb0b6fc7c992c29fadc \ + --hash=sha256:fe01645169a2112aa1d4ebc3e4c5f029c5c8f97adfc32e5d37c993b39a994d75 +zipp==4.1.2 \ + --hash=sha256:b30cb6cd253122169c47de245ca24a86bac2a5d3802ba15bf7ba6414eb9e144d \ + --hash=sha256:cf474b90b07ea932637e17c6b9479de2b2882900b0d311bdaf4f5c000a15a97f diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-3d.json b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-3d.json index 552ff84..8d6d6d1 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-3d.json +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-3d.json @@ -37,7 +37,13 @@ "ckpts/slat_flow_img2shape_dit_1_3B_1024_bf16.json", "ckpts/slat_flow_img2shape_dit_1_3B_1024_bf16.safetensors", "ckpts/shape_dec_next_dc_f16c32_fp16.json", - "ckpts/shape_dec_next_dc_f16c32_fp16.safetensors" + "ckpts/shape_dec_next_dc_f16c32_fp16.safetensors", + "ckpts/slat_flow_imgshape2tex_dit_1_3B_512_bf16.json", + "ckpts/slat_flow_imgshape2tex_dit_1_3B_512_bf16.safetensors", + "ckpts/slat_flow_imgshape2tex_dit_1_3B_1024_bf16.json", + "ckpts/slat_flow_imgshape2tex_dit_1_3B_1024_bf16.safetensors", + "ckpts/tex_dec_next_dc_f16c32_fp16.json", + "ckpts/tex_dec_next_dc_f16c32_fp16.safetensors" ] }, "port_requires": { diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-embeddings.json b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-embeddings.json index 881f1f0..6504a25 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-embeddings.json +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-embeddings.json @@ -8,19 +8,39 @@ "lock": "mlx-embeddings.lock", "ports": { "classification": [ + "kev", "laya" ] }, "port_bits": { + "kev": [ + 8, + 32 + ], "laya": [ 6, 8 ] }, "port_convert": { + "kev": "convert", "laya": "convert" }, + "port_recipes": { + "jaredpalmer/kev-4b": { + "port": "kev", + "base": "Qwen/Qwen3-4B-Base", + "base_revision": "906bfd4b4dc7f14ee4320094d8b41684abff8539", + "lora": "adapter_model.safetensors", + "lora_scale": 1.0 + } + }, "port_signatures": { + "kev": [ + "adapter_config.json", + "adapter_model.safetensors", + "head.pt" + ], "laya": [ "rl_agent_config.json", "encoder/config.json", @@ -30,6 +50,13 @@ ] }, "port_quantize": { + "kev": { + "include": [ + "backbone.embed_tokens", + "backbone.layers." + ], + "group_size": 64 + }, "laya": { "include": [ "encoder.layers.", @@ -39,13 +66,26 @@ } }, "categories": { - "classification": "classifiers" + "classification": "classifiers", + "embedding": "models" }, "remap_files": {}, "registry": { "classification": { "model_types": [], "remapping": {} + }, + "embedding": { + "model_types": [ + "bert", + "modernbert", + "qwen3", + "xlm_roberta", + "lfm2", + "llama_bidirec", + "gemma3_text" + ], + "remapping": {} } } } diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-embeddings.lock b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-embeddings.lock index 0f3cbef..8d41295 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-embeddings.lock +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-embeddings.lock @@ -739,9 +739,9 @@ opencv-python==5.0.0.93 \ --hash=sha256:f8b6d0a212253dd26ad338c812f1f23ca118fdf05a9c8c6b9444f161aa8c5881 \ --hash=sha256:f90ba04b8f73bc5c3814037699739f0156f597338a98f05956c684e7c3ca10d2 # via mlx-vlm -opentelemetry-api==1.45.1 \ - --hash=sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75 \ - --hash=sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb +opentelemetry-api==1.45.2 \ + --hash=sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34 \ + --hash=sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4 # via fastapi packaging==26.3 \ --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-video.lock b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-video.lock index 1b16949..aaae2c2 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-video.lock +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-video.lock @@ -758,9 +758,9 @@ opencv-python==5.0.0.93 \ # via # mlx-video-with-audio # mlx-vlm -opentelemetry-api==1.45.1 \ - --hash=sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75 \ - --hash=sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb +opentelemetry-api==1.45.2 \ + --hash=sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34 \ + --hash=sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4 # via fastapi packaging==26.3 \ --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-vlm.lock b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-vlm.lock index f5ab5a2..e695ea4 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-vlm.lock +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-vlm.lock @@ -671,9 +671,9 @@ opencv-python==5.0.0.93 \ --hash=sha256:f8b6d0a212253dd26ad338c812f1f23ca118fdf05a9c8c6b9444f161aa8c5881 \ --hash=sha256:f90ba04b8f73bc5c3814037699739f0156f597338a98f05956c684e7c3ca10d2 # via mlx-vlm -opentelemetry-api==1.45.1 \ - --hash=sha256:aa38ed19bcc084ba42782a73255b3582283eced7ad6dddbd6695189e69adfb75 \ - --hash=sha256:b31553efa588ae44bc306f863c785c5333a9ecc091248c6ee68b4b6c87fdedfb +opentelemetry-api==1.45.2 \ + --hash=sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34 \ + --hash=sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4 # via fastapi packaging==26.3 \ --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/__init__.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/__init__.py index 8a9f255..589b7e5 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/__init__.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/__init__.py @@ -9,3 +9,8 @@ def load(path): def generate(model, image, out, **kwargs): from .pipeline import generate as generate_mesh return generate_mesh(model, image, out, **kwargs) + + +def prepare(model, resolution): + from .pipeline import prepare as prepare_model + return prepare_model(model, resolution) diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/closed.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/closed.py new file mode 100644 index 0000000..58abf9e --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/closed.py @@ -0,0 +1,136 @@ +"""A closed, outward-facing solid around a dual-grid mesh, which is open, unoriented and non-manifold.""" + +import numpy as np + +PAD = 3 + + +def closed_surface(vertices, faces, grid, band=0.75): + """Fill cells hidden along every axis, using bounded tiles and 2D axis projections. + + The mesh is sampled at the requested grid resolution; axis-visible openings remain open. + """ + from scipy import ndimage + from scipy.spatial import cKDTree + from skimage.measure import marching_cubes + from itertools import product + + triangles = np.asarray(faces, dtype=np.int64) + if triangles.ndim != 2 or triangles.shape[1] != 3 or not len(triangles): + raise ValueError("A closed surface requires at least one triangle.") + points = (np.asarray(vertices, dtype=np.float64) + 0.5) * grid + corners = points[triangles] + samples = np.concatenate([points[np.unique(triangles)], corners.mean(axis=1), + (corners[:, 0] + corners[:, 1]) / 2, + (corners[:, 1] + corners[:, 2]) / 2, + (corners[:, 2] + corners[:, 0]) / 2]) + cells = np.unique(np.floor(samples).astype(np.int64), axis=0) + origin = cells.min(axis=0) - PAD + cells -= origin + shape = cells.max(axis=0) + PAD + 1 + plane_sizes = [int(shape[1] * shape[2]), int(shape[0] * shape[2]), int(shape[0] * shape[1])] + if sum(plane_sizes) * 2 * np.dtype(np.int32).itemsize > 64 * 1024 * 1024: + raise ValueError("Axis projections exceed the 64 MiB reconstruction bound.") + projection_shapes = [(shape[1], shape[2]), (shape[0], shape[2]), (shape[0], shape[1])] + first = [np.full(s, shape[axis], dtype=np.int32) for axis, s in enumerate(projection_shapes)] + last = [np.full(s, -1, dtype=np.int32) for s in projection_shapes] + tile = 64 + group_keys, inverse = np.unique(cells // tile, axis=0, return_inverse=True) + order = np.argsort(inverse, kind="stable") + offsets = np.searchsorted(inverse[order], np.arange(len(group_keys) + 1)) + groups = {tuple(key): cells[order[offsets[i]:offsets[i + 1]]] for i, key in enumerate(group_keys)} + candidates = set() + limits = (shape - 1) // tile + for key in groups: + for delta in product((-1, 0, 1), repeat=3): + neighbor = tuple(key[i] + delta[i] for i in range(3)) + if all(0 <= neighbor[i] <= limits[i] for i in range(3)): + candidates.add(neighbor) + tree = cKDTree(samples) + far = band + 1.0 + + def field(start, end): + low = np.maximum(start - 2, 0) + high = np.minimum(end + 2, shape) + occupied = np.zeros(tuple(high - low), dtype=bool) + for key in product(*(range(int(low[i] // tile), int((high[i] - 1) // tile) + 1) for i in range(3))): + group = groups.get(key) + if group is None: + continue + selected = group[np.all((group >= low) & (group < high), axis=1)] + if len(selected): + occupied[tuple((selected - low).T)] = True + near = ndimage.binary_dilation(occupied, structure=np.ones((3, 3, 3), dtype=bool), iterations=2) + near = near[tuple(slice(int(start[i] - low[i]), int(end[i] - low[i])) for i in range(3))] + index = np.argwhere(near) + values = np.full(tuple(end - start), far, dtype=np.float32) + if len(index): + distance, _ = tree.query(index + start + origin + 0.5, distance_upper_bound=far, workers=-1) + values[tuple(index.T)] = np.minimum(distance, far) + return values + + for key in sorted(candidates): + start = np.asarray(key) * tile + end = np.minimum(start + tile, shape) + index = np.argwhere(field(start, end) <= band) + start + if not len(index): + continue + for axis, other in enumerate(((1, 2), (0, 2), (0, 1))): + coords = (index[:, other[0]], index[:, other[1]]) + np.minimum.at(first[axis], coords, index[:, axis]) + np.maximum.at(last[axis], coords, index[:, axis]) + + surfaces, faces_out = [], [] + vertex_offset = 0 + for key in product(*(range(int((shape[i] - 2) // tile) + 1) for i in range(3))): + start = np.asarray(key) * tile + end = np.minimum(start + tile + 1, shape) + region = tuple(slice(int(start[i]), int(end[i])) for i in range(3)) + possible = True + for axis, other in enumerate(((1, 2), (0, 2), (0, 1))): + section = (region[other[0]], region[other[1]]) + if not np.any((first[axis][section] < end[axis]) & (last[axis][section] >= start[axis])): + possible = False + break + nearby = any(tuple(key[i] + delta[i] for i in range(3)) in candidates + for delta in product((0, 1), repeat=3)) + if not possible and not nearby: + continue + values = field(start, end) + inside = np.ones(tuple(end - start), dtype=bool) + x, y, z = (np.arange(start[i], end[i]) for i in range(3)) + inside &= (x[:, None, None] >= first[0][region[1], region[2]][None, :, :]) & (x[:, None, None] <= last[0][region[1], region[2]][None, :, :]) + inside &= (y[None, :, None] >= first[1][region[0], region[2]][:, None, :]) & (y[None, :, None] <= last[1][region[0], region[2]][:, None, :]) + inside &= (z[None, None, :] >= first[2][region[0], region[1]][:, :, None]) & (z[None, None, :] <= last[2][region[0], region[1]][:, :, None]) + empty = values > band + level = values - band + level[empty & inside] = -band + if not (level.min() <= 0 < level.max()): + continue + surface, triangles, _, _ = marching_cubes(level, 0, method="lewiner") + surface = ((surface + start + origin + 0.5) / grid - 0.5).astype(np.float32) + surfaces.append(surface) + faces_out.append(triangles + vertex_offset) + vertex_offset += len(surface) + if not surfaces: + raise ValueError("The mesh has no reconstructable closed surface.") + surface, inverse = np.unique(np.concatenate(surfaces), axis=0, return_inverse=True) + triangles = inverse[np.concatenate(faces_out)].astype(np.int32) + valid = (triangles[:, 0] != triangles[:, 1]) & (triangles[:, 1] != triangles[:, 2]) & (triangles[:, 2] != triangles[:, 0]) + triangles = triangles[valid] + a, b, c = (surface[triangles[:, i]].astype(np.float64) for i in range(3)) + if np.einsum("ij,ij->", a, np.cross(b, c)) < 0: + triangles = triangles[:, ::-1] + return surface, np.ascontiguousarray(triangles) + + +def without_fins(vertices, faces): + """The mesh without triangles that share all three vertices with another, and without the vertices only they used. + + Edge collapse folds a thin wall into such back-to-back pairs; they enclose nothing and put four faces on an edge. + """ + faces = np.asarray(faces) + _, inverse, counts = np.unique(np.sort(faces, axis=1), axis=0, return_inverse=True, return_counts=True) + faces = faces[counts[inverse.reshape(-1)] == 1] + used, compact = np.unique(faces, return_inverse=True) + return np.asarray(vertices)[used], np.ascontiguousarray(compact.reshape(-1, 3).astype(faces.dtype)) diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/components.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/components.py new file mode 100644 index 0000000..d176dcf --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/components.py @@ -0,0 +1,26 @@ +"""Dependency-free TRELLIS request component contract.""" +from pathlib import Path + +BASE = ('image_encoder', 'ss_flow', 'ss_decoder', 'shape_flow_512', 'shape_decoder') +HIGH = 'shape_flow_1024' +TEXTURE = ('tex_flow_512', 'tex_flow_1024', 'tex_decoder') +NAMES = frozenset(BASE + (HIGH,) + TEXTURE) + + +def textured(config): + return all(name in config.get("components", {}) for name in TEXTURE) + + +def required_components(config, resolution): + if type(resolution) is not int or resolution not in (512, 1024, 1536): + raise ValueError('TRELLIS.2 resolution must be 512, 1024 or 1536.') + names = BASE + ((HIGH,) if resolution > 512 else ()) + if textured(config): + names += (('tex_flow_512' if resolution == 512 else 'tex_flow_1024'), 'tex_decoder') + return names + + +def checkpoint_bytes(path, names): + if any(name not in NAMES for name in names): + raise ValueError('Unknown TRELLIS component.') + return {name: (Path(path) / (name + '.safetensors')).stat().st_size for name in names} diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/convert.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/convert.py index d4fa6a6..1f87e4b 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/convert.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/convert.py @@ -1,4 +1,5 @@ -"""Convert a local TRELLIS.2 image-to-3D checkpoint, with its image encoder and structure decoder, to MLX weights.""" +"""Convert a local TRELLIS.2 image-to-3D checkpoint (shape and texture stages), with its image encoder and structure +decoder, to MLX weights.""" import argparse import json @@ -16,10 +17,15 @@ "shape_flow_512": ("shape_slat_flow_model_512", "SLatFlowModel"), "shape_flow_1024": ("shape_slat_flow_model_1024", "SLatFlowModel"), "shape_decoder": ("shape_slat_decoder", "FlexiDualGridVaeDecoder"), + "tex_flow_512": ("tex_slat_flow_model_512", "SLatFlowModel"), + "tex_flow_1024": ("tex_slat_flow_model_1024", "SLatFlowModel"), + "tex_decoder": ("tex_slat_decoder", "SparseUnetVaeDecoder"), } -QUANTIZED = ("image_encoder", "ss_flow", "shape_flow_512", "shape_flow_1024") +QUANTIZED = ("image_encoder", "ss_flow", "shape_flow_512", "shape_flow_1024", "tex_flow_512", "tex_flow_1024") FLOW_FLAGS = {"pe_mode": "rope", "share_mod": True, "qk_rms_norm": True, "qk_rms_norm_cross": True} SAMPLERS = ("sparse_structure_sampler", "shape_slat_sampler") +TEXTURE_SAMPLER = "tex_slat_sampler" +NORMALIZATIONS = ("shape_slat_normalization", "tex_slat_normalization") ENCODER_TYPE = "dinov3_vit" RESOLUTIONS = (512, 1024, 1536) DEFAULT_RESOLUTION = 1024 @@ -69,6 +75,8 @@ def _plan(base, sources): files[component] = Path(str(stem) + ".safetensors") if kind.endswith("FlowModel"): _check_flow(key, configs[component]) + if configs["tex_decoder"].get("pred_subdiv", True): + raise ValueError("tex_slat_decoder must follow the shape decoder's subdivision.") encoder = (args.get("image_cond_model") or {}) if encoder.get("name") != "DinoV3FeatureExtractor": raise ValueError("Only the DINOv3 image condition model is supported.") @@ -82,10 +90,12 @@ def _plan(base, sources): missing = [str(path) for path in files.values() if not path.is_file()] if missing: raise ValueError("The checkpoint is missing: " + ", ".join(missing)) - settings = {name: args[name]["params"] for name in SAMPLERS if name in args} - if len(settings) != len(SAMPLERS) or "shape_slat_normalization" not in args: + samplers = SAMPLERS + (TEXTURE_SAMPLER,) + settings = {name: args[name]["params"] for name in samplers if name in args} + if len(settings) != len(samplers) or any(name not in args for name in NORMALIZATIONS): raise ValueError("pipeline.json lacks the sampler or normalization settings.") - settings["shape_slat_normalization"] = args["shape_slat_normalization"] + for name in NORMALIZATIONS: + settings[name] = args[name] return files, configs, settings diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/flow.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/flow.py index 004c985..94a77b3 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/flow.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/flow.py @@ -112,10 +112,13 @@ def _guided(x_t, t, positive, negative, strength, rescale): def sample(w, config, noise, cond, neg_cond, rope, steps, guidance_strength, guidance_rescale, guidance_interval, rescale_t, extra=None, proj=None): """Euler integration from t=1 to 0; classifier-free guidance only inside ``guidance_interval``. + A list ``cond`` conditions step ``i`` on view ``i % len(cond)``, TRELLIS's stochastic multi-image mode. The unconditional branch of a projection-conditioned model sees zero projected features.""" + views = list(cond) if isinstance(cond, (list, tuple)) else [cond] x = noise both_proj = None if proj is None else mx.concatenate([proj, mx.zeros_like(proj)], axis=0) - for t, t_prev in schedule(steps, rescale_t): + for index, (t, t_prev) in enumerate(schedule(steps, rescale_t)): + cond = views[index % len(views)] guided = guidance_strength != 1 and guidance_interval[0] <= t <= guidance_interval[1] inputs = x if extra is None else mx.concatenate([x, extra], axis=-1) if guided: diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/guide.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/guide.py new file mode 100644 index 0000000..5e63504 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/guide.py @@ -0,0 +1,166 @@ +"""Surface voxels of a guide mesh, used in place of the sampled sparse structure.""" + +import json +import os +import struct +from pathlib import Path + +import numpy as np + +COMPONENTS = {5121: np.uint8, 5123: np.uint16, 5125: np.uint32, 5126: np.float32} +WIDTHS = {"SCALAR": 1, "VEC3": 3} +TRIANGLES = 4 +CHUNK_POINTS = 1 << 21 + + +def _chunks(path): + data = Path(path).read_bytes() + if len(data) < 20 or data[:4] != b"glTF": + raise ValueError("The guide must be a binary glTF (.glb) file.") + _, version, length = struct.unpack_from(" len(binary): + raise ValueError("A guide accessor reads past the GLB binary chunk.") + rows = np.ndarray((count, width), dtype=dtype, buffer=binary, offset=start, strides=(stride, dtype.itemsize)) + return np.array(rows) + + +def _matrix(node): + if "matrix" in node: + return np.asarray(node["matrix"], dtype=np.float64).reshape(4, 4).T + x, y, z, w = node.get("rotation", (0, 0, 0, 1)) + rotation = np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) + matrix = np.eye(4) + matrix[:3, :3] = rotation * np.asarray(node.get("scale", (1, 1, 1)), dtype=np.float64)[None] + matrix[:3, 3] = node.get("translation", (0, 0, 0)) + return matrix + + +def read(path): + """World-space glTF (y-up) vertices and triangle indices of every triangle primitive in the default scene.""" + document, binary = _chunks(path) + nodes = document.get("nodes", []) + scenes = document.get("scenes") + if scenes: + roots = scenes[document.get("scene", 0)].get("nodes", []) + else: + children = {child for node in nodes for child in node.get("children", [])} + roots = [index for index in range(len(nodes)) if index not in children] + vertices, faces, count = [], [], 0 + pending = [(index, np.eye(4)) for index in roots] + while pending: + index, parent = pending.pop() + node = nodes[index] + world = parent @ _matrix(node) + pending.extend((child, world) for child in node.get("children", [])) + for primitive in document["meshes"][node["mesh"]]["primitives"] if "mesh" in node else []: + if primitive.get("mode", TRIANGLES) != TRIANGLES or "POSITION" not in primitive.get("attributes", {}): + continue + positions = _accessor(document, binary, primitive["attributes"]["POSITION"], "VEC3", (5126,)) + if "indices" in primitive: + indices = _accessor(document, binary, primitive["indices"], "SCALAR", (5121, 5123, 5125))[:, 0] + else: + indices = np.arange(len(positions)) + if len(indices) % 3 or (len(indices) and indices.max() >= len(positions)): + raise ValueError("Guide triangles must index existing vertices.") + vertices.append(positions.astype(np.float64) @ world[:3, :3].T + world[:3, 3]) + faces.append(indices.reshape(-1, 3).astype(np.int64) + count) + count += len(positions) + if not faces or not sum(len(group) for group in faces): + raise ValueError("The guide GLB holds no triangles.") + vertices, faces = np.concatenate(vertices), np.concatenate(faces) + if not np.isfinite(vertices).all(): + raise ValueError("Guide vertices must be finite.") + return vertices, faces + + +def _cells(corners, level, resolution): + side = np.arange(level + 1) + i, j = np.meshgrid(side, side, indexing="ij") + keep = i + j <= level + u, v = i[keep] / level, j[keep] / level + weights = np.stack([1 - u - v, u, v], axis=1) + found = [] + for start in range(0, len(corners), max(1, CHUNK_POINTS // len(weights))): + points = np.einsum("sk,fkd->fsd", weights, corners[start:start + max(1, CHUNK_POINTS // len(weights))]) + cells = np.floor((points.reshape(-1, 3) + 0.5) * resolution).astype(np.int64) + found.append(np.unique(np.clip(cells, 0, resolution - 1), axis=0)) + return found + + +def surface_coords(path, resolution): + """Integer (x, y, z) voxels at ``resolution`` that the guide's surface passes through, after centering the guide + in the unit cube with its largest extent spanning it; TRELLIS axes are z-up with the glTF front facing -y. + Also returns the glTF-axes center and the extent that map the unit cube back onto the guide.""" + vertices, faces = read(path) + upright = np.stack([vertices[:, 0], -vertices[:, 2], vertices[:, 1]], axis=1) + used = upright[np.unique(faces)] + low, high = used.min(axis=0), used.max(axis=0) + extent = float((high - low).max()) + if not extent > 0: + raise ValueError("The guide mesh has no extent.") + center = (low + high) / 2 + corners = ((upright - center) / extent)[faces] + # Samples at most half a cell apart along each edge reach every voxel the triangle crosses. + edges = np.linalg.norm(corners - corners[:, [1, 2, 0]], axis=2).max(axis=1) + levels = np.maximum(np.ceil(edges * 2 * resolution), 1).astype(np.int64) + found = [] + for level in np.unique(levels): + found.extend(_cells(corners[levels == level], int(level), resolution)) + coords = np.unique(np.concatenate(found), axis=0).astype(np.int32) + return coords, np.array([center[0], center[2], -center[1]]), extent + + +def place(path, center, extent): + """Rewrite a generated unit-cube GLB's positions as ``position * extent + center``, the guide's frame.""" + document, binary = _chunks(path) + binary = bytearray(binary) + accessor = document["accessors"][document["meshes"][0]["primitives"][0]["attributes"]["POSITION"]] + view = document["bufferViews"][accessor["bufferView"]] + if view.get("byteStride", 12) != 12 or accessor["componentType"] != 5126: + raise ValueError("Generated positions must be packed float32 triples.") + start = view.get("byteOffset", 0) + accessor.get("byteOffset", 0) + positions = np.frombuffer(bytes(binary), dtype=" LOW_RESOLUTION: - cond_high = dinov3.encode(weights["image_encoder"], encoder, dinov3.pixels(picture, CASCADE_FLOOR)) + cond_high = [dinov3.encode(weights["image_encoder"], encoder, dinov3.pixels(picture, CASCADE_FLOOR)) + for picture in pictures] cursor = time.perf_counter() stages["conditioning"] = cursor - started - ss = config["components"]["ss_flow"] - grid = ss["resolution"] - noise = _noise(rng, (1, ss["in_channels"], grid ** 3)).transpose(0, 2, 1) - rope = flow.rope_tables(flow.grid_positions(grid), ss["model_channels"] // ss["num_heads"]) - latent = flow.sample(weights["ss_flow"], ss, noise, cond_low, mx.zeros_like(cond_low), rope, - **_sampler(settings["sparse_structure_sampler"], steps, guidance)) - logits = structure.decode(weights["ss_decoder"], config["components"]["ss_decoder"], - latent.reshape(1, grid, grid, grid, -1)) - coords = structure.occupied(logits, LOW_RESOLUTION // 16) + if guide is None: + ss = config["components"]["ss_flow"] + grid = ss["resolution"] + noise = _noise(rng, (1, ss["in_channels"], grid ** 3)).transpose(0, 2, 1) + rope = flow.rope_tables(flow.grid_positions(grid), ss["model_channels"] // ss["num_heads"]) + latent = flow.sample(weights["ss_flow"], ss, noise, cond_low, mx.zeros_like(cond_low[0]), rope, + **_sampler(settings["sparse_structure_sampler"], steps, guidance)) + logits = structure.decode(weights["ss_decoder"], config["components"]["ss_decoder"], + latent.reshape(1, grid, grid, grid, -1)) + coords = structure.occupied(logits, LOW_RESOLUTION // 16) + else: + coords, guide_center, guide_extent = surface_coords(guide, LOW_RESOLUTION // 16) previous, cursor = cursor, time.perf_counter() - stages["sparse_structure"] = cursor - previous + stages["sparse_structure" if guide is None else "guide"] = cursor - previous shape_params = _sampler(settings["shape_slat_sampler"], steps, guidance) normalization = settings["shape_slat_normalization"] low = config["components"]["shape_flow_512"] head_dim = low["model_channels"] // low["num_heads"] slat = flow.sample(weights["shape_flow_512"], low, _noise(rng, (1, len(coords), low["in_channels"])), - cond_low, mx.zeros_like(cond_low), flow.rope_tables(coords, head_dim), **shape_params) + cond_low, mx.zeros_like(cond_low[0]), flow.rope_tables(coords, head_dim), **shape_params) slat = _denormalize(slat[0], normalization) previous, cursor = cursor, time.perf_counter() stages["shape_latent_512"] = cursor - previous @@ -120,23 +219,57 @@ def generate(model, image, out, steps=12, seed=42, resolution=1024, guidance=7.5 coords, level_resolution = cascade_coords(upsampled, LOW_RESOLUTION, resolution) high = config["components"]["shape_flow_1024"] slat = flow.sample(weights["shape_flow_1024"], high, _noise(rng, (1, len(coords), high["in_channels"])), - cond_high, mx.zeros_like(cond_high), flow.rope_tables(coords, head_dim), **shape_params) + cond_high, mx.zeros_like(cond_high[0]), flow.rope_tables(coords, head_dim), **shape_params) slat = _denormalize(slat[0], normalization) previous, cursor = cursor, time.perf_counter() stages["shape_latent_high"] = cursor - previous - voxels, vertices, crossed, split = sparse.decode(weights["shape_decoder"], decoder, slat, coords) + paint = textured(config) + texture_latent = None + if paint: + name = "tex_flow_512" if resolution == LOW_RESOLUTION else "tex_flow_1024" + tex, cond = config["components"][name], cond_low if cond_high is None else cond_high + shape = (slat - mx.array(normalization["mean"], dtype=mx.float32)) / mx.array(normalization["std"], + dtype=mx.float32) + params = settings["tex_slat_sampler"] + noise = _noise(rng, (1, len(coords), tex["in_channels"] - shape.shape[-1])) + texture_latent = flow.sample(weights[name], tex, noise, cond, mx.zeros_like(cond[0]), + flow.rope_tables(coords, head_dim), extra=shape[None], + **_sampler(params, steps, params["guidance_strength"])) + texture_latent = _denormalize(texture_latent[0], settings["tex_slat_normalization"]) + previous, cursor = cursor, time.perf_counter() + stages["texture_latent"] = cursor - previous + subdivisions = [] + voxels, vertices, crossed, split = sparse.decode(weights["shape_decoder"], decoder, slat, coords, subdivisions) previous, cursor = cursor, time.perf_counter() stages["decode"] = cursor - previous + attributes = None + if paint: + _, attributes = sparse.decode_attributes(weights["tex_decoder"], config["components"]["tex_decoder"], + texture_latent, coords, subdivisions) + previous, cursor = cursor, time.perf_counter() + stages["texture_decode"] = cursor - previous vertices, faces = dual_grid.to_mesh(voxels, vertices, crossed, split, level_resolution) - vertices = gltf_axes(vertices) previous, cursor = cursor, time.perf_counter() stages["mesh"] = cursor - previous - vertices, faces = decimate(vertices, faces, max_faces) + vertices, faces = closed.closed_surface(vertices, faces, level_resolution) + vertices = gltf_axes(vertices) + previous, cursor = cursor, time.perf_counter() + stages["closed_surface"] = cursor - previous + vertices, faces = closed.without_fins(*decimate(vertices, faces, max_faces, aggression=3)) previous, cursor = cursor, time.perf_counter() stages["decimation"] = cursor - previous - write_glb(out, vertices, faces) + colors = materials = None + if paint: + upright = np.stack([vertices[:, 0], -vertices[:, 2], vertices[:, 1]], axis=1) + colors, materials = vertex_materials(voxel_colors(upright, voxels, attributes[:, :5], level_resolution)) + write_glb(out, vertices, faces, colors, materials) stages["export"] = time.perf_counter() - cursor + if guide is not None: + # The guided mesh replaces the guide in place, ready to bake onto it. + place(out, guide_center, guide_extent) return {"path": str(out), "seconds": round(time.perf_counter() - started, 3), "steps": steps, + "views": len(pictures), "guided": guide is not None, "seed": seed, "resolution": level_resolution, "vertices": len(vertices), "faces": len(faces), - "voxels": len(voxels), "stage_seconds": {name: round(value, 3) for name, value in stages.items()}, + "voxels": len(voxels), "vertex_colors": paint, "pbr": paint, + "stage_seconds": {name: round(value, 3) for name, value in stages.items()}, "peak_memory_gb": round(mx.get_peak_memory() / 1e9, 3)} diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/sparse.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/sparse.py index 7a249db..7ce2b4d 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/sparse.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/sparse.py @@ -88,18 +88,20 @@ def subdivide(voxels, feats, keep): return coords, split -def up_block(w, name, voxels, out_channels): - """Channel-to-space residual block: predicts which octants exist and moves channels into them.""" - subdiv = w.linear(name + ".to_subdiv", voxels.feats) +def up_block(w, name, voxels, out_channels, keep=None): + """Channel-to-space residual block: moves channels into the octants that exist, predicted here unless ``keep`` + (N, 8) gives them. Returns the child voxels and the octants kept.""" + if keep is None: + keep = np.array(w.linear(name + ".to_subdiv", voxels.feats) > 0) h = nn.silu(_norm(w, name + ".norm1", voxels.feats)) h = sparse_conv(w, name + ".conv1", voxels.replace(h)).feats - coords, (h, skip) = subdivide(voxels, (h, voxels.feats), np.array(subdiv > 0)) + coords, (h, skip) = subdivide(voxels, (h, voxels.feats), keep) child = Voxels(h, coords) h = nn.silu(mx.fast.layer_norm(h, None, None, 1e-6)) h = sparse_conv(w, name + ".conv2", child.replace(h)).feats repeat = out_channels // skip.shape[1] skip = mx.repeat(skip, repeat, axis=1) if repeat > 1 else skip - return child.replace(h + skip) + return child.replace(h + skip), keep def _levels(config): @@ -107,8 +109,9 @@ def _levels(config): return [(level, channels[level], blocks[level]) for level in range(len(blocks))] -def run(w, config, feats, coords, stop_level=None): - """Decoder trunk: returns the last level's voxels, or the coordinates reached at ``stop_level``.""" +def run(w, config, feats, coords, stop_level=None, subdivisions=None, guide=None): + """Decoder trunk: returns the last level's voxels, or the coordinates reached at ``stop_level``. A list passed as + ``subdivisions`` receives each level's kept octants; ``guide`` replays such a list instead of predicting them.""" voxels = Voxels(w.linear("from_latent", feats), coords) channels = config["model_channels"] for level, width, count in _levels(config): @@ -118,14 +121,26 @@ def run(w, config, feats, coords, stop_level=None): voxels = convnext_block(w, "blocks.{0}.{1}".format(level, index), voxels) mx.eval(voxels.feats) if level < len(channels) - 1: - voxels = up_block(w, "blocks.{0}.{1}".format(level, count), voxels, channels[level + 1]) + voxels, keep = up_block(w, "blocks.{0}.{1}".format(level, count), voxels, channels[level + 1], + None if guide is None else guide[level]) + if subdivisions is not None: + subdivisions.append(keep) mx.eval(voxels.feats) return voxels -def decode(w, config, feats, coords): +def decode_attributes(w, config, feats, coords, guide): + """Per-voxel attributes in [0, 1] (base color, metallic, roughness, alpha) on the voxels a shape decode produced + with the subdivisions ``guide``; rows follow that decode's voxel order.""" + voxels = run(w, config, feats, coords, guide=guide) + h = w.linear("output_layer", mx.fast.layer_norm(voxels.feats, None, None, 1e-5)) * 0.5 + 0.5 + mx.eval(h) + return voxels.coords, np.array(h) + + +def decode(w, config, feats, coords, subdivisions=None): """Per-voxel dual vertex (3), edge crossing flags (3) and quad split weight (1) at the output level.""" - voxels = run(w, config, feats, coords) + voxels = run(w, config, feats, coords, subdivisions=subdivisions) h = w.linear("output_layer", mx.fast.layer_norm(voxels.feats, None, None, 1e-5)) margin = 0.5 vertices = (1 + 2 * margin) * mx.sigmoid(h[:, 0:3]) - margin diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/denoiser_cache.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/denoiser_cache.py new file mode 100644 index 0000000..b7b3aea --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/denoiser_cache.py @@ -0,0 +1,110 @@ +"""Per-generation, first-block-gated residual forecasts for TripoSG.""" +import math +from collections import Counter + + +class DenoiserCache: + def __init__(self, steps, memory_limit_bytes=256 * 1024 ** 2, threshold=.0125): + if type(steps) is not int or steps < 1 or type(memory_limit_bytes) is not int or memory_limit_bytes < 1: + raise ValueError('Cache steps and byte limit must be positive integers.') + if not math.isfinite(threshold) or threshold < 0: + raise ValueError('Cache threshold must be finite and nonnegative.') + self.steps, self.memory_limit_bytes, self.threshold = steps, memory_limit_bytes, threshold + self.calls = self.reused = self.age = self.streak = self.peak_bytes = 0 + self.accumulated = 0.0 + self.signature = None + self.owners = None + self.anchors = [] + self.current_probe = self.first_output = None + self.current_time = self.factor = 0.0 + self.reuse = False + self.reasons = Counter() + + def decide(self, error, signature, cache_bytes): + index = self.calls + self.calls += 1 + if signature != self.signature: + self.close() + self.signature, self.age, self.streak, self.accumulated = signature, 0, 0, 0.0 + self.age += 1 + if cache_bytes <= 0 or cache_bytes > self.memory_limit_bytes: + reason = 'memory_limit' + elif not math.isfinite(error) or error < 0: + reason = 'invalid_indicator' + self.age = 0 + else: + self.peak_bytes = max(self.peak_bytes, cache_bytes) + self.accumulated += error + if self.age <= 3: + reason = 'warmup' + elif index >= self.steps - 2: + reason = 'final_refresh' + elif self.streak >= 1: + reason = 'reuse_limit' + elif self.threshold == 0 or self.accumulated >= self.threshold: + reason = 'threshold' + else: + self.streak += 1 + self.reused += 1 + return True + self.streak, self.accumulated = 0, 0.0 + self.reasons[reason] += 1 + return False + + def begin(self, weights, features, first_input, first_output, timestep): + import mlx.core as mx + + signature = (id(weights), id(features), first_output.shape, str(first_output.dtype)) + if signature != self.signature: + self.anchors.clear() + probe = first_output - first_input + error, factor = 0.0, 0.0 + if len(self.anchors) == 2: + earlier, latest = self.anchors + gap = latest[0] - earlier[0] + factor = (timestep - latest[0]) / gap if gap else 0.0 + predicted = latest[1] + factor * (latest[1] - earlier[1]) + error = (mx.mean(mx.abs(probe.astype(mx.float32) - predicted.astype(mx.float32))) / + mx.maximum(mx.mean(mx.abs(probe.astype(mx.float32))), 1e-6)).item() + if not math.isfinite(factor) or not 0 < factor <= 2: + error = math.inf + if not math.isfinite(timestep): + error = math.inf + if len(self.anchors) < 2 and signature == self.signature and self.age >= 3: + error = math.inf + size = 6 * probe.nbytes + self.reuse = self.decide(error, signature, size) and len(self.anchors) == 2 + self.current_time, self.factor = timestep, factor + self.owners = weights, features + if not self.reuse and size <= self.memory_limit_bytes: + mx.async_eval(probe) + self.current_probe, self.first_output = probe, first_output + elif size > self.memory_limit_bytes: + self.anchors.clear() + self.current_probe = self.first_output = None + return self.reuse + + def predict(self, first_output): + earlier, latest = self.anchors + return first_output + (latest[2] + self.factor * (latest[2] - earlier[2])) + + def record(self, output): + import mlx.core as mx + + if self.first_output is not None: + residual = output - self.first_output + mx.async_eval(residual) + self.anchors = (self.anchors + [(self.current_time, self.current_probe, residual)])[-2:] + self.current_probe = self.first_output = None + + def close(self): + self.anchors.clear() + self.current_probe = self.first_output = self.owners = None + self.signature = None + self.reuse = False + + def stats(self): + return {'mode':'adaptive', 'threshold':self.threshold, 'max_reuses':1, + 'full_steps':self.calls-self.reused, 'reused_steps':self.reused, + 'peak_cache_bytes':self.peak_bytes, 'memory_limit_bytes':self.memory_limit_bytes, + 'refresh_reasons':dict(self.reasons)} diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/geometry.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/geometry.py index f7947c2..ceb89be 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/geometry.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/geometry.py @@ -1,6 +1,8 @@ """Iso-surface extraction, triangle-cap decimation and a self-contained binary glTF mesh writer.""" +import io import json +import math import struct import time @@ -35,37 +37,109 @@ def extract_mesh(query, depth=9, bounds=DEFAULT_BOUNDS, seconds=None): return vertices, faces, counts -def decimate(vertices, faces, max_faces): - """Quadric edge collapse down to `max_faces` triangles; meshes at or under the cap pass through.""" +def decimate(vertices, faces, max_faces, aggression=7): + """Quadric edge collapse down to `max_faces` triangles; meshes at or under the cap pass through. + + A lower `aggression` raises the error threshold more slowly, which joins fewer separate sheets along an edge. + """ if len(faces) <= max_faces: return vertices, faces from fast_simplification import simplify points, triangles = simplify(np.ascontiguousarray(vertices, dtype=np.float32), - np.ascontiguousarray(faces, dtype=np.int32), target_count=max_faces) + np.ascontiguousarray(faces, dtype=np.int32), target_count=max_faces, agg=aggression) return points.astype(np.float32), triangles -def write_glb(path, vertices, faces): +def _material_atlas(materials, faces): + """Bake independent triangle islands into a linear occlusion/roughness/metallic PNG.""" + from PIL import Image + + count = len(faces) + columns = math.isqrt(count - 1) + 1 + rows = (count + columns - 1) // columns + width, height = columns * 8, rows * 8 + if width > 8192 or height > 8192: + raise ValueError("Material atlas exceeds the 8192-pixel export bound; lower the face cap.") + atlas = np.zeros((height, width, 3), dtype=np.uint8) + tiles = atlas.reshape(rows, 8, columns, 8, 3).transpose(0, 2, 1, 3, 4) + yy, xx = np.mgrid[0:8, 0:8] + u, v = (xx - 1) / 5, (yy - 1) / 5 + weights = np.stack((1 - u - v, u, v), axis=-1).clip(0) + weights /= weights.sum(axis=-1, keepdims=True) + for start in range(0, count, 4096): + end = min(start + 4096, count) + ids = np.arange(start, end) + baked = np.einsum("hwv,fvc->fhwc", weights, materials[faces[start:end]]) + tiles[ids // columns, ids % columns] = np.rint(baked * 255).astype(np.uint8) + ids = np.arange(count) + origins = np.stack(((ids % columns) * 8, (ids // columns) * 8), axis=1) + corners = np.array([[1.5, 1.5], [6.5, 1.5], [1.5, 6.5]]) + uv = ((origins[:, None, :] + corners) / [width, height]).astype("= len(vertices): raise ValueError("Mesh faces must index existing vertices.") + if colors is not None: + colors = np.ascontiguousarray(colors, dtype=" 1: + raise ValueError("Vertex colors must be one RGB value in [0, 1] per vertex.") + if materials is not None: + # glTF numbers COLOR_n attributes from 0 without gaps. + if colors is None: + raise ValueError("Vertex materials need vertex colors.") + materials = np.ascontiguousarray(materials, dtype=" 1): + raise ValueError("Vertex materials must be one occlusion, roughness and metallic value in [0, 1] " + "per vertex.") + image = None + if materials is not None: + uv, image = _material_atlas(materials, faces) + references = faces.ravel() + vertices, colors, materials = vertices[references], colors[references], materials[references] + faces = np.arange(len(references), dtype=" 1 else latents - prediction = denoise(weights["transformer"], transformer, inputs, - [timestep] * inputs.shape[0], features) - if guidance > 1: - unconditioned, conditioned = mx.split(prediction, 2, axis=0) - prediction = unconditioned + guidance * (conditioned - unconditioned) - latents = latents + delta * prediction - mx.eval(latents) + context_cache = _CrossAttentionCache(weights["transformer"], features) + cache, cache_result = None, None + if denoiser_cache == 'adaptive': + from .denoiser_cache import DenoiserCache + + limit = cache_memory_mib * 1024 ** 2 + reservation = 6 * features.shape[0] * (NUM_TOKENS + 1) * transformer['width'] * 4 + if reservation <= limit: + cache = DenoiserCache(steps, limit) + else: + cache_result = {'mode':'adaptive', 'full_steps':steps, 'reused_steps':0, + 'peak_cache_bytes':0, 'memory_limit_bytes':limit, 'fallback_reason':'memory_limit'} + try: + for timestep, delta in flow_schedule(config["scheduler"], steps): + inputs = mx.concatenate([latents, latents], axis=0) if guidance > 1 else latents + prediction = denoise(weights["transformer"], transformer, inputs, + [timestep] * inputs.shape[0], features, context_cache=context_cache, + **({'denoiser_cache':cache} if cache is not None else {})) + if guidance > 1: + unconditioned, conditioned = mx.split(prediction, 2, axis=0) + prediction = unconditioned + guidance * (conditioned - unconditioned) + latents = latents + delta * prediction + mx.eval(latents) + finally: + if cache is not None: + cache.close() + del context_cache previous, cursor = cursor, time.perf_counter() stages["sampling"] = cursor - previous decoder = Decoder(weights["vae"], config["components"]["vae"], latents) + query = FieldQuery(decoder) context = time.perf_counter() - cursor decode = {} - vertices, faces, queries = extract_mesh(FieldQuery(decoder), resolution.bit_length() - 1, seconds=decode) + vertices, faces, queries = extract_mesh(query, resolution.bit_length() - 1, seconds=decode) stages["decode_dense"] = decode["decode_dense"] + context stages["decode_refine"] = decode["decode_refine"] stages["marching_cubes"] = decode["marching_cubes"] @@ -106,7 +136,10 @@ def generate(model, image, out, steps=50, seed=42, resolution=512, guidance=7.0, stages["decimation"] = cursor - previous write_glb(out, vertices, faces) stages["export"] = time.perf_counter() - cursor - return {"path": str(out), "seconds": round(time.perf_counter() - started, 3), "steps": steps, + result = {"path": str(out), "seconds": round(time.perf_counter() - started, 3), "steps": steps, "seed": seed, "resolution": resolution, "vertices": len(vertices), "faces": len(faces), "queries": queries, "stage_seconds": {name: round(value, 3) for name, value in stages.items()}, "peak_memory_gb": round(mx.get_peak_memory() / 1e9, 3)} + if denoiser_cache == 'adaptive': + result['denoiser_cache'] = cache.stats() if cache is not None else cache_result + return result diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/transformer.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/transformer.py index 66067c7..edfe69e 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/transformer.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/triposg/transformer.py @@ -6,40 +6,72 @@ import mlx.nn as nn -def attention(w, name, x, heads, context=None, qk_norm=False, cross_norm=False): - cross = context is not None - context = x if context is None else context +def _cross_keys_values(w, name, context, heads, dim, qk_norm, cross_norm): if cross_norm: context = w.norm(name + ".norm_cross", context) - q, k, v = (w.linear(name + ".to_" + key, value) for key, value in - (("q", x), ("k", context), ("v", context))) + k, v = (w.linear(name + ".to_" + key, context) for key in ("k", "v")) + batch = context.shape[0] + k, v = mx.split(mx.concatenate([k, v], axis=-1).reshape(batch, -1, heads, 2 * dim), 2, axis=-1) + k, v = (a.reshape(batch, -1, heads, dim).transpose(0, 2, 1, 3) for a in (k, v)) + return (w.rms(name + ".norm_k", k) if qk_norm else k), v + + +class _CrossAttentionCache: + """Fixed conditioning for one generation or point decoder, never a resident model.""" + + def __init__(self, weights, context): + self.weights, self.context = weights, context + self.values = {} + + def get(self, w, name, context, heads, dim, qk_norm, cross_norm): + if w is not self.weights or context is not self.context: + raise ValueError("Cross-attention cache belongs to another conditioning input.") + key = name, heads, dim, qk_norm, cross_norm + if key not in self.values: + k, v = _cross_keys_values(w, name, context, heads, dim, qk_norm, cross_norm) + mx.eval(k, v) + self.values[key] = k, v + return self.values[key] + + +def attention(w, name, x, heads, context=None, qk_norm=False, cross_norm=False, context_cache=None): + cross = context is not None + context = x if context is None else context + q = w.linear(name + ".to_q", x) batch, length, width = q.shape dim = width // heads # The released checkpoint concatenates projections, then splits within each # head. Splitting the projection into ordinary heads changes the model. if cross: - k, v = mx.split(mx.concatenate([k, v], axis=-1).reshape(batch, -1, heads, 2 * dim), 2, axis=-1) + get = _cross_keys_values if context_cache is None else context_cache.get + k, v = get(w, name, context, heads, dim, qk_norm, cross_norm) + q = q.reshape(batch, length, heads, dim).transpose(0, 2, 1, 3) + if qk_norm: + q = w.rms(name + ".norm_q", q) else: + if cross_norm: + context = w.norm(name + ".norm_cross", context) + k, v = (w.linear(name + ".to_" + key, context) for key in ("k", "v")) q, k, v = mx.split(mx.concatenate([q, k, v], axis=-1).reshape(batch, length, heads, 3 * dim), 3, axis=-1) - q, k, v = [a.reshape(batch, -1, heads, dim).transpose(0, 2, 1, 3) for a in (q, k, v)] - if qk_norm: - q, k = w.rms(name + ".norm_q", q), w.rms(name + ".norm_k", k) + q, k, v = [a.reshape(batch, -1, heads, dim).transpose(0, 2, 1, 3) for a in (q, k, v)] + if qk_norm: + q, k = w.rms(name + ".norm_q", q), w.rms(name + ".norm_k", k) y = mx.fast.scaled_dot_product_attention(q, k, v, scale=dim ** -0.5) return w.linear(name + ".to_out.0", y.transpose(0, 2, 1, 3).reshape(batch, length, width)) -def block(w, name, x, heads, context=None, self_attention=True, qk_norm=False, skip=None): +def block(w, name, x, heads, context=None, self_attention=True, qk_norm=False, skip=None, context_cache=None): if skip is not None: x = w.norm(name + ".skip_norm", w.linear(name + ".skip_linear", mx.concatenate([skip, x], axis=-1))) if self_attention: x = x + attention(w, name + ".attn1", w.norm(name + ".norm1", x), heads, qk_norm=qk_norm) if context is not None: x = x + attention(w, name + ".attn2", w.norm(name + ".norm2", x), heads, - context=context, qk_norm=qk_norm, cross_norm=not qk_norm) + context=context, qk_norm=qk_norm, cross_norm=not qk_norm, context_cache=context_cache) return x + w.feed_forward(name + ".ff", w.norm(name + ".norm3", x)) -def denoise(w, config, latents, timestep, image_features): +def denoise(w, config, latents, timestep, image_features, context_cache=None, denoiser_cache=None): width, layers, heads = config["width"], config["num_layers"], config["num_attention_heads"] half = width // 2 frequencies = mx.exp(-math.log(10000) * mx.arange(half, dtype=mx.float32) / half) @@ -49,11 +81,21 @@ def denoise(w, config, latents, timestep, image_features): x = mx.concatenate([embedding[:, None, :], w.linear("proj_in", latents)], axis=1) skips = [] for index in range(layers): + first_input = x if index == 0 and denoiser_cache is not None else None x = block(w, "blocks." + str(index), x, heads, context=image_features, - qk_norm=True, skip=skips.pop() if index > layers // 2 else None) + qk_norm=True, skip=skips.pop() if index > layers // 2 else None, + context_cache=context_cache) + if first_input is not None: + reuse = denoiser_cache.begin(w, image_features, first_input, x, float(timestep[0])) + del first_input + if reuse: + x = denoiser_cache.predict(x) + break if index < layers // 2: skips.append(x) mx.eval(x) + if denoiser_cache is not None and not denoiser_cache.reuse: + denoiser_cache.record(x) return w.linear("proj_out", w.norm("norm_out", x)[:, 1:]) @@ -73,11 +115,20 @@ def __init__(self, weights, config, latents): self.context = block(weights, "decoder.blocks." + str(index), self.context, config["num_attention_heads"]) mx.eval(self.context) + self.context_cache = _CrossAttentionCache(weights, self.context) + + def prepare_context(self): + """Materialize fixed cross-attention projections before tracing point queries.""" + heads = self.config['num_attention_heads'] + self.context_cache.get(self.weights, + 'decoder.blocks.' + str(self.config['num_layers_decoder']) + '.attn2', + self.context, heads, self.context.shape[-1] // heads, False, True) def __call__(self, points): w, config = self.weights, self.config query = position_embedding(points, config["embed_frequency"], config.get("embed_include_pi", False)) query = w.linear("decoder.proj_query", query) query = block(w, "decoder.blocks." + str(config["num_layers_decoder"]), query, - config["num_attention_heads"], context=self.context, self_attention=False) + config["num_attention_heads"], context=self.context, self_attention=False, + context_cache=self.context_cache) return -w.linear("decoder.proj_out", w.norm("decoder.norm_out", query)) diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/__init__.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/__init__.py new file mode 100644 index 0000000..d1a27d0 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/__init__.py @@ -0,0 +1,5 @@ +"""Kev decision model (Qwen3 decoder with a pointer head), ported to MLX by mlx-agent.""" + +from .kev import Model, ModelArgs, load, predict + +__all__ = ["Model", "ModelArgs", "load", "predict"] diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/convert.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/convert.py new file mode 100644 index 0000000..577e59c --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/convert.py @@ -0,0 +1,185 @@ +"""Convert a Kev checkpoint (LoRA adapter and pointer head over a Qwen3 base) to MLX. + +The LoRA is folded into the base weights in float32, then the decoder is cast to bfloat16 +and optionally quantized. The pointer head stays float32. +""" + +from __future__ import annotations + +import argparse +import collections +import io +import json +import math +import pickle +import shutil +import sys +import zipfile +from pathlib import Path + +import mlx.core as mx +import mlx.nn as nn +import numpy as np +from mlx.utils import tree_flatten + +from .kev import TOKENIZER_FILES, Model, ModelArgs + +CHECKPOINT_FILES = ("adapter_config.json", "adapter_model.safetensors", "head.pt") +BASE_FILES = ("config.json",) + TOKENIZER_FILES +QUANTIZE_INCLUDE = ("backbone.embed_tokens", "backbone.layers.") +GROUP_SIZE = 64 +LORA_PREFIX = "base_model.model." +STORAGES = {"FloatStorage": np.float32, "HalfStorage": np.float16} + + +class HeadUnpickler(pickle.Unpickler): + """Reads a torch zip checkpoint of plain tensors and settings; any other global is refused.""" + + def __init__(self, data: bytes, archive: zipfile.ZipFile, prefix: str): + super().__init__(io.BytesIO(data)) + self.archive, self.prefix = archive, prefix + + def find_class(self, module, name): + if (module, name) == ("collections", "OrderedDict"): + return collections.OrderedDict + if (module, name) == ("torch._utils", "_rebuild_tensor_v2"): + return self.tensor + if module == "torch" and name in STORAGES: + return name + raise pickle.UnpicklingError("head.pt references {0}.{1}".format(module, name)) + + def persistent_load(self, pid): + if not (isinstance(pid, tuple) and len(pid) == 5 and pid[0] == "storage" and pid[1] in STORAGES): + raise pickle.UnpicklingError("head.pt holds an unsupported storage") + raw = self.archive.read("{0}data/{1}".format(self.prefix, pid[2])) + return np.frombuffer(raw, dtype=STORAGES[pid[1]]) + + @staticmethod + def tensor(storage, offset, size, stride, *_): + count = math.prod(size) + contiguous = tuple(math.prod(size[index + 1:]) for index in range(len(size))) + if tuple(stride) != contiguous or offset + count > storage.size: + raise pickle.UnpicklingError("head.pt holds a non-contiguous tensor") + return storage[offset:offset + count].reshape(size) + + +def read_head(path: Path) -> dict: + """The head checkpoint's settings and weights (numpy arrays) without importing torch.""" + try: + with zipfile.ZipFile(path) as archive: + names = archive.namelist() + pickles = [name for name in names if name.endswith("/data.pkl")] + if len(pickles) != 1: + raise SystemExit("{0} is not a torch zip checkpoint.".format(path)) + prefix = pickles[0][: -len("data.pkl")] + if prefix + "byteorder" in names and archive.read(prefix + "byteorder").strip() != b"little": + raise SystemExit("{0} is not little-endian.".format(path)) + meta = HeadUnpickler(archive.read(pickles[0]), archive, prefix).load() + except (zipfile.BadZipFile, pickle.UnpicklingError, KeyError, ValueError) as error: + raise SystemExit("{0} is not a readable Kev head: {1}".format(path, error)) from error + if not isinstance(meta, dict) or not isinstance(meta.get("head"), dict): + raise SystemExit("{0} has no head weights.".format(path)) + return meta + + +def lora_scaling(settings: dict, scale: float) -> float: + if (settings.get("peft_type") != "LORA" or settings.get("use_dora") or settings.get("trainable_token_indices") + or settings.get("modules_to_save") or settings.get("rank_pattern") or settings.get("alpha_pattern")): + raise SystemExit("Only a plain LoRA adapter with one rank folds into the base weights.") + rank, alpha = settings["r"], settings["lora_alpha"] + return scale * (alpha / math.sqrt(rank) if settings.get("use_rslora") else alpha / rank) + + +def merged_weights(base: Path, adapter: Path, scaling: float) -> dict: + """The base decoder under backbone names with the LoRA folded in: a float32 sum, stored as bfloat16.""" + weights = {} + for shard in sorted(base.glob("*.safetensors")): + weights.update(mx.load(str(shard))) + lora = mx.load(str(adapter)) + suffix_a, suffix_b = ".lora_A.weight", ".lora_B.weight" + targets = sorted(name[len(LORA_PREFIX):-len(suffix_a)] for name in lora if name.endswith(suffix_a)) + if not targets or set(lora) != {LORA_PREFIX + target + suffix for target in targets for suffix in (suffix_a, suffix_b)}: + raise SystemExit("{0} holds tensors other than LoRA A/B pairs for the decoder.".format(adapter)) + for target in targets: + name = "model.{0}.weight".format(target) + if name not in weights: + raise SystemExit("The adapter targets {0}, which the base does not have.".format(name)) + delta = lora[LORA_PREFIX + target + suffix_b].astype(mx.float32) @ lora[LORA_PREFIX + target + suffix_a].astype(mx.float32) + weights[name] = (weights[name].astype(mx.float32) + scaling * delta).astype(mx.bfloat16) + mx.eval(weights[name]) + result = {} + for name, value in weights.items(): + if name.startswith("lm_head."): + continue + if not name.startswith("model."): + raise SystemExit("The base holds {0}, outside the decoder.".format(name)) + result["backbone." + name[len("model."):]] = value.astype(mx.bfloat16) + return result + + +def quantizes(path: str, module: nn.Module) -> bool: + """Decoder linear layers and the token embedding; norms and the pointer head stay as converted.""" + return ( + isinstance(module, (nn.Linear, nn.Embedding)) + and path.startswith(QUANTIZE_INCLUDE) + and module.weight.shape[-1] % GROUP_SIZE == 0 + ) + + +def convert(hf_path: str, mlx_path: str, quantize: bool = False, q_bits: int = 8, lora: str = None, + lora_scale: float = 1.0) -> Path: + out = Path(mlx_path).expanduser() + if out.exists() and any(out.iterdir()): + raise SystemExit("{0} already exists and is not empty.".format(out)) + if lora is None: + raise SystemExit("Pass the checkpoint's adapter with --lora; --hf-path is its Qwen3 base snapshot.") + base, adapter = Path(hf_path).expanduser(), Path(lora).expanduser() + checkpoint = adapter.parent + missing = [str(checkpoint / name) for name in CHECKPOINT_FILES if not (checkpoint / name).is_file()] + missing += [str(base / name) for name in BASE_FILES if not (base / name).is_file()] + if missing: + raise SystemExit("Not a Kev checkpoint and Qwen3 base; missing {0}.".format(", ".join(missing))) + print("[INFO] Loading {0} over {1}".format(checkpoint, base), flush=True) + meta = read_head(checkpoint / "head.pt") + if meta.get("option_isolation") or meta.get("special_embeddings"): + raise SystemExit("Option isolation and trained delimiter embeddings are not ported.") + backbone = json.loads((base / "config.json").read_text(encoding="utf-8")) + if backbone.get("model_type") != "qwen3": + raise SystemExit("The base is {0!r}; the Kev port runs a qwen3 decoder.".format(backbone.get("model_type"))) + config = {"model_type": "kev", "backbone": backbone, "head_dim": int(meta.get("head_dim", 256))} + config.update({key: meta[key] for key in ("base", "base_revision") if isinstance(meta.get(key), str)}) + settings = json.loads((checkpoint / "adapter_config.json").read_text(encoding="utf-8")) + model = Model(ModelArgs.from_dict(config)) + weights = merged_weights(base, adapter, lora_scaling(settings, lora_scale)) + weights.update({"head." + name: mx.array(value) for name, value in meta["head"].items()}) + model.load_weights(list(weights.items()), strict=True) + del weights + if quantize: + print("[INFO] Quantizing to {0} bits".format(q_bits), flush=True) + nn.quantize(model, group_size=GROUP_SIZE, bits=q_bits, class_predicate=quantizes) + config["quantization"] = {"group_size": GROUP_SIZE, "bits": q_bits} + out.mkdir(parents=True, exist_ok=True) + print("[INFO] Writing {0}".format(out), flush=True) + mx.save_safetensors(str(out / "model.safetensors"), dict(tree_flatten(model.parameters())), metadata={"format": "mlx"}) + for name in TOKENIZER_FILES: + shutil.copyfile(base / name, out / name) + (out / "config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8") + print("[INFO] Conversion complete", flush=True) + return out + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--hf-path", required=True, help="the Qwen3 base snapshot directory") + parser.add_argument("--mlx-path", required=True, help="destination directory") + parser.add_argument("--lora", required=True, help="the checkpoint's adapter_model.safetensors (head.pt beside it)") + parser.add_argument("--lora-scale", type=float, default=1.0) + parser.add_argument("-q", "--quantize", action="store_true") + parser.add_argument("--q-bits", type=int, default=8, choices=(4, 5, 6, 8)) + arguments = parser.parse_args(argv) + convert(arguments.hf_path, arguments.mlx_path, arguments.quantize, arguments.q_bits, arguments.lora, arguments.lora_scale) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/kev.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/kev.py new file mode 100644 index 0000000..7a7eb49 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-embeddings/kev/kev.py @@ -0,0 +1,247 @@ +"""Kev: a Qwen3 decoder with a pointer head over option spans (jaredpalmer/kev-4b). + +A request renders the state once, then each question as `` instructions``, one +`` option `` span per option and a closing ```` token. Every question runs +as its own causal row of the state tokens followed by its branch, which matches the +checkpoint's block-causal packed layout token for token and position for position. The head +scores the hidden state at each ```` against the ```` state; a softmax over the +options gives the answer distribution. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass +from pathlib import Path +from typing import Dict, List, Optional + +import mlx.core as mx +import mlx.nn as nn + +from mlx_embeddings.models.qwen3 import ModelArgs as BackboneArgs +from mlx_embeddings.models.qwen3 import Qwen3Model + +# Existing Qwen special tokens reused as delimiters: state, question, option open, option close, decide. +DELIMITERS = ("<|fim_prefix|>", "<|fim_middle|>", "<|box_start|>", "<|box_end|>", "<|fim_suffix|>") +TOKENIZER_FILES = ("tokenizer.json", "tokenizer_config.json") +QUESTION_TYPES = ("noul", "choice", "score") +MAX_OPTIONS = 255 +_CONTROL = re.compile(r"<\|([A-Za-z0-9_]+)\|>") + + +@dataclass +class ModelArgs: + backbone: dict + model_type: str = "kev" + head_dim: int = 256 + max_state: int = 8192 + max_branch: int = 8192 + + @classmethod + def from_dict(cls, params: dict) -> "ModelArgs": + names = cls.__dataclass_fields__ + return cls(**{key: value for key, value in params.items() if key in names}) + + +class PointerHead(nn.Module): + """Scaled dot product between the ```` state and each option's closing state.""" + + def __init__(self, dims: int, pointer: int): + super().__init__() + self.q = nn.Linear(dims, pointer) + self.k = nn.Linear(dims, pointer) + self.scale = pointer ** -0.5 + + def __call__(self, decide: mx.array, options: mx.array) -> mx.array: + query = self.q(decide)[:, :, None] + return (self.k(options) @ query).squeeze(-1) * self.scale + + +class Model(nn.Module): + def __init__(self, args: ModelArgs): + super().__init__() + self.args = args + self.backbone = Qwen3Model(BackboneArgs.from_dict(args.backbone)) + self.head = PointerHead(self.backbone.hidden_size, args.head_dim) + + def __call__(self, ids, lengths, decide, options, present): + """Option logits [rows, options] for right-padded rows; absent options are -inf.""" + attention = (mx.arange(ids.shape[1])[None, :] < lengths[:, None]).astype(mx.int32) + hidden = self.backbone(ids, attention_mask=attention).astype(mx.float32) + decided = hidden[mx.arange(ids.shape[0]), decide] + spans = mx.take_along_axis(hidden, options[:, :, None], axis=1) + return mx.where(present, self.head(decided, spans), -mx.inf) + + +# ----------------------------------------------------------------------------- requests + + +class RequestTokenizer: + """Delimiter ids and caller-text tokenization over a ``tokenizers`` file (no transformers).""" + + def __init__(self, directory: Path): + from tokenizers import Tokenizer + + self.tokenizer = Tokenizer.from_file(str(Path(directory) / "tokenizer.json")) + ids = [self.tokenizer.token_to_id(token) for token in DELIMITERS] + missing = [token for token, value in zip(DELIMITERS, ids) if value is None] + if missing: + raise ValueError("the tokenizer has no delimiter tokens {0}".format(", ".join(missing))) + self.state_id, self.question_id, self.open_id, self.close_id, self.decide_id = ids + settings = json.loads((Path(directory) / "tokenizer_config.json").read_text(encoding="utf-8")) + pad = settings.get("pad_token") + pad = pad.get("content") if isinstance(pad, dict) else pad + self.pad_id = (self.tokenizer.token_to_id(pad) if isinstance(pad, str) else None) or 0 + + def user_ids(self, text: str) -> List[int]: + """Caller text never yields a delimiter: ``<|name|>`` is rewritten to ``<¦name¦>`` first.""" + return self.tokenizer.encode(_CONTROL.sub(r"<¦\1¦>", text), add_special_tokens=False).ids + + def count(self, text: str) -> int: + return len(self.tokenizer.encode(text, add_special_tokens=False).ids) + + +def render(value, indent: int = 0) -> str: + """Text, objects and arrays flattened to the text the model reads; field names stay as labels.""" + pad = " " * indent + if value is None: + return "" + if isinstance(value, (str, int, float, bool)): + return str(value) + if isinstance(value, list): + return "\n".join("{0}- {1}".format(pad, render(item, indent + 1).lstrip()) for item in value) + return "\n".join( + "{0}{1}:\n{2}".format(pad, key, render(item, indent + 1)) if isinstance(item, (dict, list)) + else "{0}{1}: {2}".format(pad, key, render(item)) + for key, item in value.items() + ) + + +def option_text(name: str, description) -> str: + return name if description is None or description == "" else "{0}: {1}".format(name, render(description)) + + +def parse_question(name: str, definition: dict) -> dict: + """A request question ({type, instructions, criteria}) as instruction text, option texts and answer metadata.""" + if not isinstance(definition, dict) or definition.get("type") not in QUESTION_TYPES: + raise ValueError("question {0!r} needs a type of {1}".format(name, ", ".join(QUESTION_TYPES))) + kind, criteria = definition["type"], definition.get("criteria") + if kind == "noul": + if criteria is not None and not isinstance(criteria, dict): + raise ValueError("question {0!r}: noul criteria are an object with optional true and false texts".format(name)) + criteria = criteria or {} + options = [option_text("no", criteria.get("false")), option_text("yes", criteria.get("true"))] + meta = {"id": name, "type": "noul"} + elif kind == "choice": + if not isinstance(criteria, dict) or not 1 <= len(criteria) <= MAX_OPTIONS: + raise ValueError("question {0!r}: choice criteria are an object of 1 to {1} options".format(name, MAX_OPTIONS)) + options = [option_text(key, value) for key, value in criteria.items()] + meta = {"id": name, "type": "choice", "keys": list(criteria)} + else: + if not isinstance(criteria, list) or not 2 <= len(criteria) <= MAX_OPTIONS: + raise ValueError("question {0!r}: score criteria are a list of 2 to {1} levels".format(name, MAX_OPTIONS)) + options = [render(level) for level in criteria] + meta = {"id": name, "type": "score", "legend": {str(index): render(level) for index, level in enumerate(criteria)}} + return {"instructions": render(definition.get("instructions")), "options": options, "meta": meta} + + +def build_rows(tok: RequestTokenizer, state, parsed: List[dict], max_state: int, max_branch: int): + """One causal row per question (state + branch) with its readout offsets, and the packed token count.""" + prefix = [tok.state_id] + tok.user_ids(render(state))[: max_state - 1] + rows, packed = [], len(prefix) + for question in parsed: + branch = [tok.question_id] + tok.user_ids(question["instructions"]) + closes = [] + for text in question["options"]: + branch += [tok.open_id] + tok.user_ids(text) + [tok.close_id] + closes.append(len(prefix) + len(branch) - 1) + branch.append(tok.decide_id) + if len(branch) > max_branch - len(prefix): + raise ValueError("question {0!r}: branch too long: {1} tokens".format(question["meta"]["id"], len(branch))) + rows.append({"ids": prefix + branch, "decide": len(prefix) + len(branch) - 1, "options": closes}) + packed += len(branch) + return rows, packed + + +def batch(rows: List[dict], pad_id: int): + length = max(len(row["ids"]) for row in rows) + width = max(len(row["options"]) for row in rows) + ids, options, present = [], [], [] + for row in rows: + ids.append(row["ids"] + [pad_id] * (length - len(row["ids"]))) + count = len(row["options"]) + options.append(row["options"] + [0] * (width - count)) + present.append([True] * count + [False] * (width - count)) + return ( + mx.array(ids, dtype=mx.int32), mx.array([len(row["ids"]) for row in rows], dtype=mx.int32), + mx.array([row["decide"] for row in rows], dtype=mx.int32), + mx.array(options, dtype=mx.int32), mx.array(present), + ) + + +def r2(value: float) -> float: + return round(float(value), 2) + + +def choice_confidence(p: List[float]) -> float: + k = len(p) + return 1.0 if k == 1 else (max(p) - 1 / k) / (1 - 1 / k) + + +def score_confidence(p: List[float]) -> float: + """One minus the expected distance from the modal level, as a fraction of the scale.""" + levels = len(p) + mode = max(range(levels), key=lambda index: p[index]) + return 1.0 - sum(value * abs(index - mode) for index, value in enumerate(p)) / (levels - 1) + + +def answer(p: List[float], meta: dict) -> dict: + if meta["type"] == "noul": + return {"type": "noul", "noul": r2(p[1])} + if meta["type"] == "choice": + keys = meta["keys"] + return {"type": "choice", "choice": keys[max(range(len(p)), key=lambda index: p[index])], + "confidence": r2(choice_confidence(p)), "probabilities": {key: r2(value) for key, value in zip(keys, p)}} + return {"type": "score", "score": r2(sum(index * value for index, value in enumerate(p))), "legend": meta["legend"], + "probabilities": {str(index): r2(value) for index, value in enumerate(p)}, "confidence": r2(score_confidence(p))} + + +def probabilities(model: Model, tok: RequestTokenizer, state, questions: Dict[str, dict]): + """Option distributions in question order, the parsed questions, and the packed token count.""" + if not isinstance(questions, dict) or not questions: + raise ValueError("questions must be a non-empty object of question definitions") + parsed = [parse_question(name, definition) for name, definition in questions.items()] + rows, packed = build_rows(tok, state, parsed, model.args.max_state, model.args.max_branch) + p = mx.softmax(model(*batch(rows, tok.pad_id)), axis=-1) + mx.eval(p) + return [values[:len(row["options"])] for values, row in zip(p.tolist(), rows)], parsed, packed + + +def predict(model: Model, tok: RequestTokenizer, state, questions: Dict[str, dict]) -> dict: + """Answer every question about one state (System One answer shapes).""" + distributions, parsed, packed = probabilities(model, tok, state, questions) + answers = {question["meta"]["id"]: answer(p, question["meta"]) for p, question in zip(distributions, parsed)} + return {"answers": answers, "usage": {"input_tokens": packed, "output_tokens": tok.count(json.dumps(answers))}} + + +def load(path, dtype: Optional[mx.Dtype] = None): + """A converted Kev directory: (model, tokenizer).""" + directory = Path(path) + config = json.loads((directory / "config.json").read_text(encoding="utf-8")) + model = Model(ModelArgs.from_dict(config)) + weights = {} + for shard in sorted(directory.glob("*.safetensors")): + weights.update(mx.load(str(shard))) + quantization = config.get("quantization") + if quantization: + nn.quantize( + model, group_size=quantization["group_size"], bits=quantization["bits"], + class_predicate=lambda name, module: "{0}.scales".format(name) in weights, + ) + model.load_weights(list(weights.items()), strict=True) + if dtype is not None: + model.backbone.set_dtype(dtype) + model.eval() + mx.eval(model.parameters()) + return model, RequestTokenizer(directory) diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-video/t2v/denoiser_cache.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-video/t2v/denoiser_cache.py new file mode 100644 index 0000000..68d4d7a --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-video/t2v/denoiser_cache.py @@ -0,0 +1,182 @@ +"""Bounded, first-block-gated residual forecasting for the Wan2.1 denoiser. + +The policy has no framework dependency. MLX modules are imported only when a +session is attached; retained activations never enter a model parameter tree. +""" + +import math +from collections import Counter + + +class DenoiserCachePolicy: + def __init__(self, steps, threshold=0.0125, max_reuses=3, warmup=3, final_steps=2, + memory_limit_bytes=256 * 1024 ** 2): + for value in (steps, max_reuses, warmup, final_steps, memory_limit_bytes): + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError("cache counts and memory limit must be positive integers") + if not math.isfinite(threshold) or threshold < 0: + raise ValueError("cache threshold must be finite and nonnegative") + self.steps, self.threshold, self.max_reuses = steps, threshold, max_reuses + self.warmup, self.final_steps = warmup, final_steps + self.memory_limit_bytes = memory_limit_bytes + self.calls = self.reused = self.streak = self.age = self.peak_bytes = 0 + self.accumulated = 0.0 + self.signature = None + self.reasons = Counter() + + def decide(self, error, signature, cache_bytes): + """Return whether this call may reuse an established residual.""" + index = self.calls + self.calls += 1 + if signature != self.signature: + self.signature, self.age, self.streak, self.accumulated = signature, 0, 0, 0.0 + self.age += 1 + if cache_bytes > self.memory_limit_bytes or cache_bytes <= 0: + reason = "memory_limit" + elif not math.isfinite(error) or error < 0: + reason = "invalid_indicator" + self.age = 0 + else: + self.peak_bytes = max(self.peak_bytes, cache_bytes) + self.accumulated += error + if self.age <= self.warmup: + reason = "warmup" + elif index >= self.steps - self.final_steps: + reason = "final_refresh" + elif self.streak >= self.max_reuses: + reason = "reuse_limit" + elif self.threshold == 0 or self.accumulated >= self.threshold: + reason = "threshold" + else: + self.reused += 1 + self.streak += 1 + return True + self.streak, self.accumulated = 0, 0.0 + self.reasons[reason] += 1 + return False + + def stats(self): + return {"mode": "adaptive", "threshold": self.threshold, + "max_reuses": self.max_reuses, + "full_steps": self.calls - self.reused, "reused_steps": self.reused, + "peak_cache_bytes": self.peak_bytes, "memory_limit_bytes": self.memory_limit_bytes, + "refresh_reasons": dict(self.reasons)} + + +def required_cache_bytes(config, width, height, frames): + """Six float32 feature buffers, conservatively reserving batched CFG.""" + stride = config.get("vae_stride", (4, 8, 8)) + patch = config.get("patch_size", (1, 2, 2)) + length = ((frames - 1) // stride[0] + 1) * (height // stride[1]) * (width // stride[2]) + length = math.ceil(length / (patch[1] * patch[2])) + return 6 * 2 * length * config["dim"] * 4 + + +class WanDenoiserCache: + """One generation's state; close restores blocks and releases all features.""" + + def __init__(self, steps, memory_limit_bytes, **profile): + profile.setdefault("max_reuses", 1) + self.policy = DenoiserCachePolicy(steps, memory_limit_bytes=memory_limit_bytes, **profile) + self.model = None + self.original_blocks = None + self.anchors = [] + self.current_probe = self.residual = self.first_output = None + self.current_time = 0.0 + self.signature = None + self.reuse = False + + def attach(self, model): + import mlx.core as mx + import mlx.nn as nn + + if self.model is not None or len(model.blocks) < 2: + raise ValueError("cache requires one Wan model with at least two blocks") + session = self + originals = model.blocks + cached = getattr(model, "_mlx_agent_compiled_blocks", None) + identities = tuple(id(block) for block in originals) + if cached is None or cached[0] != identities: + cached = (identities, tuple(mx.compile(block) for block in originals)) + object.__setattr__(model, "_mlx_agent_compiled_blocks", cached) + + class Block(nn.Module): + def __init__(self, index, block, compiled): + super().__init__() + self.block = block + object.__setattr__(self, "index", index) + object.__setattr__(self, "compiled", compiled) + + @property + def cross_attn(self): + return self.block.cross_attn + + def __call__(self, x, **kwargs): + if self.index == 0: + output = self.compiled(x, **kwargs) + signature = (id(kwargs["context"]), id(kwargs.get("cross_kv_cache")), + id(kwargs.get("rope_cos_sin")), x.shape, str(x.dtype), + tuple(kwargs["seq_lens"]), tuple(kwargs["grid_sizes"])) + probe = output - x + same = signature == session.signature + if not same: + session.anchors.clear() + session.residual = None + error = 0.0 + factor = 0.0 + if len(session.anchors) == 2: + earlier, latest = session.anchors + gap = latest[0] - earlier[0] + factor = (session.current_time - latest[0]) / gap if gap else 0.0 + predicted = latest[1] + factor * (latest[1] - earlier[1]) + error = (mx.mean(mx.abs(probe.astype(mx.float32) - predicted.astype(mx.float32))) / + mx.maximum(mx.mean(mx.abs(probe.astype(mx.float32))), 1e-6)).item() + if not gap or not math.isfinite(factor) or not 0 < factor <= 2: + error = math.inf + size = 6 * probe.nbytes + session.reuse = session.policy.decide(error, signature, size) + session.reuse = session.reuse and same and len(session.anchors) == 2 + session.signature = signature + if session.reuse: + session.residual = latest[2] + factor * (latest[2] - earlier[2]) + elif size <= session.policy.memory_limit_bytes: + mx.async_eval(probe) + session.current_probe, session.first_output = probe, output + else: + session.anchors.clear() + session.current_probe = session.first_output = None + return output + if session.reuse: + return x + session.residual if self.index == len(originals) - 1 else x + output = self.compiled(x, **kwargs) + if self.index == len(originals) - 1 and session.first_output is not None: + residual = output - session.first_output + mx.async_eval(residual) + session.anchors = (session.anchors + [(session.current_time, session.current_probe, residual)])[-2:] + session.current_probe = session.first_output = None + return output + + class Forward: + # Override any retained monolithic graph, while keeping native helpers. + def __getattr__(self, name): + return getattr(model, name) + + def _compiled(self, *args, **kwargs): + t = kwargs.get("t") + session.current_time = float(t.reshape(-1)[0].item()) if t is not None else float(session.policy.calls) + return model(*args, **kwargs) + + wrappers = [Block(i, block, cached[1][i]) for i, block in enumerate(originals)] + self.model, self.original_blocks = model, originals + model.blocks = wrappers + return Forward() + + def close(self): + if self.model is not None: + self.model.blocks = self.original_blocks + self.model = self.original_blocks = None + self.anchors.clear() + self.current_probe = self.residual = self.first_output = self.signature = None + + def stats(self): + return self.policy.stats() diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-video/t2v/t2v.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-video/t2v/t2v.py index 2677512..01a43ca 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-video/t2v/t2v.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-video/t2v/t2v.py @@ -25,6 +25,8 @@ class Model: def __init__(self, path: Path, config: dict): self.path = path self.config = config + self.retain_weights = False + self.components = {} def load(path) -> Model: @@ -78,12 +80,31 @@ def _pixel_std(frames) -> float: def generate(model: Model, prompt: str, out: str, width: int = 832, height: int = 480, frames: int = 81, - fps: int = 16, steps: int = 50, seed: int = 42) -> dict: + fps: int = 16, steps: int = 50, seed: int = 42, denoiser_cache: str = "off", + cache_memory_mib: int = 256) -> dict: """Render one video to ``out`` (MP4); returns its dimensions, timing, memory, and pixel spread.""" import mlx.core as mx import mlx_video.generate_wan as wan from transformers import AutoTokenizer + if denoiser_cache not in ("off", "adaptive"): + raise ValueError("denoiser_cache must be off or adaptive") + if isinstance(cache_memory_mib, bool) or not isinstance(cache_memory_mib, int) or not 8 <= cache_memory_mib <= 4096: + raise ValueError("cache_memory_mib must be 8..4096") + cache = None + cache_result = None + if denoiser_cache == "adaptive": + from .denoiser_cache import WanDenoiserCache, required_cache_bytes + + if model.config.get("model_version") != "2.1" or model.config.get("dual_model", False) or model.config.get("model_type") != "t2v": + raise ValueError("adaptive denoiser caching requires single-model Wan2.1 T2V") + limit = cache_memory_mib * 1024 ** 2 + if required_cache_bytes(model.config, width, height, frames) > limit: + cache_result = {"mode": "adaptive", "full_steps": steps, "reused_steps": 0, + "peak_cache_bytes": 0, "memory_limit_bytes": limit, "fallback_reason": "memory_limit"} + else: + cache = WanDenoiserCache(steps, limit) + spent = {"load": 0.0} written = {} original_loaders = {name: getattr(wan, name) for name in LOADERS} @@ -94,7 +115,19 @@ def timed(function): def wrapper(*arguments, **keywords): started = time.time() try: - return function(*arguments, **keywords) + key = repr((arguments, sorted(keywords.items()))) + retained = model.components.get(function.__name__) if model.retain_weights else None + if function.__name__ == "load_vae_decoder" and cache is not None: + cache.close() + if retained is not None and retained[0] == key: + value = retained[1] + else: + value = function(*arguments, **keywords) + if model.retain_weights: + model.components[function.__name__] = (key, value) + if function.__name__ == "load_wan_model" and cache is not None: + return cache.attach(value) + return value finally: spent["load"] += time.time() - started return wrapper @@ -104,7 +137,15 @@ def redirected(name, *arguments, **keywords): try: if name == TOKENIZER_REPO and local_tokenizer.is_dir(): name = str(local_tokenizer) - return from_pretrained(name, *arguments, **keywords) + keywords.update(local_files_only=True, trust_remote_code=False) + key = repr((name, arguments, sorted(keywords.items()))) + retained = model.components.get("tokenizer") if model.retain_weights else None + if retained is not None and retained[0] == key: + return retained[1] + value = from_pretrained(name, *arguments, **keywords) + if model.retain_weights: + model.components["tokenizer"] = (key, value) + return value finally: spent["load"] += time.time() - started @@ -124,22 +165,28 @@ def capture(video, output_path, fps=None): mock.patch.object(AutoTokenizer, "from_pretrained", redirected), ] with contextlib.ExitStack() as stack: + if cache is not None: + stack.callback(cache.close) for patch in patches: stack.enter_context(patch) with contextlib.redirect_stdout(sys.stderr): wan.generate_video( model_dir=str(model.path), prompt=prompt, width=width, height=height, num_frames=frames, steps=steps, seed=seed, output_path=out, + **({"no_compile": True} if cache is not None else {}), ) total = time.time() - started peak_memory_gb = mx.get_peak_memory() / 1e9 if "frames" not in written: raise RuntimeError("the pipeline produced no video") seconds = max(total - spent["load"], 0.0) - return { + result = { "path": str(out), "width": written["width"], "height": written["height"], "frames": written["frames"], "fps": fps, "duration_seconds": round(written["frames"] / fps, 3), "steps": steps, "seed": seed, "seconds": round(seconds, 3), "load_seconds": round(spent["load"], 3), "seconds_per_frame": round(seconds / written["frames"], 3), "peak_memory_gb": round(peak_memory_gb, 3), "pixel_std": round(written["pixel_std"], 3), } + if denoiser_cache == "adaptive": + result["denoiser_cache"] = cache.stats() if cache is not None else cache_result + return result diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-vlm/qwen35/convert.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-vlm/qwen35/convert.py index a285f42..ae2ad82 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-vlm/qwen35/convert.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-vlm/qwen35/convert.py @@ -6,8 +6,8 @@ weights already shifted, and appends the multi-token-prediction block as the last ``blk``. This port restores the grouped head order and ``A_log``, keeps the shifted norms and a ``(channels, kernel, 1)`` kernel (the layout MLX-VLM -loads without re-sanitizing), drops the prediction block, and affine-quantizes -every projection and both vocabulary tables to ``q_bits``. The tokenizer is +loads without re-sanitizing), drops the prediction block, and writes projections +and vocabulary tables in the requested quantized or floating format. The tokenizer is rebuilt from the GGUF vocabulary. Given the model's Qwen3-VL projector GGUF (``mmproj``), the vision tower joins it as MLX-VLM's ``qwen3_5``. """ @@ -240,13 +240,13 @@ def text_config(metadata: dict, dims: dict, vocab_size: int, tied: bool, quantiz }, "attention_bias": False, "tie_word_embeddings": tied, - "quantization": quantization, - "quantization_config": quantization, } for key, field in (("bos_token_id", "tokenizer.ggml.bos_token_id"), ("eos_token_id", "tokenizer.ggml.eos_token_id"), ("pad_token_id", "tokenizer.ggml.padding_token_id")): if field in metadata: config[key] = int(metadata[field]) + if quantization is not None: + config.update(quantization=quantization, quantization_config=quantization) return config @@ -328,7 +328,7 @@ def vision_language_config(text: dict, vision: dict, tokens: list) -> dict: missing = sorted(token for token in special.values() if token not in tokens) if missing: raise ValueError("The vocabulary lacks the vision tokens {0}.".format(", ".join(missing))) - quantization = text["quantization"] + quantization = text.get("quantization") nested = {key: value for key, value in text.items() if key not in ("architectures", "quantization", "quantization_config")} config = { "architectures": ["Qwen3_5ForConditionalGeneration"], @@ -336,12 +336,12 @@ def vision_language_config(text: dict, vision: dict, tokens: list) -> dict: "text_config": nested, "vision_config": vision, "tie_word_embeddings": text["tie_word_embeddings"], - "quantization": quantization, - "quantization_config": quantization, } config.update({key: tokens.index(token) for key, token in special.items()}) if "eos_token_id" in text: config["eos_token_id"] = text["eos_token_id"] + if quantization is not None: + config.update(quantization=quantization, quantization_config=quantization) return config @@ -454,7 +454,9 @@ def convert(gguf_path, out_dir, q_bits: int, writer, log=print, projector=None) vision_metadata = read_metadata(vision_reader) vision_tensors = {tensor.name: tensor for tensor in vision_reader.tensors} vision = vision_config(vision_metadata, vision_tensors, dims, projector.name) - quantization = {"group_size": GROUP_SIZE, "bits": q_bits, "mode": "affine"} + full_precision = q_bits in (16, 32) + output_dtype = mx.float16 if q_bits == 16 else mx.float32 if q_bits == 32 else mx.bfloat16 + quantization = None if full_precision else {"group_size": GROUP_SIZE, "bits": q_bits, "mode": "affine"} tokens = reader.fields["tokenizer.ggml.tokens"].contents() files = tokenizer_files(reader, metadata, tokens, source.name) for tensor in reader.tensors: @@ -463,7 +465,7 @@ def convert(gguf_path, out_dir, q_bits: int, writer, log=print, projector=None) continue suffix = tensor.name.split(".", 2)[2] if tensor.name.startswith("blk.") else tensor.name values = restore(suffix, quants.dequantize(tensor.data, tensor.tensor_type), dims) - if values.ndim == 2 and values.shape[-1] % GROUP_SIZE == 0: + if not full_precision and values.ndim == 2 and values.shape[-1] % GROUP_SIZE == 0: log("quantizing {0} -> {1} ({2}-bit)".format(tensor.name, target, q_bits)) weight, scales, biases = mx.quantize(mx.array(values).astype(mx.bfloat16), group_size=GROUP_SIZE, bits=q_bits) mx.eval(weight, scales, biases) @@ -472,20 +474,20 @@ def convert(gguf_path, out_dir, q_bits: int, writer, log=print, projector=None) writer.add(base + ".scales", scales) writer.add(base + ".biases", biases) continue - # A_log stays float32 (MLX-VLM's cast predicate keeps it so); every other small tensor is bfloat16. - array = mx.array(values).astype(mx.float32 if suffix == "ssm_a" else mx.bfloat16) + # A_log stays float32 for stability; other tensors use the selected output dtype. + array = mx.array(values).astype(mx.float32 if suffix == "ssm_a" else output_dtype) mx.eval(array) writer.add(target, array) if vision is not None: log("adding the vision tower from {0}".format(projector.name)) for source_name, target in vision_names(vision["depth"]).items(): tensor = vision_tensors[source_name] - array = mx.array(quants.dequantize(tensor.data, tensor.tensor_type)).astype(mx.bfloat16) + array = mx.array(quants.dequantize(tensor.data, tensor.tensor_type)).astype(output_dtype) mx.eval(array) writer.add(target, array) # Conv2d kernels [out, channels, height, width] per temporal step -> MLX Conv3d [out, time, height, width, channels]. kernels = [quants.dequantize(vision_tensors[name].data, vision_tensors[name].tensor_type) for name in PATCH_KERNELS] - kernel = mx.array(np.stack(kernels, axis=1).transpose(0, 1, 3, 4, 2)).astype(mx.bfloat16) + kernel = mx.array(np.stack(kernels, axis=1).transpose(0, 1, 3, 4, 2)).astype(output_dtype) mx.eval(kernel) writer.add("vision_tower.patch_embed.proj.weight", kernel) files.update(processor_files(vision_metadata, vision)) @@ -498,6 +500,8 @@ def convert(gguf_path, out_dir, q_bits: int, writer, log=print, projector=None) config = text_config(metadata, dims, vocab_size, tied, quantization) if vision is not None: config = vision_language_config(config, vision, tokens) + if full_precision: + config["torch_dtype"] = "float%d" % q_bits (out_dir / "config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8") log("wrote {0} tensors in {1} shard(s), {2} bytes; dropped {3} prediction block(s)".format( len(writer.weight_map), shards, writer.total, dims["predict_layers"])) diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/serve-recipes.json b/packages/codex/mlx-agent/src/mlx_agent/resources/serve-recipes.json index 4f9fcb3..2cd7bcf 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/serve-recipes.json +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/serve-recipes.json @@ -3,28 +3,95 @@ "recipes": { "strata": { "executable": "python", - "argv": ["{executable}", "{runtime_adapter}", "--model", "{repo}", "--port", "{port}", "--host", "127.0.0.1", "--max-tokens", "{max_tokens}"], + "argv": [ + "{executable}", + "{runtime_adapter}", + "--model", + "{repo}", + "--port", + "{port}", + "--host", + "127.0.0.1", + "--max-tokens", + "{max_tokens}" + ], "adapter_argv": null, "default_port": 8084, "readiness": "http://127.0.0.1:{port}/v1/models", "install_hint": "make install-strata in mlx-workbench" }, + "splash": { + "executable": "splash", + "argv": [ + "{executable}", + "serve", + "--model", + "{served_model}", + "--model-dir", + "{splash_target}", + "--offline", + "--host", + "127.0.0.1", + "--port", + "{port}" + ], + "adapter_argv": null, + "thinking_off_argv": [ + "--default-reasoning-effort", + "none" + ], + "default_port": 8086, + "readiness": "http://127.0.0.1:{port}/ready", + "install_hint": "brew install incoai/tap/splash" + }, "mlx_lm": { "executable": "mlx_lm.server", - "argv": ["{executable}", "--model", "{repo}", "--port", "{port}", "--max-tokens", "{max_tokens}"], - "adapter_argv": ["--adapter-path", "{adapter_path}"], - "thinking_off_argv": ["--chat-template-args", "{\"enable_thinking\":false}"], + "argv": [ + "{executable}", + "--model", + "{repo}", + "--port", + "{port}", + "--max-tokens", + "{max_tokens}" + ], + "adapter_argv": [ + "--adapter-path", + "{adapter_path}" + ], + "thinking_off_argv": [ + "--chat-template-args", + "{\"enable_thinking\":false}" + ], "default_port": 8080, "readiness": "http://127.0.0.1:{port}/v1/models", "install_hint": "pip install mlx-lm" }, "mlx-vlm": { "executable": "mlx_vlm.server", - "argv": ["{executable}", "--model", "{repo}", "--port", "{port}", "--host", "127.0.0.1"], + "argv": [ + "{executable}", + "--model", + "{repo}", + "--port", + "{port}", + "--host", + "127.0.0.1" + ], "adapter_argv": null, "default_port": 8083, "readiness": "http://127.0.0.1:{port}/v1/models", "install_hint": "pip install mlx-vlm" + }, + "tasks": { + "executable": "python", + "argv": [ + "{executable}" + ], + "adapter_argv": null, + "default_port": 8085, + "readiness": "http://127.0.0.1:{port}/v1/models", + "install_hint": "install the local model backend with mlx-agent backend install" } } } diff --git a/packages/codex/mlx-agent/src/mlx_agent/runner_model_cache.py b/packages/codex/mlx-agent/src/mlx_agent/runner_model_cache.py new file mode 100644 index 0000000..42f0b31 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/runner_model_cache.py @@ -0,0 +1,47 @@ +"""One model object retained only inside an engine-owned resident worker.""" +from pathlib import Path +import time + +_enabled = False +_entry = None +_loads = 0 +_cache_hits = 0 +_load_seconds = 0.0 +_allocator_cache = None + + +def load_model(loader, path, **options): + global _entry, _loads, _cache_hits, _load_seconds + if not _enabled: + return loader(path, **options) + if _allocator_cache is not None: + _allocator_cache.apply_limit() + local = Path(path) + if not local.is_absolute() or not local.is_dir(): + raise ValueError("Resident inference requires existing absolute local model files.") + key = (loader.__module__, loader.__qualname__, str(local.resolve()), repr(sorted(options.items()))) + if _entry is not None and _entry[0] != key: + raise ValueError("A resident worker cannot switch models or loaders.") + if _entry is None: + started = time.monotonic() + _entry = key, loader(path, **options) + _load_seconds += time.monotonic() - started + _loads += 1 + else: + _cache_hits += 1 + return _entry[1] + + +def loaded(): + return _entry is not None + + +def enabled(): + return _enabled + + +def statistics(): + result = {'loads':_loads,'cache_hits':_cache_hits,'load_seconds':_load_seconds} + if _entry is not None and callable(getattr(_entry[1], 'component_statistics', None)): + result['components'] = _entry[1].component_statistics() + return result diff --git a/packages/codex/mlx-agent/src/mlx_agent/serve.py b/packages/codex/mlx-agent/src/mlx_agent/serve.py index bf072e7..5e24d7d 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/serve.py +++ b/packages/codex/mlx-agent/src/mlx_agent/serve.py @@ -1,7 +1,8 @@ """Confirmation-gated launcher for local MLX serving runtimes. -Serve is the only component that spawns processes, so every mutation goes -through the wire-style preview -> confirm -> receipt flow. Serve never +Receipt-owned launches use the wire-style preview -> confirm -> receipt +flow. The protected-service foreground entry point delegates lifecycle to +its existing service manager. Serve never installs runtimes, never downloads models, binds only to 127.0.0.1, and stops only processes that it started itself, verified against their receipts. """ @@ -19,12 +20,15 @@ import sys import secrets import time +import threading import urllib.error import urllib.request from datetime import datetime, timezone from pathlib import Path +from .identity_pass import recheck_bound_identity from .model_doctor import scan_wired_configs +from .serving_plan import preview_hash, receipt_fields from .transactions import _atomic_in_directory from .wiring import require_secret_free_config, validate_health_endpoint @@ -35,6 +39,7 @@ PORT_MIN, PORT_MAX = 1, 65535 READINESS_DEADLINE_DEFAULT = 60.0 STOP_DEADLINE_SECONDS = 10.0 +SPLASH_STOP_DEADLINE_SECONDS = 20.0 MAX_RECEIPTS = 50 _RECIPES_PATH = Path(__file__).resolve().parent / "resources" / "serve-recipes.json" @@ -67,11 +72,7 @@ def _utc_now(): def _preview_hash(plan): - canonical = json.dumps( - {key: plan[key] for key in sorted(plan) if key != "preview_hash"}, - sort_keys=True, separators=(",", ":"), - ) - return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + return preview_hash(plan) def receipts_root(root=None): @@ -133,6 +134,16 @@ def resolve_serve_runtime(repo, path, runtime, recipes, hf_cache=None, if runtime == "auto": raise ServeError("model_config_unavailable", "Automatic runtime selection needs a readable local config.json.", "Select a downloaded local model or explicitly review its serving runtime.") from None + if runtime == "splash": + from .splash_runtime import SplashError, installed_runtime, read_target + try: + if local is None: + raise SplashError("model_not_local", "Splash serves local files or a cached repository only.", + "Pass --path to local weights, or --repo for a model in the Hugging Face cache.") + read_target(local) + return "splash", installed_runtime()["launcher"] + except SplashError as error: + raise ServeError(error.code, str(error), error.remediation) from error if runtime == "strata" or (runtime == "auto" and config.get("serving_runtime") == "strata"): from .strata_runtime import StrataError, installed_runtime, read_model try: @@ -142,6 +153,14 @@ def resolve_serve_runtime(repo, path, runtime, recipes, hf_cache=None, return "strata", installed_runtime()["python"] except StrataError as error: raise ServeError(error.code, str(error), error.remediation) from error + if runtime in ("auto", "tasks"): + from .task_serving import resolve_model + try: + _, executable, _ = resolve_model(local, manifests, registries, backend_root, capture=False) + return "tasks", executable + except ServeError as error: + if runtime == "tasks" or error.code != "unsupported_runtime": + raise hits = lookup(config.get("model_type"), manifests, registries) if config.get("model_type") else [] if runtime == "auto": backend = choose_backend(hits, "text_llm", "vision_config" in config) @@ -181,72 +200,50 @@ def _adapter_evidence(path): return str(local), identity -def _require_adapter_identity(plan): - if plan.get("adapter_path") is None: - return - try: - path, identity = _adapter_evidence(plan["adapter_path"]) - if path == plan["adapter_path"] and identity == plan.get("adapter_identity"): - return - except ServeError: - pass - raise ServeError("adapter_changed", "Adapter files changed after the serving preview.", - "Review a fresh serve plan before starting this adapter.") - - -def _require_training_binding(plan): - binding = plan.get("training_binding") - if binding is None: - return - try: - from .training_artifacts import read_trained_adapter - _, current = read_trained_adapter(binding["training_receipt"]) - if current == binding: - return - except (OSError, ValueError, TypeError, KeyError): - pass - raise ServeError("training_receipt_changed", "The training receipt or its pinned artifacts changed.", - "Review a fresh serving preview for the completed training receipt.") - - -def _require_prefill_identity(plan): - if "prefill_kernel" in plan: - from .prefill_runtime import can_wrap_runtime, identity - configured = plan["prefill_kernel"] - facts = {k: v for k, v in configured.items() if k not in ("adapter_enabled", "runtime_executable")} - if (facts != identity() or (configured.get("adapter_enabled") - and not can_wrap_runtime(configured["runtime_executable"]))): - raise ServeError("prefill_kernel_changed", "Prompt kernel source or dependencies changed.", - "Review a fresh serving preview.") - - -def _require_decode_identity(plan): - if "decode_profile" in plan: - from .prompt_lookup_runtime import can_wrap_runtime, identity - configured = plan["decode_profile"] - facts = {k: v for k, v in configured.items() if k not in ("adapter_enabled", "runtime_executable")} - if (facts != identity() or (configured.get("adapter_enabled") - and not can_wrap_runtime(configured["runtime_executable"]))): - raise ServeError("decode_profile_changed", "Code-edit runtime source or dependencies changed.", - "Review a fresh serving preview.") - - -def _require_vision_identity(plan): - if "vision_profile" in plan: - from .vision_runtime import identity - configured = plan["vision_profile"] - facts = {key: value for key, value in configured.items() if key != "adapter_enabled"} - if facts != identity(configured["runtime_executable"]): - raise ServeError("vision_profile_changed", "Vision runtime source or dependencies changed.", - "Review a fresh serving preview.") - - def plan_start(repo, runtime, recipes, port=None, max_tokens=MAX_TOKENS_DEFAULT, adapter_path=None, path=None, jit=False, receipts_dir=None, hf_cache=None, memory_policy=None, runtime_executable=None, strata_speculation=False, strata_decoding=None, strata_expert_memory_gb=None, strata_context_tokens=None, training_receipt=None, thinking="default", - m5_prefill=False, prompt_lookup=False, vision_cache=False): + m5_prefill=False, prompt_lookup=False, vision_cache=False, api_key_file=None, api_key_sha256=None, + system_prompt=None, default_temperature=None, default_top_p=None, + splash_draft_model=None, splash_max_memory_gb=None, splash_max_context_tokens=None): """Render the start plan and local file identities without side effects.""" + if runtime != "splash" and (splash_draft_model is not None or splash_max_memory_gb is not None + or splash_max_context_tokens is not None): + raise ServeError("invalid_arguments", "Splash options require the Splash runtime.", "Use --runtime splash.") + access = None + if api_key_file is not None: + if api_key_sha256 is not None: + raise ServeError("invalid_arguments", "Select one API key source.", "Use a private key file or a verification digest.") + try: + from .inference_auth import configuration_digest + digest = configuration_digest(key_file=api_key_file) + api_key_sha256 = digest + access = {"access_key_file": str(Path(api_key_file).absolute()), "access_key_sha256": digest} + except (OSError, ValueError, TypeError): + raise ServeError("invalid_access_key", "The serving key file is unavailable or not private.", + "Use an owned mode-0600 regular file containing a 32–256 character API key.") from None + if api_key_sha256 is not None: + from .inference_auth import validate_digest + try: + validate_digest(api_key_sha256) + except ValueError as error: + raise ServeError("invalid_arguments", str(error), "Use a valid SHA-256 verification digest.") from error + if not jit and runtime != "tasks": + raise ServeError("jit_required", "Authenticated serving requires a supervised endpoint.", "Use --jit.") + if runtime == "tasks": + if adapter_path is not None or training_receipt is not None or m5_prefill or prompt_lookup or vision_cache or strata_decoding is not None or strata_speculation or strata_expert_memory_gb is not None or strata_context_tokens is not None or thinking != "default" or system_prompt is not None or default_temperature is not None or default_top_p is not None: + raise ServeError("invalid_arguments", "Task endpoints accept local models and their memory policy.", "Remove chat, adapter and Strata options.") + from .task_serving import plan_start as plan_task_endpoint + return _authenticated_plan(plan_task_endpoint(repo, path, port, receipts_dir, hf_cache, memory_policy), api_key_sha256, access) + from . import inference_defaults + try: + request_defaults = inference_defaults.validate(system_prompt, default_temperature, default_top_p) + except ValueError as error: + raise ServeError('invalid_arguments', str(error), 'Review the request defaults.') from None + if request_defaults and (not jit or runtime == 'tasks'): + raise ServeError('invalid_arguments', 'Request defaults require a managed chat gateway.', + 'Use --jit with a text or vision runtime.') if thinking not in ("default", "off"): raise ServeError("invalid_arguments", "thinking must be default or off.", "Pass --thinking off or omit it.") if type(m5_prefill) is not bool or (m5_prefill and runtime != "mlx_lm"): @@ -273,18 +270,14 @@ def plan_start(repo, runtime, recipes, port=None, max_tokens=MAX_TOKENS_DEFAULT, raise ServeError("invalid_training_receipt", str(error), "Select a completed receipt whose base and adapter files are unchanged.") from error path, adapter_path = binding["base_path"], binding["adapter_path"] if memory_policy is not None: - from .jit_serve import validate_memory_policy + from .memory_policy import PolicyRejected, enforce_launch, validate try: - memory_policy = validate_memory_policy(memory_policy) + memory_policy = validate(memory_policy) + enforce_launch(memory_policy, runtime, jit) + except PolicyRejected as error: + raise ServeError(error.code, str(error), error.remediation) from error except ValueError as error: raise ServeError("invalid_arguments", str(error), "Correct the memory policy.") from error - if not jit: - raise ServeError("jit_required", "Memory policy requires a JIT endpoint.", "Use --jit.") - if runtime != "strata" and "model_memory_budget_gb" in memory_policy: - raise ServeError("invalid_arguments", "Model memory budgets currently require Strata.", "Select a prepared Strata profile.") - if runtime == "strata" and "context_tokens" in memory_policy: - from .jit_serve import STRATA_CONTEXT - raise ServeError("invalid_arguments", STRATA_CONTEXT, "Remove --context-tokens.") has_repo = isinstance(repo, str) and bool(repo.strip()) has_path = isinstance(path, str) and bool(path.strip()) if has_repo == has_path: @@ -351,44 +344,29 @@ def plan_start(repo, runtime, recipes, port=None, max_tokens=MAX_TOKENS_DEFAULT, "max_tokens": str(max_tokens), "runtime_adapter": str(Path(__file__).with_name("strata_runtime.py").resolve()), } - strata_model = strata_runtime = strata_allocation = None + contribution = None if runtime != "strata" and (strata_expert_memory_gb is not None or strata_context_tokens is not None or strata_decoding is not None): raise ServeError("invalid_arguments", "Strata memory controls require the Strata runtime.", "Select a prepared local Strata profile.") if runtime == "strata": - from .strata_runtime import StrataError, installed_runtime, read_model, memory_estimate, memory_allocation, resolve_decoding + from .strata_runtime import StrataError, plan_contribution try: - if not has_path or adapter_path is not None or type(strata_speculation) is not bool: - raise StrataError("strata_model_required", "Strata requires a local GGUF profile without a LoRA adapter.") - strata_model = read_model(local_path) - strata_context_tokens = 131072 if strata_context_tokens is None else strata_context_tokens - strata_decoding = resolve_decoding(strata_model, strata_speculation, strata_decoding) - uses_draft = strata_decoding == "mtp" - budget = (memory_policy or {}).get("model_memory_budget_gb") - if budget is not None: - if strata_expert_memory_gb is not None: - raise StrataError("invalid_arguments", "Choose a total model memory budget or an expert budget.") - strata_allocation = memory_allocation(strata_model, budget, strata_context_tokens, uses_draft) - strata_memory_bytes = strata_allocation["estimated_resident_bytes"] - else: - strata_memory_bytes = memory_estimate(strata_model, strata_expert_memory_gb, strata_context_tokens, uses_draft) - strata_runtime = installed_runtime() - if runtime_executable is not None and runtime_executable != strata_runtime["python"]: - raise StrataError("strata_not_installed", "The reviewed Strata executable changed.") - values["executable"] = strata_runtime["python"] + contribution = plan_contribution(local_path, has_path, adapter_path, strata_speculation, strata_decoding, + strata_context_tokens, strata_expert_memory_gb, memory_policy, runtime_executable) except StrataError as error: raise ServeError(error.code, str(error), error.remediation) from error + if runtime == "splash": + from .splash_runtime import SplashError, plan_contribution + try: + contribution = plan_contribution(local_path, has_repo, repo, hf_cache, adapter_path, jit, runtime_executable, + splash_draft_model, splash_max_memory_gb, splash_max_context_tokens) + except SplashError as error: + raise ServeError(error.code, str(error), error.remediation) from error + if contribution is not None: + contribution.apply_values(values) argv = [part.format(**values) for part in recipe["argv"]] - if strata_model: - argv += ["--runtime-root", strata_runtime["root"], "--speculation", "on" if strata_speculation else "off", - "--decoding", strata_decoding, - "--context-tokens", str(strata_context_tokens), - "--expected-model-fingerprint", strata_model["fingerprint"], - "--expected-runtime-fingerprint", strata_runtime["fingerprint"]] - if strata_expert_memory_gb is not None: - argv += ["--expert-memory-gb", str(strata_expert_memory_gb)] - if strata_allocation is not None: - argv += ["--memory-budget-gb", str(budget)] + if contribution is not None: + contribution.extend_argv(argv) if adapter_path is not None: argv.extend( part.format(adapter_path=str(adapter_path)) for part in recipe["adapter_argv"] @@ -439,16 +417,8 @@ def plan_start(repo, runtime, recipes, port=None, max_tokens=MAX_TOKENS_DEFAULT, "readiness": recipe["readiness"].format(port=selected_port), "bind": "127.0.0.1", } - if strata_model: - plan.update(strata_model_fingerprint=strata_model["fingerprint"], - strata_runtime_fingerprint=strata_runtime["fingerprint"], - weight_format="gguf", weight_quantization=strata_model["quantization"], weights_preserved=True, - strata_speculation=strata_speculation, strata_decoding=strata_decoding, - strata_expert_memory_gb=strata_expert_memory_gb, - strata_context_tokens=strata_context_tokens, strata_memory_estimate_bytes=strata_memory_bytes, - readiness_deadline=900) - if strata_allocation is not None: - plan["strata_memory_allocation"] = strata_allocation + if contribution is not None: + contribution.apply_fields(plan) elif has_path: plan.update(_local_weight_evidence(local_path)) if prefill_kernel is not None: @@ -461,6 +431,8 @@ def plan_start(repo, runtime, recipes, port=None, max_tokens=MAX_TOKENS_DEFAULT, plan["adapter_identity"] = adapter_identity if thinking == "off": plan["thinking"] = "off" if recipe.get("thinking_off_argv") else "unsupported" + if request_defaults: + plan['request_defaults'] = request_defaults if binding is not None: plan["training_binding"] = binding if jit: @@ -472,7 +444,8 @@ def plan_start(repo, runtime, recipes, port=None, max_tokens=MAX_TOKENS_DEFAULT, "Select an existing local model directory; serving never downloads weights.") local = local.resolve() worker = list(argv) - worker[worker.index("--model") + 1] = str(local) + if contribution is None or not contribution.retarget_worker(worker): + worker[worker.index("--model") + 1] = str(local) worker[worker.index("--port") + 1] = "{worker_port}" # Both supported runtimes expose --host. The VLM default binds all # interfaces, so explicitly fence the private worker to loopback. @@ -486,7 +459,17 @@ def plan_start(repo, runtime, recipes, port=None, max_tokens=MAX_TOKENS_DEFAULT, "--config", plan["control_config"]] if memory_policy is not None: plan["memory_policy"] = memory_policy - plan["preview_hash"] = _preview_hash(plan) + return _authenticated_plan(plan, api_key_sha256, access) + + +def _authenticated_plan(plan, digest, access=None): + if digest is not None: + from .inference_auth import runtime_fingerprint + plan.update(api_key_sha256=digest, auth_runtime_sha256=runtime_fingerprint(), **(access or {})) + from .worker_transport import choose + choose(plan).mark(plan) + plan['readiness'] = 'http://127.0.0.1:{}/_mlx/status'.format(plan['port']) + plan['preview_hash'] = _preview_hash({key: value for key, value in plan.items() if key != 'preview_hash'}) return plan @@ -506,19 +489,22 @@ def _default_port_free(port): def _default_spawn(argv, log_path): - handle = open(log_path, "ab", buffering=0) - process = subprocess.Popen( - argv, - stdin=subprocess.DEVNULL, - stdout=handle, - stderr=subprocess.STDOUT, - start_new_session=True, - env={**os.environ, "HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1"}, - ) + with open(log_path, "ab", buffering=0) as handle: + process = subprocess.Popen( + argv, + stdin=subprocess.DEVNULL, + stdout=handle, + stderr=subprocess.STDOUT, + start_new_session=True, + env={**os.environ, "HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1"}, + ) + # API/MCP callers outlive a CLI invocation: retain and reap each child so + # an exited zombie cannot be mistaken for a live serving process. + threading.Thread(target=process.wait, name="mlx-serve-reaper", daemon=True).start() return process.pid -def _default_readiness(url, deadline_seconds, clock=time.monotonic, sleep=time.sleep, child_pid=None): +def _default_readiness(url, deadline_seconds, clock=time.monotonic, sleep=time.sleep, child_pid=None, headers=None): validate_health_endpoint(url) deadline = clock() + deadline_seconds while clock() < deadline: @@ -530,8 +516,9 @@ def _default_readiness(url, deadline_seconds, clock=time.monotonic, sleep=time.s if not _pid_alive(child_pid): return False try: - request = urllib.request.Request(url, method="GET") - opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + from .inference_auth import loopback_opener + request = urllib.request.Request(url, method="GET", headers=headers or {}) + opener = loopback_opener() with opener.open(request, timeout=2.0) as response: if 200 <= response.status < 400: return True @@ -588,7 +575,8 @@ def start_serve(plan, receipts_dir=None, confirm=False, preview_hash=None, which = which or _default_which port_free = port_free or _default_port_free spawn = spawn or _default_spawn - readiness = readiness or (lambda url, deadline: _default_readiness(url, deadline, child_pid=pid if spawn is _default_spawn else None)) + readiness_headers = {} + readiness = readiness or (lambda url, deadline: _default_readiness(url, deadline, child_pid=pid if spawn is _default_spawn else None, headers=readiness_headers)) pid_alive = pid_alive or _pid_alive root = receipts_root(receipts_dir) @@ -606,11 +594,7 @@ def start_serve(plan, receipts_dir=None, confirm=False, preview_hash=None, "The supplied preview hash does not match this start plan.", "Re-run serve start without --confirm and review the fresh plan.", ) - _require_training_binding(plan) - _require_adapter_identity(plan) - _require_prefill_identity(plan) - _require_decode_identity(plan) - _require_vision_identity(plan) + recheck_bound_identity(plan) if plan["runtime"] == "strata" and not plan.get("jit"): from .jit_serve import available_memory_bytes @@ -631,20 +615,17 @@ def start_serve(plan, receipts_dir=None, confirm=False, preview_hash=None, "Install it yourself ({0}); serve never installs runtimes.".format(recipe_hint), ) if plan.get("jit"): - from .jit_serve import model_fingerprint if which(plan["worker_argv"][0]) is None: raise ServeError("runtime_not_installed", "The model worker executable is not installed.", load_recipes()[plan["runtime"]]["install_hint"]) - if model_fingerprint(plan["local_path"]) != plan["fingerprint"]: - raise ServeError("preview_stale", "Local model files changed after preview.", - "Review a fresh JIT serve plan.") if plan["repo"] is not None and model_present is not None and not model_present(plan["repo"]): raise ServeError( "model_not_local", "The model is not present in a local inventory.", "Download it with the runtime's own pull command first; serve never downloads models.", ) - if plan["path"] is not None: + # A Splash target may be a GGUF file; its identity check above proved it present. + if plan["path"] is not None and plan["runtime"] != "splash": present = path_present or _default_path_present if not present(plan["path"]): raise ServeError( @@ -685,26 +666,15 @@ def start_serve(plan, receipts_dir=None, confirm=False, preview_hash=None, config_path = Path(plan["control_config"]) if config_path.parent != root.absolute() or config_path.is_symlink(): raise ServeError("invalid_arguments", "Unsafe JIT configuration path.", "Review a fresh serve plan.") - config = {key: plan[key] for key in ("local_path", "fingerprint", "worker_argv", "max_tokens")} - config["runtime"] = plan["runtime"] - if plan.get("adapter_path") is not None: - config.update(adapter_path=plan["adapter_path"], adapter_identity=plan["adapter_identity"]) - if plan.get("training_binding") is not None: - config["training_binding"] = plan["training_binding"] - if "readiness_deadline" in plan: - config["worker_readiness_seconds"] = plan["readiness_deadline"] - if plan["runtime"] == "strata": - config["strata_expert_memory_gb"] = plan.get("strata_expert_memory_gb") - config["strata_context_tokens"] = plan.get("strata_context_tokens", 131072) - config["strata_speculation"] = plan.get("strata_speculation", False) - config["strata_decoding"] = plan["strata_decoding"] - if "strata_memory_allocation" in plan: - config["strata_memory_allocation"] = plan["strata_memory_allocation"] - config.update(model=plan["repo"] or plan["path"], control_token=secrets.token_hex(32), - memory_policy=plan.get("memory_policy"), config_path=str(config_path), - state_path=str(root.absolute() / "{}.jit-state.json".format(plan["port"])), - log_path=str(root.absolute() / "{}.worker.log".format(plan["port"]))) + from .worker_transport import gateway_config + config = gateway_config(plan, control_token=secrets.token_hex(32), + state_path=str(root.absolute() / "{}.jit-state.json".format(plan["port"])), + log_path=root.absolute() / "{}.worker.log".format(plan["port"]), + config_path=config_path, + task_state_dir=str(root.absolute().parent / "tasks" / str(plan["port"]))) _atomic_in_directory(root, config_path.name, json.dumps(config).encode(), 0o600) + if plan.get("api_key_sha256") is not None: + readiness_headers["Authorization"] = "Bearer " + config["control_token"] pid = spawn(plan["argv"], str(log_path)) if not readiness(plan["readiness"], plan.get("readiness_deadline", readiness_deadline)): _terminate_pid(pid) @@ -714,11 +684,7 @@ def start_serve(plan, receipts_dir=None, confirm=False, preview_hash=None, "Inspect the serve log at {0}.".format(log_path), ) try: - _require_training_binding(plan) - _require_adapter_identity(plan) - _require_prefill_identity(plan) - _require_decode_identity(plan) - _require_vision_identity(plan) + recheck_bound_identity(plan) except ServeError: _terminate_pid(pid) raise @@ -737,22 +703,10 @@ def start_serve(plan, receipts_dir=None, confirm=False, preview_hash=None, "started_at": now(), "preview_hash": plan["preview_hash"], } - if plan.get("jit"): - receipt["jit"] = True - if plan.get("adapter_path") is not None: - receipt.update(adapter_path=plan["adapter_path"], adapter_identity=plan["adapter_identity"]) - if plan.get("training_binding") is not None: - receipt["training_binding"] = plan["training_binding"] - if "prefill_kernel" in plan: - receipt["prefill_kernel"] = plan["prefill_kernel"] - if "decode_profile" in plan: - receipt["decode_profile"] = plan["decode_profile"] - if "vision_profile" in plan: - receipt["vision_profile"] = plan["vision_profile"] - if "strata_decoding" in plan: - receipt["strata_decoding"] = plan["strata_decoding"] - if "strata_memory_allocation" in plan: - receipt["strata_memory_allocation"] = plan["strata_memory_allocation"] + process_start = _pid_start(pid) + if process_start: + receipt["process_started_at"] = process_start + receipt.update(receipt_fields(plan)) content = (json.dumps(receipt, sort_keys=True, separators=(",", ":")) + "\n").encode("utf-8") _atomic_in_directory(root, receipt_path.name, content, 0o600) return {"status": "started", "receipt": receipt} @@ -807,6 +761,7 @@ def status_serve(receipts_dir=None, pid_alive=_pid_alive, pid_command=_pid_comma "repo": receipt["repo"], "path": receipt.get("path"), "runtime": receipt["runtime"], + "api_key_sha256": receipt.get("api_key_sha256"), "port": receipt["port"], "pid": receipt["pid"], "alive": alive, @@ -816,6 +771,8 @@ def status_serve(receipts_dir=None, pid_alive=_pid_alive, pid_command=_pid_comma "process_started_at": _pid_start(receipt["pid"]) if alive and pid_command is _pid_command else None, }) entries[-1].update(_adapter_metadata(receipt, root)) + if receipt.get("task_kinds"): + entries[-1]["task_kinds"] = receipt["task_kinds"] if receipt.get("training_binding") is not None: entries[-1]["training_binding"] = receipt["training_binding"] if "prefill_kernel" in receipt: @@ -824,6 +781,8 @@ def status_serve(receipts_dir=None, pid_alive=_pid_alive, pid_command=_pid_comma entries[-1]["decode_profile"] = receipt["decode_profile"] if "vision_profile" in receipt: entries[-1]["vision_profile"] = receipt["vision_profile"] + if "protection" in receipt: + entries[-1]["protection"] = receipt["protection"] if receipt.get("jit"): entries[-1]["jit"] = True if alive and entries[-1]["argv_match"]: @@ -864,12 +823,19 @@ def _argv_matches(receipt, command, require_port=True): argv = receipt.get("argv") or [] if not argv: return False + if receipt.get("runtime") == "splash" and not receipt.get("jit"): + # The launcher execs Splash's server on its own prepared copy of the target. + return ("-m server.server" in command and "--model {0} ".format(receipt.get("splash_served_model")) in command + " " + and (not require_port or "--port {0} ".format(receipt.get("port")) in command + " ")) executable = Path(str(argv[0])).name # macOS framework Python reports its bundle binary in ps, not the # interpreter alias used to launch it. Bind a script recipe to its # absolute entry point instead of accepting any Python process. if len(argv) > 1 and str(argv[1]).endswith(".py") and Path(str(argv[1])).is_absolute(): executable = str(argv[1]) + elif len(argv) > 3 and argv[1:4] == [ + "-I", "-B", str(Path(__file__).with_name("owned_worker.py").resolve())]: + executable = str(argv[3]) model = receipt.get("repo") or receipt.get("path") if not model or executable not in command or str(model) not in command: return False @@ -910,11 +876,12 @@ def _jit_config(receipt, root): def _jit_control(receipt, root, action, policy=None, timeout=None): config = _jit_config(receipt, root) request = urllib.request.Request("http://127.0.0.1:{}/_mlx/{}".format(receipt["port"], action), - data=json.dumps(policy or {}).encode() if action in ("unload", "policy") else None, + data=json.dumps(policy or {}).encode() if action in ("unload", "policy", "cache") else None, headers={"Authorization": "Bearer " + config["control_token"], "Content-Type": "application/json"}) - opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + from .inference_auth import loopback_opener + opener = loopback_opener() try: - with opener.open(request, timeout=timeout if timeout is not None else (10 if action == "unload" else 2)) as response: + with opener.open(request, timeout=timeout if timeout is not None else (15 if action in ("unload", "policy", "cache") else 2)) as response: state = json.load(response) if not isinstance(state, dict) or state.get("model_state") not in ("loaded", "unloaded", "loading", "unloading", "failed"): raise ValueError("Invalid model residency status.") @@ -944,6 +911,18 @@ def _owned_jit_worker(receipt, root): config = _jit_config(receipt, root) expected = {"repo": None, "path": config["local_path"], "argv": argv, "port": int(argv[argv.index("--port") + 1])} + if config.get("runtime") == "tasks": + if _pid_alive(pid) and os.getpgid(pid) == pid and state.get("worker_started_at") == _pid_start(pid) and _argv_matches(expected, _pid_command(pid)): + return pid + return None + isolated = (len(argv) > 7 and argv[1:4] == + ["-I", "-B", str(Path(__file__).with_name("owned_worker.py").resolve())]) + if isolated: + if (_pid_alive(pid) and os.getpgid(pid) == pid + and state.get("worker_started_at") == _pid_start(pid) + and _argv_matches(expected, _pid_command(pid))): + return pid + return None if _pid_alive(pid) and os.getpgid(pid) == receipt["pid"] and _argv_matches(expected, _pid_command(pid)): return pid except (OSError, ValueError, TypeError, KeyError, ServeError): @@ -955,8 +934,12 @@ def unload_serve(port, receipts_dir=None, expected_pid=None, expected_start=None return _configure_owned_jit(port, receipts_dir, expected_pid, "unload", expected_start=expected_start) +def reclaim_serve_cache(port, receipts_dir=None, expected_pid=None, expected_start=None): + return _configure_owned_jit(port, receipts_dir, expected_pid, 'cache', expected_start=expected_start) + + def configure_serve_memory(port, policy, receipts_dir=None, expected_pid=None, expected_start=None): - from .jit_serve import validate_memory_policy + from .memory_policy import validate as validate_memory_policy clear_budget = isinstance(policy, dict) and "model_memory_budget_gb" in policy and policy["model_memory_budget_gb"] is None try: policy = validate_memory_policy(policy) @@ -983,7 +966,7 @@ def _configure_owned_jit(port, receipts_dir, expected_pid, action, policy=None, raise ServeError("pid_argv_mismatch", "Endpoint process no longer matches its receipt.", "Refresh serving status before unloading.") state = _jit_control(receipt, root, action, policy) - return dict(state, status="unloaded" if action == "unload" else "configured", port=port, pid=receipt["pid"]) + return dict(state, status={"unload": "unloaded", "policy": "configured", "cache": "reclaimed"}[action], port=port, pid=receipt["pid"]) def stop_serve(port, receipts_dir=None, pid_alive=_pid_alive, pid_command=_pid_command, @@ -1015,10 +998,11 @@ def stop_serve(port, receipts_dir=None, pid_alive=_pid_alive, pid_command=_pid_c "The live pid {0} does not match the serve receipt; refusing to signal it.".format(pid), "Inspect the process yourself; the receipt is retained at {0}.".format(receipt_path), ) - if (receipt.get("jit") or receipt.get("runtime") == "strata") and terminate is _terminate_pid and os.getpgid(pid) == receipt["pid"]: + if (receipt.get("jit") or receipt.get("runtime") in ("strata", "splash")) and terminate is _terminate_pid and os.getpgid(pid) == receipt["pid"]: terminate = lambda _pid, sig: os.killpg(receipt["pid"], sig) terminate(pid, signal.SIGTERM) - deadline = clock() + STOP_DEADLINE_SECONDS + # Splash gives its engine 15 seconds to stop before killing it. + deadline = clock() + (SPLASH_STOP_DEADLINE_SECONDS if receipt.get("runtime") == "splash" else STOP_DEADLINE_SECONDS) while clock() < deadline: if not pid_alive(pid): receipt_path.unlink() diff --git a/packages/codex/mlx-agent/src/mlx_agent/serve_profiles.py b/packages/codex/mlx-agent/src/mlx_agent/serve_profiles.py index 2b2aa79..b4a7414 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/serve_profiles.py +++ b/packages/codex/mlx-agent/src/mlx_agent/serve_profiles.py @@ -1,4 +1,4 @@ -"""Named local Strata settings; profiles contain no model paths or commands.""" +"""Named local serving settings; profiles contain no model paths or commands.""" import json import os @@ -6,29 +6,33 @@ import re import stat -from .jit_serve import validate_memory_policy +from .allocator_cache import FIELDS as CACHE_FIELDS +from .memory_policy import policy_from_profile, validate from .serve import receipts_root from .strata_runtime import StrataError, _validate_context from .transactions import _atomic_in_directory, _target_locks, _walk_directory -_FIELDS = {"memory_budget_gb", "min_headroom_gb", "strata_context_tokens", "strata_decoding", - "idle_timeout", "keep_loaded", "unload_under_pressure"} +_COMMON = {"min_headroom_gb", "idle_timeout", "keep_loaded", "unload_under_pressure"} +_STRATA = {"strata_context_tokens", "strata_decoding"} +_FIELDS = _COMMON | _STRATA | {"memory_budget_gb"} | CACHE_FIELDS | {"execution_wait_seconds", "release_after_request"} def _validate(settings): - if not isinstance(settings, dict) or set(settings) != _FIELDS: - raise ValueError("A serving profile requires only memory, headroom, context, decoding and idle settings.") - if settings["memory_budget_gb"] is None or settings["min_headroom_gb"] is None: - raise ValueError("Serving profiles require an explicit model budget and headroom reserve.") - validate_memory_policy({"model_memory_budget_gb": settings["memory_budget_gb"], - "minimum_headroom_gb": settings["min_headroom_gb"], "idle_timeout_seconds": settings["idle_timeout"], - "keep_loaded": settings["keep_loaded"], "unload_under_pressure": settings["unload_under_pressure"]}) - try: - _validate_context(settings["strata_context_tokens"]) - except StrataError as error: - raise ValueError(str(error)) from error - if settings["strata_decoding"] not in ("plain", "lookup", "mtp"): - raise ValueError("Profile decoding must be plain, lookup or mtp.") + if not isinstance(settings, dict) or not _COMMON <= set(settings) or set(settings) - _FIELDS: + raise ValueError("A serving profile requires memory, headroom and residency settings only.") + strata = bool(set(settings) & _STRATA) + if strata and not (_STRATA | {"memory_budget_gb"}) <= set(settings): + raise ValueError("Strata profiles require a model budget, context and decoding settings.") + if settings["min_headroom_gb"] is None or (strata and settings["memory_budget_gb"] is None): + raise ValueError("Serving profiles require an explicit headroom reserve and any selected model budget.") + validate(policy_from_profile(settings)) + if strata: + try: + _validate_context(settings["strata_context_tokens"]) + except StrataError as error: + raise ValueError(str(error)) from error + if settings["strata_decoding"] not in ("plain", "lookup", "mtp"): + raise ValueError("Profile decoding must be plain, lookup or mtp.") return dict(settings) diff --git a/packages/codex/mlx-agent/src/mlx_agent/served.py b/packages/codex/mlx-agent/src/mlx_agent/served.py new file mode 100644 index 0000000..99e07aa --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/served.py @@ -0,0 +1,183 @@ +"""Run a convert verb on a typed endpoint that already serves the same model, so the model loads once.""" + +import hashlib +import http.client +import json +import os +import time +import urllib.error +import urllib.request +from pathlib import Path + +from .inference_runner import InferenceError + +TERMINAL = ("succeeded", "failed", "cancelled") +POLL_SECONDS = 0.5 +# convert verb -> (task kind, CLI argument names that are task parameters) +VERBS = { + "speak": ("speak", ("text", "voice", "speed", "lang_code")), + "music": ("music_generation", ("caption", "lyrics", "duration", "steps", "seed", "bpm", "time_signature", + "reference")), + "generate": ("image_generation", ("prompt", "width", "height", "steps", "seed")), + "video": ("video_generation", ("prompt", "width", "height", "frames", "steps", "seed", "fps", "denoiser_cache", + "cache_memory_mib")), +} +REMEDIATION = { + "model_busy": "The served model is running another job; wait for it to finish and retry.", +} + + +def execution_limit(kind): + """Seconds an endpoint lets one job of this kind run: its backend runner's default timeout.""" + from . import describe, generate, music, speak, video + modules = {"speak": speak, "music_generation": music, "image_generation": generate, + "video_generation": video, "image_understanding": describe, "video_understanding": describe} + return modules[kind].DEFAULT_TIMEOUT_SECONDS + + +def request(verb, arguments): + """The task kind and its parameters for a convert verb, taken from the CLI arguments.""" + if verb == "describe": + media = "video" if arguments.video else "image" + names = ("prompt", "max_tokens", "temperature", "max_pixels") + (("fps",) if media == "video" else ()) + parameters = {name: getattr(arguments, name) for name in names} + parameters[media + "_path"] = str(Path(getattr(arguments, media)).expanduser().resolve()) + kind = media + "_understanding" + else: + kind, names = VERBS[verb] + parameters = {name: getattr(arguments, name) for name in names} + return kind, {name: value for name, value in parameters.items() if value is not None} + + +def endpoint(model, kind, discover=None): + """The live typed endpoint bound to this model directory that advertises this kind, or None.""" + if discover is None: + from .service_registry import discover_services as discover + wanted = Path(model).expanduser().resolve() + try: + services = discover()["services"] + except (OSError, ValueError, KeyError, TypeError): + return None + for service in services: + try: + if (service.get("runtime") == "tasks" and service.get("alive") and service.get("argv_match") + and kind in (service.get("task_kinds") or ()) and Path(service["path"]).resolve() == wanted): + return service + except (OSError, TypeError, KeyError): + continue + return None + + +def _key(service): + from .serve import receipts_root + from .serving_access import read_access_key + from .workflow_sets import _private_json + try: + config = _private_json(receipts_root(service["receipts_dir"]) / "{0}.jit-config.json".format(service["port"])) + if config.get("access_key_file") is None: + if config.get("api_key_sha256") is None: + return None + raise ValueError("no key file") + return read_access_key(config["access_key_file"], config.get("api_key_sha256"))[0] + except (OSError, ValueError, KeyError) as error: + raise InferenceError( + "endpoint_key_unavailable", + "The model is served on port {0}, but its access key is unreadable: {1}".format(service["port"], error), + "Run as the endpoint's owner, or stop that endpoint before running the model locally.", + ) from None + + +def _open(port, key, method, path, body=None, timeout=30): + from .inference_auth import loopback_opener + headers = {"Content-Type": "application/json"} + if key: + headers["Authorization"] = "Bearer " + key + data = None if body is None else json.dumps(body).encode() + call = urllib.request.Request("http://127.0.0.1:{0}{1}".format(port, path), data=data, headers=headers, + method=method) + try: + return loopback_opener().open(call, timeout=timeout) + except urllib.error.HTTPError as error: + try: + detail = json.load(error)["error"] + code, message = str(detail["code"]), str(detail["message"]) + except (ValueError, KeyError, TypeError): + code, message = "endpoint_failed", "The model endpoint answered HTTP {0}.".format(error.code) + raise InferenceError(code, message, REMEDIATION.get(code, "Inspect the endpoint with serve discover.")) from None + except OSError as error: + raise InferenceError("endpoint_unavailable", "The model endpoint on port {0} did not answer: {1}".format(port, error), + "Inspect the endpoint with serve discover.") from None + + +def _json(port, key, method, path, body=None): + with _open(port, key, method, path, body) as response: + value = json.load(response) + if not isinstance(value, dict): + raise InferenceError("endpoint_failed", "The model endpoint returned an invalid answer.", + "Inspect the endpoint with serve discover.") + return value + + +def _download(port, key, identifier, out, reference): + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + digest, size = hashlib.sha256(), 0 + with _open(port, key, "GET", "/v1/tasks/{0}/artifacts/output".format(identifier), timeout=120) as response: + descriptor = os.open(out, flags, 0o644) + # out is new; every unsuccessful exit removes it. + try: + with os.fdopen(descriptor, "wb") as target: + for chunk in iter(lambda: response.read(65536), b""): + digest.update(chunk) + size += len(chunk) + target.write(chunk) + if size != reference.get("bytes") or digest.hexdigest() != reference.get("sha256"): + raise InferenceError("artifact_changed", "The served output does not match its recorded digest.", + "Run the job again.") + except (OSError, http.client.HTTPException) as error: + Path(out).unlink(missing_ok=True) + raise InferenceError("artifact_incomplete", + "The served output stopped after {0} bytes: {1}".format(size, error), + "Run the job again.") from None + except BaseException: + Path(out).unlink(missing_ok=True) + raise + + +def run(service, kind, parameters, out, timeout, clock=time.monotonic, sleep=time.sleep): + """Submit one job to the endpoint, wait for it, and write its output artifact to out.""" + port = service["port"] + limit = execution_limit(kind) + if timeout > limit: + raise InferenceError( + "served_timeout_limit", + "The model is served on port {0}, which stops {1} jobs after {2} s; --timeout is {3} s.".format( + port, kind, limit, timeout), + "Use --timeout {0} or less, or stop that endpoint before running the model locally.".format(limit), + ) + key = _key(service) + deadline = clock() + timeout + record = _json(port, key, "POST", "/v1/tasks", {"kind": kind, "parameters": parameters}) + identifier = record["id"] + while record["state"] not in TERMINAL: + if clock() >= deadline: + _json(port, key, "POST", "/v1/tasks/{0}/cancel".format(identifier), {}) + raise InferenceError("served_timeout", "The served job exceeded {0} s and was cancelled.".format(timeout), + "Raise --timeout or lower the job size.") + sleep(POLL_SECONDS) + record = _json(port, key, "GET", "/v1/tasks/{0}".format(identifier)) + if record["state"] != "succeeded": + error = record.get("error") if isinstance(record.get("error"), dict) else {} + raise InferenceError(str(error.get("code", "task_" + record["state"])), + str(error.get("message", "The served job ended {0}.".format(record["state"]))), + "Inspect the job with the endpoint's task status.") + outcome = _json(port, key, "GET", "/v1/tasks/{0}/result".format(identifier)) + result = outcome.get("result") + if result is None: + result = _json(port, key, "GET", "/v1/tasks/{0}/artifacts/result".format(identifier)) + if out is not None: + _download(port, key, identifier, out, result["output_artifact"]) + value = {name: item for name, item in result.items() if name != "output_artifact"} + if out is not None: + value["path"] = str(out) + value["served"] = {"port": port, "task_id": identifier} + return value diff --git a/packages/codex/mlx-agent/src/mlx_agent/service_registry.py b/packages/codex/mlx-agent/src/mlx_agent/service_registry.py index a06b265..b8ba000 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/service_registry.py +++ b/packages/codex/mlx-agent/src/mlx_agent/service_registry.py @@ -59,7 +59,14 @@ def _read_roots(registry, errors): record = json.loads(raw) if not isinstance(record, dict) or record.get('schema_version') != 1 or not isinstance(record.get('receipts_dir'), str): raise ValueError('Unsupported service location record') - roots.append(str(_safe_root(record['receipts_dir']))) + try: + roots.append(str(_safe_root(record['receipts_dir']))) + except ValueError as error: + if not str(error).startswith('path component does not exist:'): + raise + # A historical registration can outlive its directory. Explicit + # and live roots are still checked independently by discovery. + except (OSError, ValueError, TypeError) as error: errors.append({'source': str(location), 'message': str(error)}) return roots @@ -178,4 +185,4 @@ def discover_services(receipts_dirs=(), registry=None, process_roots=None, inspe except (OSError, ValueError, KeyError, TypeError) as error: errors.append({'source': str(value), 'message': str(error)}) return {'schema_version': 1, 'services': services, 'errors': errors, - 'capabilities': {'scoped_doctor': True, 'scoped_watch': True, 'expected_pid_stop': True}} + 'capabilities': {'scoped_doctor': True, 'scoped_watch': True, 'model_update_preparation': True, 'model_storage_admission': True, 'expected_pid_stop': True}} diff --git a/packages/codex/mlx-agent/src/mlx_agent/serving_access.py b/packages/codex/mlx-agent/src/mlx_agent/serving_access.py new file mode 100644 index 0000000..9828027 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/serving_access.py @@ -0,0 +1,26 @@ +"""Private file credentials for explicitly protected serving endpoints.""" +import hashlib +import hmac +import os +import re +import stat + + +def read_access_key(path, expected_digest=None): + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(descriptor, 'rb') as source: + metadata = os.fstat(source.fileno()) + if (not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != os.getuid() + or stat.S_IMODE(metadata.st_mode) & 0o077 or not 32 <= metadata.st_size <= 512): + raise ValueError('The serving key requires an owned private regular file.') + raw = source.read(513) + try: + key = raw.decode('ascii').strip() + except UnicodeError: + raise ValueError('Invalid serving key file.') from None + if len(raw) > 512 or re.fullmatch(r'[A-Za-z0-9._~-]{32,256}', key) is None: + raise ValueError('The serving key must contain 32–256 URL-safe ASCII characters.') + digest = hashlib.sha256(key.encode()).hexdigest() + if expected_digest is not None and not hmac.compare_digest(digest, expected_digest): + raise ValueError('The serving key changed after review.') + return key, digest diff --git a/packages/codex/mlx-agent/src/mlx_agent/serving_plan.py b/packages/codex/mlx-agent/src/mlx_agent/serving_plan.py new file mode 100644 index 0000000..a8630d3 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/serving_plan.py @@ -0,0 +1,147 @@ +"""The reviewed serving plan: one description, one preview hash, and the copies callers used to repeat. + +Splash and Strata each return one contribution. Task endpoints return earlier +through task_serving.plan_start. Chat runtimes add nothing here. +""" +import hashlib +import json + + +class Contribution: + """What one runtime adds to a serving plan.""" + + def __init__(self, argv, values, fields, worker_entry=None): + self.argv = list(argv) + self.values = dict(values) + self.fields = dict(fields) + self.worker_entry = None if worker_entry is None else list(worker_entry) + + def apply_values(self, values): + values.update(self.values) + + def extend_argv(self, argv): + argv.extend(self.argv) + + def apply_fields(self, plan): + plan.update(self.fields) + + def retarget_worker(self, worker): + """Replace the worker program when this runtime does not use the recipe executable.""" + if self.worker_entry is None: + return False + worker[:1] = self.worker_entry + return True + + +class MemoryBasis: + """Sizes on a reviewed plan that reservation consumes without naming a runtime's fields.""" + + def __init__(self, kind, weights=None, cap_gb=None, allocation_bytes=None, estimate_bytes=None, growth_bytes=None): + self.kind = kind + self.weights = weights + self.cap_gb = cap_gb + self.allocation_bytes = allocation_bytes + self.estimate_bytes = estimate_bytes + self.growth_bytes = growth_bytes + + +def preview_hash(plan): + canonical = json.dumps( + {key: plan[key] for key in sorted(plan) if key != "preview_hash"}, + sort_keys=True, separators=(",", ":"), + ) + return hashlib.sha256(canonical.encode("utf-8")).hexdigest() + + +def memory_basis(plan): + """Runtime sizes stored on the plan. Missing Splash weights still raise KeyError.""" + runtime = plan.get("runtime") + if runtime == "splash": + return MemoryBasis("splash", weights=plan["splash_weight_bytes"], cap_gb=plan.get("splash_max_memory_gb")) + if runtime == "strata": + allocation = plan.get("strata_memory_allocation") or {} + return MemoryBasis( + "strata", + allocation_bytes=allocation.get("estimated_resident_bytes"), + estimate_bytes=plan.get("strata_memory_estimate_bytes"), + growth_bytes=plan.get("strata_memory_growth_bytes"), + ) + return MemoryBasis("local") + + +def worker_config(plan, *, control_token, state_path, log_path=None, config_path=None, task_state_dir=None): + """Config for the supervised worker. Callers supply paths; the key set lives here.""" + config = {key: plan[key] for key in ("local_path", "fingerprint", "worker_argv", "max_tokens")} + config["runtime"] = plan["runtime"] + if "request_defaults" in plan: + config["request_defaults"] = plan["request_defaults"] + config.update({key: plan[key] for key in ( + "private_worker", "access_key_file", "access_key_sha256", "api_key_sha256", "auth_runtime_sha256", + ) if key in plan}) + if plan["runtime"] == "tasks": + config.update(task_identity=plan["task_identity"], task_kinds=plan["task_kinds"], port=plan["port"], + task_runtime_fingerprint=plan["task_runtime_fingerprint"], task_state_dir=task_state_dir) + if plan.get("adapter_path") is not None: + config.update(adapter_path=plan["adapter_path"], adapter_identity=plan["adapter_identity"]) + if plan.get("training_binding") is not None: + config["training_binding"] = plan["training_binding"] + if "readiness_deadline" in plan: + config["worker_readiness_seconds"] = plan["readiness_deadline"] + if plan["runtime"] == "strata": + config["strata_expert_memory_gb"] = plan.get("strata_expert_memory_gb") + config["strata_context_tokens"] = plan.get("strata_context_tokens", 131072) + config["strata_speculation"] = plan.get("strata_speculation", False) + config["strata_decoding"] = plan["strata_decoding"] + if "strata_memory_allocation" in plan: + config["strata_memory_allocation"] = plan["strata_memory_allocation"] + if plan["runtime"] == "splash": + config.update({key: plan[key] for key in ("splash_served_model", "splash_weight_bytes", "splash_max_memory_gb")}) + for key in ( + "jit", "prefill_kernel", "decode_profile", "vision_profile", + "splash_model_dir", "splash_model_fingerprint", "splash_draft_model", "splash_draft_fingerprint", + "splash_launcher", "splash_runtime_fingerprint", + "strata_memory_estimate_bytes", "strata_memory_growth_bytes", + ): + if key in plan: + config[key] = plan[key] + config.update(model=plan["repo"] or plan["path"], control_token=control_token, + memory_policy=plan.get("memory_policy"), state_path=state_path) + if config_path is not None: + config["config_path"] = str(config_path) + if log_path is not None: + config["log_path"] = str(log_path) + return config + + +def receipt_fields(plan): + """Plan fields copied onto a serve receipt. The caller adds pid, log, and time.""" + fields = {} + if plan.get("jit"): + fields["jit"] = True + if plan.get("api_key_sha256") is not None: + fields["api_key_sha256"] = plan["api_key_sha256"] + if "private_worker" in plan: + fields["protection"] = { + "access": "api_key", + "worker_transport": plan["private_worker"]["protocol"], + "worker_source_sha256": plan["private_worker"]["source_sha256"], + } + if plan.get("task_kinds"): + fields["task_kinds"] = plan["task_kinds"] + if plan.get("adapter_path") is not None: + fields.update(adapter_path=plan["adapter_path"], adapter_identity=plan["adapter_identity"]) + if plan.get("training_binding") is not None: + fields["training_binding"] = plan["training_binding"] + if "prefill_kernel" in plan: + fields["prefill_kernel"] = plan["prefill_kernel"] + if "decode_profile" in plan: + fields["decode_profile"] = plan["decode_profile"] + if "vision_profile" in plan: + fields["vision_profile"] = plan["vision_profile"] + if "strata_decoding" in plan: + fields["strata_decoding"] = plan["strata_decoding"] + if "strata_memory_allocation" in plan: + fields["strata_memory_allocation"] = plan["strata_memory_allocation"] + if plan["runtime"] == "splash": + fields.update(splash_served_model=plan["splash_served_model"], splash_version=plan["splash_version"]) + return fields diff --git a/packages/codex/mlx-agent/src/mlx_agent/source_evidence.py b/packages/codex/mlx-agent/src/mlx_agent/source_evidence.py new file mode 100644 index 0000000..79629d8 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/source_evidence.py @@ -0,0 +1,128 @@ +"""Bounded local source identities and completed managed-fetch provenance.""" +from __future__ import annotations + +import hashlib +import json +import os +from pathlib import Path +import re +import stat + +MAX_FILES = 10000 +MAX_JSON = 2 * 1024 * 1024 +_COMMIT = re.compile(r"[0-9a-fA-F]{40}") + + +def immutable_revision(value): + return isinstance(value, str) and _COMMIT.fullmatch(value) is not None + + +def safe_path(value): + path = Path(value).expanduser().absolute() + for component in (path, *path.parents): + if component.is_symlink(): + if str(component) in ("/var", "/tmp", "/etc") and os.readlink(component) == "private" + str(component): + continue + raise ValueError("Source evidence cannot traverse symbolic links.") + return path.resolve() + + +def read_json(path): + location = safe_path(path) + descriptor = os.open(location, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)) + try: + before = os.fstat(descriptor) + if (not stat.S_ISREG(before.st_mode) or before.st_size > MAX_JSON + or before.st_uid != os.getuid() or before.st_mode & 0o022): + raise ValueError("Source evidence must be a bounded regular JSON file.") + raw = os.read(descriptor, MAX_JSON + 1) + after = os.fstat(descriptor) + if len(raw) > MAX_JSON or (before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns): + raise ValueError("Source evidence changed while reading.") + value = json.loads(raw) + if not isinstance(value, dict): + raise ValueError("Source evidence must be an object.") + return value + finally: + os.close(descriptor) + + +def file_identity(path, root=None): + location = safe_path(path) + before = location.stat() + if not stat.S_ISREG(before.st_mode): + raise ValueError("A source identity requires a regular file.") + digest = hashlib.sha256() + digest.update(json.dumps([before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns]).encode()) + with location.open("rb") as stream: + digest.update(stream.read(1024 * 1024)) + if before.st_size > 2 * 1024 * 1024: + stream.seek(-1024 * 1024, os.SEEK_END) + digest.update(stream.read(1024 * 1024)) + after = location.stat() + if (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns): + raise ValueError("Source files changed while reading.") + name = str(location.relative_to(safe_path(root))) if root is not None else str(location) + return {"path": name, "bytes": before.st_size, "signature": digest.hexdigest()} + + +def identities(path, exclude=()): + root = safe_path(path) + if root.is_file(): + return [file_identity(root)] + if not root.is_dir(): + raise ValueError("The source directory is missing.") + result = [] + def failed(error): + raise error + for directory, dirs, files in os.walk(root, followlinks=False, onerror=failed): + dirs[:] = sorted(name for name in dirs if name != ".cache") + for name in dirs: + safe_path(Path(directory) / name) + for name in sorted(files): + item = Path(directory) / name + if str(item.relative_to(root)) in exclude: + continue + result.append(file_identity(item, root)) + if len(result) > MAX_FILES: + raise ValueError("The source exceeds the bounded file identity limit.") + return sorted(result, key=lambda item: item["path"]) + + +def fingerprint(path, exclude=()): + return hashlib.sha256(json.dumps(identities(path, exclude), sort_keys=True, separators=(",", ":")).encode()).hexdigest() + + +def completed_fetch(receipt_path, selected_path=None, bundle_root=False): + receipt_path = safe_path(receipt_path) + receipt = read_json(receipt_path) + if receipt.get("kind") != "fetch" or not immutable_revision(receipt.get("revision")) or not receipt.get("fresh_destination"): + raise ValueError("Conversion needs a completed immutable managed fetch receipt.") + marker_path = receipt_path.with_name(receipt_path.stem + ".done.json") + if safe_path(receipt.get("marker", "")) != marker_path: + raise ValueError("The fetch marker is outside its recorded receipt.") + marker = read_json(marker_path) + keys = ("repo", "revision", "file", "subfolder", "additional_files", "local_dir", "preview_hash", "proof_token", "started_at", "downloads_dir", "downloads") + if marker.get("exit_status") != "done" or not receipt.get("proof_token") or any(marker.get(key) != receipt.get(key) for key in keys): + raise ValueError("The completed fetch does not match its source receipt.") + root = safe_path(receipt["local_dir"]) + if safe_path(marker.get("path", "")) != root or marker.get("files") != identities(root): + raise ValueError("The downloaded source files changed after completion.") + suffix = receipt.get("file") or receipt.get("subfolder") + selected = root if bundle_root and receipt.get("file") else (root / suffix if suffix else root) + selected = safe_path(selected) + if selected_path is not None and safe_path(selected_path) != selected: + raise ValueError("The conversion source differs from the completed download selection.") + origin = {key: receipt.get(key) for key in ("repo", "revision", "file", "subfolder", "additional_files")} + evidence = {"origin": origin, "path": str(selected), "fingerprint": fingerprint(selected), + "fetch_receipt": str(receipt_path)} + if receipt.get("downloads"): + support = safe_path(receipt["downloads_dir"]) + if support == root or not support.is_relative_to(root): + raise ValueError("Managed support files are outside the reviewed download.") + files = [] + for item in receipt["downloads"]: + target = support / item["sha256"] / item["url"].rsplit("/", 1)[-1] + files.append(file_identity(target, root)) + evidence["support"] = {"downloads_dir": str(support), "downloads": receipt["downloads"], "files": files} + return evidence diff --git a/packages/codex/mlx-agent/src/mlx_agent/speak_runner.py b/packages/codex/mlx-agent/src/mlx_agent/speak_runner.py index 0248a1c..c1a8115 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/speak_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/speak_runner.py @@ -7,6 +7,11 @@ import time import wave +if __package__: + from .runner_model_cache import load_model +else: + from runner_model_cache import load_model + def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) @@ -36,7 +41,7 @@ def _synthesize(arguments): from mlx_audio.tts.utils import load started = time.time() - model = load(arguments.model, model_type=arguments.model_type) + model = load_model(load, arguments.model, model_type=arguments.model_type) load_seconds = time.time() - started kwargs = {"text": arguments.text, "speed": arguments.speed, "verbose": False} diff --git a/packages/codex/mlx-agent/src/mlx_agent/splash_runtime.py b/packages/codex/mlx-agent/src/mlx_agent/splash_runtime.py new file mode 100644 index 0000000..1d2b2f7 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/splash_runtime.py @@ -0,0 +1,289 @@ +"""Optional Splash serving for local GGUF and MLX targets, including prepared Strata profiles.""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import re +import shutil +import subprocess +from pathlib import Path + +from .serving_plan import Contribution + +MIN_VERSION = (1, 4, 0) +_VERSION = re.compile(r"Splash (\d+)\.(\d+)\.(\d+)") +_SPLIT = re.compile(r"(.+)-(\d{5})-of-(\d{5})\.gguf") +# Splash's --model rule: an OWNER/REPO repository ID without "--" or "..". +_OWNER = re.compile(r"[A-Za-z0-9_](?:[A-Za-z0-9._-]*[A-Za-z0-9_])?") +_SERVED_NAME = re.compile(r"[A-Za-z0-9_](?:[A-Za-z0-9._-]{0,94}[A-Za-z0-9_])?") +_LAUNCHER_DIRS = ("/opt/homebrew/bin", "/usr/local/bin", "~/.local/bin") +_INSTALL = ("Install Splash 1.4.0 or later on an Apple M3 or newer with macOS 26.4 or later " + "(brew install incoai/tap/splash); serve never installs runtimes.") + + +class SplashError(RuntimeError): + def __init__(self, code, message, remediation=_INSTALL): + super().__init__(message) + self.code = code + self.remediation = remediation + + +def find_launcher(): + """The `splash` launcher: MLX_AGENT_SPLASH, PATH, then the Homebrew and ~/.local/bin locations.""" + override = os.environ.get("MLX_AGENT_SPLASH") + candidates = [override] if override else [shutil.which("splash")] + [ + str(Path(directory).expanduser() / "splash") for directory in _LAUNCHER_DIRS] + for candidate in candidates: + if candidate and Path(candidate).is_file() and os.access(candidate, os.X_OK): + return Path(candidate).absolute() + raise SplashError("splash_not_installed", "No executable Splash launcher was found.") + + +def installed_runtime(launcher=None, run=subprocess.run): + """Version and identity of a released Splash launcher; a source checkout reports no version.""" + path = Path(launcher) if launcher is not None else find_launcher() + try: + result = run([str(path), "--version"], capture_output=True, text=True, timeout=30, + stdin=subprocess.DEVNULL, env={**os.environ, "HF_HUB_OFFLINE": "1"}) + resolved = path.resolve() + content = resolved.read_bytes() + except (OSError, subprocess.SubprocessError) as error: + raise SplashError("splash_not_installed", "The Splash launcher could not run: " + str(error)) from error + match = _VERSION.fullmatch((result.stdout or "").strip()) + if result.returncode != 0 or match is None: + raise SplashError("splash_not_installed", "The Splash launcher did not report a release version.") + version = tuple(int(part) for part in match.groups()) + text = ".".join(str(part) for part in version) + if version < MIN_VERSION: + raise SplashError("splash_version_unsupported", + "Splash {0} predates 1.4.0, the first release serving split GGUFs.".format(text), + "Upgrade Splash (brew upgrade incoai/tap/splash).") + digest = hashlib.sha256() + for part in (str(path), str(resolved), text): + digest.update(part.encode() + b"\0") + digest.update(content) + return {"launcher": str(path), "resolved": str(resolved), "version": text, "fingerprint": digest.hexdigest()} + + +def _engine(runtime): + """The engine binary of a released Splash installation, beside its launcher's bin folder.""" + engine = Path(runtime["resolved"]).parents[1] / "libexec" / "engine" / "splash" + return engine if engine.is_file() and os.access(engine, os.X_OK) else None + + +def worker_entry(runtime): + """The Python program the shell launcher runs, which a supervised worker starts directly.""" + libexec = Path(runtime["resolved"]).parents[1] / "libexec" + python, launcher = libexec / "python" / "bin" / "python3", libexec / "install" / "launcher.py" + if not (python.is_file() and os.access(python, os.X_OK) and launcher.is_file()): + raise SplashError("splash_not_installed", "The Splash installation has no launcher program for --jit.") + return [str(python), str(launcher)] + + +def annotate_support(outputs, run=subprocess.run): + """Add ``splash`` to each quantized MLX output: the family Splash's engine finds its config to describe, else its refusal. + + The engine's ``model-check`` is the rule Splash holds every start to. Nothing is added without an installed + release whose engine knows the check; Strata profiles keep their own runtime. + """ + try: + engine = _engine(installed_runtime(run=run)) + except SplashError: + return outputs + if engine is None: + return outputs + for output in outputs: + if output.get("runtime") is not None or not isinstance(output.get("quantization"), dict): + continue + try: + result = run([str(engine), "model-check", "mlx-affine", "none", str(Path(output["path"]) / "config.json")], + capture_output=True, text=True, timeout=30, stdin=subprocess.DEVNULL) + except (OSError, subprocess.SubprocessError): + return outputs + if result.returncode == os.EX_USAGE: + return outputs + if result.returncode == 0: + try: + family = json.loads(result.stdout)["family"] + except (ValueError, TypeError, KeyError): + continue + if isinstance(family, str): + output["splash"] = {"family": family} + continue + refusals = [line[len("error: "):] for line in (result.stderr or "").splitlines() if line.startswith("error: ")] + output["splash"] = {"family": None, "reason": refusals[-1] if refusals else None} + return outputs + + +def _identity(paths): + from .strata_runtime import file_identity + return {str(path): file_identity(path) for path in paths} + + +def _fingerprint(identities): + return hashlib.sha256(json.dumps(identities, sort_keys=True).encode()).hexdigest() + + +def _gguf_parts(path): + if path.suffix != ".gguf" or not path.is_file(): + raise ValueError("A Splash GGUF target is a file ending in .gguf: " + str(path)) + match = _SPLIT.fullmatch(path.name) + if match is None: + return [path] + stem, _, count = match.groups() + parts = [path.with_name("{0}-{1:05d}-of-{2}.gguf".format(stem, index, count)) for index in range(1, int(count) + 1)] + missing = [part.name for part in parts if not part.is_file()] + if not parts or missing: + raise FileNotFoundError("Missing split GGUF part: " + (missing[0] if missing else path.name)) + return parts + + +def _repository_id(value): + owner, _, name = value.partition("/") + return (_OWNER.fullmatch(owner) is not None and _SERVED_NAME.fullmatch(name) is not None + and "--" not in value and ".." not in value and not value.endswith(".git")) + + +def _served_model(name): + cleaned = re.sub(r"[^A-Za-z0-9._-]+", "-", name) + cleaned = re.sub(r"-{2,}", "-", re.sub(r"\.{2,}", ".", cleaned))[:96].strip("-.") or "model" + if cleaned.endswith(".git") or not _SERVED_NAME.fullmatch(cleaned): + cleaned = "model" + return "local/" + cleaned + + +def read_target(path, served_model=None): + """Resolve a local target without loading weights: a GGUF file or part, a GGUF or MLX directory, or a Strata profile. + + ``served_model`` is a cached repository's ID, which the API then reports; otherwise the name is ``local/``. + """ + root = Path(path).expanduser().absolute() + if served_model is not None and not _repository_id(served_model): + raise SplashError("invalid_repo", "Splash cannot report {0} as an OWNER/REPO model ID.".format(served_model), + "Serve the snapshot with --path instead.") + try: + source = None + if root.is_dir() and (root / "strata-model.json").is_file(): + from .gguf import GGUFError + from .strata_runtime import StrataError, read_model + try: + target = Path(read_model(root)["gguf"]) + except (StrataError, GGUFError) as error: + code = error.code if isinstance(error, StrataError) else "splash_model_invalid" + raise SplashError(code, str(error), "Select a valid prepared Strata profile or its GGUF file.") from error + files, weight_format, source, name = _gguf_parts(target), "gguf", "strata_profile", root.name + elif root.is_file(): + target, files, weight_format = root, _gguf_parts(root), "gguf" + match = _SPLIT.fullmatch(root.name) + name = match.group(1) if match else root.stem + elif root.is_dir() and (root / "config.json").is_file(): + config = json.loads((root / "config.json").read_text(encoding="utf-8")) + if not isinstance(config, dict) or not isinstance(config.get("quantization"), dict): + raise ValueError("Splash serves quantized MLX checkpoints; config.json declares no quantization.") + weights = sorted(root.glob("*.safetensors")) + if not weights: + raise FileNotFoundError("The MLX directory holds no .safetensors weights.") + target, files, weight_format, name = root, [root / "config.json", *weights], "mlx", root.name + elif root.is_dir(): + ggufs = sorted(item for item in root.glob("*.gguf") if "mmproj" not in item.name.lower()) + groups = {(_SPLIT.fullmatch(item.name).group(1) if _SPLIT.fullmatch(item.name) else item.stem) for item in ggufs} + if len(groups) != 1: + raise ValueError("A Splash GGUF directory must hold the GGUF targets of exactly one name; select the file instead.") + target, files, weight_format, name = root, _gguf_parts(ggufs[0]), "gguf", groups.pop() + else: + raise FileNotFoundError("The Splash target is not present: " + str(root)) + if weight_format == "gguf": + from .gguf import GGUFError, read_gguf_header + try: + architecture = read_gguf_header(files[0])["metadata"].get("general.architecture") + except GGUFError as error: + raise ValueError("Not a readable GGUF file: " + str(error)) from error + else: + architecture = config.get("model_type") + identities = _identity(files) + return {"path": str(root), "target": str(target), "source": source, "format": weight_format, + "architecture": architecture if isinstance(architecture, str) else None, + "files": [str(item) for item in files], "weight_bytes": sum(item.stat().st_size for item in files), + "served_model": served_model or _served_model(name), "fingerprint": _fingerprint(identities)} + except SplashError: + raise + except FileNotFoundError as error: + raise SplashError("model_not_local", str(error), "Point --path at local model files; serve never downloads models.") from error + except (OSError, ValueError, TypeError, KeyError) as error: + raise SplashError("splash_model_invalid", str(error), "Select a quantized GGUF or MLX target that Splash supports.") from error + + +def read_draft(path): + """A local DFlash2 draft directory: config.json with dflash_config, and safetensors weights.""" + root = Path(path).expanduser().absolute() + remediation = "Pass a local DFlash2 draft directory, such as a download of incoai/Qwen3.8-Flash-Next-DFlash2." + try: + config = json.loads((root / "config.json").read_text(encoding="utf-8")) + weights = sorted(root.glob("*.safetensors")) + if not isinstance(config, dict) or not isinstance(config.get("dflash_config"), dict) or not weights: + raise ValueError("The directory is not a DFlash2 draft (config.json dflash_config and safetensors weights).") + identities = _identity([root / "config.json", *weights]) + size = sum(item.stat().st_size for item in weights) + except (OSError, ValueError, TypeError) as error: + raise SplashError("splash_draft_invalid", str(error), remediation) from error + return {"path": str(root), "fingerprint": _fingerprint(identities), "weight_bytes": size} + + +def serve_arguments(draft=None, max_memory_gb=None, max_context_tokens=None): + """Bounded Splash options appended after the recipe; sizes go as whole bytes, never binary-unit text.""" + args = [] + if draft is not None: + args += ["--draft-model", draft["path"]] + if max_memory_gb is not None: + if type(max_memory_gb) not in (int, float) or not math.isfinite(max_memory_gb) or not 1 <= max_memory_gb <= 1024: + raise SplashError("invalid_arguments", "Splash memory must be a finite value from 1 to 1024 GB.", + "Pass --splash-max-memory-gb in decimal GB.") + args += ["--max-memory", str(math.floor(max_memory_gb * 1e9))] + if max_context_tokens is not None: + if type(max_context_tokens) is not int or not 512 <= max_context_tokens <= 1_010_000: + raise SplashError("invalid_arguments", "Splash context must be an integer from 512 to 1010000 tokens.", + "Pass --splash-max-context in tokens.") + args += ["--max-context", str(max_context_tokens)] + return args + + +def plan_contribution(local_path, has_repo, repo, hf_cache, adapter_path, jit, runtime_executable, + draft_model, max_memory_gb, max_context_tokens): + """Splash's part of a serving plan. Raises SplashError; the caller maps it.""" + if adapter_path is not None: + raise SplashError("invalid_arguments", "Splash serves local weights without a LoRA adapter.", + "Remove the adapter path.") + model_dir = local_path + if has_repo: + from .convert import cached_snapshot + snapshot = cached_snapshot(repo.strip(), hf_cache) + if snapshot is None: + raise SplashError("model_not_local", "The repository is not in the Hugging Face cache: " + repo.strip(), + "Download it first; serve never downloads models.") + model_dir = str(snapshot) + if jit and not Path(model_dir).is_dir(): + raise SplashError("invalid_arguments", "--jit serves a model directory.", + "Select the directory that holds the GGUF, or the Strata profile.") + target = read_target(model_dir, served_model=repo.strip() if has_repo else None) + draft = read_draft(draft_model) if draft_model is not None else None + runtime = installed_runtime() + if runtime_executable is not None and runtime_executable != runtime["launcher"]: + raise SplashError("splash_not_installed", "The reviewed Splash launcher changed.") + fields = {"splash_launcher": runtime["launcher"], + "splash_version": runtime["version"], "splash_runtime_fingerprint": runtime["fingerprint"], + "splash_model_fingerprint": target["fingerprint"], "splash_target": target["target"], + "splash_model_dir": model_dir, "splash_served_model": target["served_model"], + "splash_source": target["source"], "splash_draft_model": draft["path"] if draft else None, + "splash_draft_fingerprint": draft["fingerprint"] if draft else None, + "splash_max_memory_gb": max_memory_gb, "splash_max_context_tokens": max_context_tokens, + "weight_format": target["format"], "weight_bytes": target["weight_bytes"], + "weights_preserved": True, "readiness_deadline": 900} + entry = worker_entry(runtime) if jit else None + if jit: + fields.update(splash_worker_entry=entry, + splash_weight_bytes=target["weight_bytes"] + (draft["weight_bytes"] if draft else 0)) + values = {"executable": runtime["launcher"], "served_model": target["served_model"], "splash_target": target["target"]} + return Contribution(serve_arguments(draft, max_memory_gb, max_context_tokens), values, fields, worker_entry=entry) diff --git a/packages/codex/mlx-agent/src/mlx_agent/standalone_assets.py b/packages/codex/mlx-agent/src/mlx_agent/standalone_assets.py new file mode 100644 index 0000000..89e79e6 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/standalone_assets.py @@ -0,0 +1,237 @@ +"""Read-only inventory and explicit byte comparison of standalone model files.""" + +from __future__ import annotations + +import hashlib +import os +import re +import stat +from pathlib import Path + +_CHUNK = 1024 * 1024 +_SHARD = re.compile(r"(?:^|[-_.])\d+-of-\d+(?:\.|$)", re.IGNORECASE) +_SKIP = {".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv", ".tox", ".mypy_cache", ".pytest_cache", ".quarantine", ".Trash"} + + +def _identity(st): + return (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns, st.st_nlink) + + +def _model_marker(names): + return any(name in {"config.json", "model_index.json"} or name.endswith(".index.json") for name in names) + + +def _provider_path(path): + return any(part.startswith("models--") for part in path.parts) + + +def _exists(path): + try: + path.stat() + return True + except (FileNotFoundError, NotADirectoryError): + return False + + +def _excluded_ancestor(path): + for parent in (path, *path.parents): + if _provider_path(parent): + return True + markers = ("config.json", "model_index.json", "model.safetensors.index.json", + "pytorch_model.bin.index.json", "diffusion_pytorch_model.safetensors.index.json") + if any(_exists(parent / marker) for marker in markers): + return True + if _exists(parent / "blobs") and (_exists(parent / "manifests") or _exists(parent / "manifests-v2")): + return True + return False + + +def _open_parent(path, root, root_identity): + root_fd = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + descriptors = [root_fd] + try: + opened_root = os.fstat(root_fd) + if (opened_root.st_dev, opened_root.st_ino) != root_identity: + raise OSError("Scan root changed") + relative = Path(os.path.abspath(path)).relative_to(Path(os.path.abspath(root))) + parent_fd = root_fd + for component in relative.parts[:-1]: + parent_fd = os.open(component, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=parent_fd) + descriptors.append(parent_fd) + return parent_fd, relative.name, descriptors + except BaseException: + for descriptor in reversed(descriptors): + os.close(descriptor) + raise + + +def _stat_beneath(path, root, root_identity): + parent, name, descriptors = _open_parent(path, root, root_identity) + try: + return os.stat(name, dir_fd=parent, follow_symlinks=False) + finally: + for descriptor in reversed(descriptors): + os.close(descriptor) + + +def hash_file(path, expected, root, root_identity): + """Hash a stable regular file through no-follow descriptors beneath its root.""" + file_flags = os.O_RDONLY | os.O_NOFOLLOW | getattr(os, "O_NONBLOCK", 0) + parent_fd, name, descriptors = _open_parent(path, root, root_identity) + fd = None + try: + fd = os.open(name, file_flags, dir_fd=parent_fd) + before = os.fstat(fd) + if not stat.S_ISREG(before.st_mode) or before.st_nlink != 1 or _identity(before) != expected: + raise OSError("File changed before comparison") + digest = hashlib.sha256() + while True: + chunk = os.read(fd, _CHUNK) + if not chunk: + break + digest.update(chunk) + after = os.fstat(fd) + current = _stat_beneath(path, root, root_identity) + current_root = os.lstat(root) + if (not stat.S_ISREG(current.st_mode) or _identity(after) != expected or _identity(current) != expected + or (current_root.st_dev, current_root.st_ino) != root_identity): + raise OSError("File or scan root changed during comparison") + return digest.hexdigest() + finally: + if fd is not None: + os.close(fd) + for descriptor in reversed(descriptors): + os.close(descriptor) + + +def scan(roots, owned_items, limit, compare=False, exclude_roots=()): + """Return storage items, full-digest groups and explicit coverage details.""" + owned = {file["id"] for item in owned_items for file in item["files"]} + items, errors, identities = [], [], {} + seen = set() + limited = False + excluded_roots = sorted(set(os.path.realpath(os.path.expanduser(value)) for value in exclude_roots if value)) + + def excluded(path): + candidate = os.path.realpath(path) + return any(os.path.commonpath((candidate, root)) == root for root in excluded_roots) + + visited = 0 + visit_limit = max(1024, limit * 32) + + def error(path, message): + record = {"path": str(path), "message": str(message)} + if record not in errors: + errors.append(record) + + for root in dict.fromkeys(str(Path(value).expanduser()) for value in roots): + base = Path(root) + if excluded(base): + continue + try: + st_root = base.lstat() + if not stat.S_ISDIR(st_root.st_mode) or _excluded_ancestor(Path(os.path.abspath(base))): + continue + except OSError as exc: + error(base, exc) + continue + for folder, dirs, files in os.walk(base, followlinks=False, onerror=lambda exc: error(exc.filename or base, exc)): + here = Path(folder) + visited += 1 + len(dirs) + len(files) + if visited > visit_limit: + limited = True + break + if _provider_path(here) or _model_marker(files) or ("blobs" in dirs and ({"manifests", "manifests-v2"} & set(dirs))): + dirs[:] = [] + continue + dirs[:] = sorted(name for name in dirs if name not in _SKIP and not name.startswith(".") + and not name.startswith("models--") and not (here / name).is_symlink() + and not excluded(here / name)) + for name in sorted(files): + path = here / name + if path.suffix.lower() not in {".safetensors", ".ckpt"} or _SHARD.search(name): + continue + key = str(path) + unique_path = os.path.abspath(key) + if unique_path in seen: + continue + seen.add(unique_path) + try: + st = path.lstat() + except OSError as exc: + error(path, exc) + continue + if not stat.S_ISREG(st.st_mode): + continue + try: + checked_stat = _stat_beneath(key, root, (st_root.st_dev, st_root.st_ino)) + if not stat.S_ISREG(checked_stat.st_mode) or _identity(st) != _identity(checked_stat): + raise OSError("File changed during inventory") + except OSError as exc: + error(path, exc) + continue + disk_id = "{0}:{1}".format(st.st_dev, st.st_ino) + if disk_id in owned: + continue + if len(items) >= limit: + limited = True + break + items.append({"path": key, "kind": "asset", "format": path.suffix[1:].lower(), "name": name, + "model_key": key, "shape": None, "files": [{"id": disk_id, "path": key, "bytes": st.st_size}], + "asset": {"sha256": None, "mtime_ns": st.st_mtime_ns, "ctime_ns": st.st_ctime_ns, "nlink": st.st_nlink}}) + identities[key] = (_identity(st), root, (st_root.st_dev, st_root.st_ino)) + if limited: + break + if limited: + break + if limited: + error(base, "Standalone model-file scan reached a file or traversal limit; results are incomplete.") + items.sort(key=lambda item: item["path"]) + sizes = {} + for item in items: + identity = identities[item["path"]][0] + if identity[-1] == 1: + sizes.setdefault(identity[2], []).append(item) + candidates = [item for group in sizes.values() if len(group) > 1 for item in group] if compare else [] + checked = 0 + digests = {} + for item in candidates: + try: + if _excluded_ancestor(Path(os.path.abspath(item["path"])).parent): + raise OSError("Model-file ownership changed before comparison") + digest = hash_file(item["path"], *identities[item["path"]]) + if _excluded_ancestor(Path(os.path.abspath(item["path"])).parent): + raise OSError("Model-file ownership changed during comparison") + except OSError as exc: + error(item["path"], exc) + continue + checked += 1 + item["asset"]["sha256"] = digest + digests.setdefault(digest, []).append(item) + groups = [] + for digest, members in sorted(digests.items()): + stable = [] + for item in members: + try: + identity, root, root_identity = identities[item["path"]] + if _excluded_ancestor(Path(os.path.abspath(item["path"])).parent): + raise OSError("Model-file ownership changed after comparison") + current = _stat_beneath(item["path"], root, root_identity) + if not stat.S_ISREG(current.st_mode) or _identity(current) != identities[item["path"]][0]: + raise OSError("File changed after comparison") + stable.append(item) + except OSError as exc: + error(item["path"], exc) + item["asset"]["sha256"] = None + checked -= 1 + members = stable + if len(members) < 2: + continue + members.sort(key=lambda item: item["path"]) + identity = "asset:sha256:" + digest + groups.append({"kind": "exact", "verification": "full_sha256", "identity": identity, + "model_key": members[0]["name"], "keep": members[0]["path"], + "redundant": [item["path"] for item in members[1:]], + "reclaimable_bytes": sum(item["files"][0]["bytes"] for item in members[1:])}) + return items, groups, {"compared": compare, "candidates": len(candidates), "checked": checked, + "errors": errors, "excluded_roots": excluded_roots} diff --git a/packages/codex/mlx-agent/src/mlx_agent/strata_runtime.py b/packages/codex/mlx-agent/src/mlx_agent/strata_runtime.py index c90827f..e2b76d9 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/strata_runtime.py +++ b/packages/codex/mlx-agent/src/mlx_agent/strata_runtime.py @@ -20,6 +20,8 @@ MODEL_MARKER = "strata-model.json" INSTALL_MARKER = "installed.json" _FIRST = re.compile(r"Qwen3\.8-Flash-Next-GSQ-RCO-(Q2_0|IQ3_S)-00001-of-00002\.gguf") +# Names, shapes, BF16 dtypes and byte sizes of the supported 31-tensor head. +_MTP_LAYOUT = "c533cc874cc6c8723eeaa55a615de1c5703b1f6639f455455c9eaa04b3590783" # GGUF block layouts implemented by the pinned engine. No tensor data is loaded here. _BLOCKS = {0: (1, 4), 1: (1, 2), 30: (1, 2), 2: (32, 18), 6: (32, 22), 8: (32, 34), 11: (256, 110), 12: (256, 144), 13: (256, 176), 14: (256, 210), @@ -115,6 +117,54 @@ def file_identity(path): return {"bytes": stat.st_size, "mtime_ns": stat.st_mtime_ns, "device": stat.st_dev, "inode": stat.st_ino, "header_sha256": header} +def _mtp_parameter_bytes(tensors, metadata): + """Final float16/4-bit storage in both supported native loaders; unknown layouts stay raw.""" + if not isinstance(metadata, dict): + return None + dimensions = {"embedding_length": 2560, "expert_count": 512, + "expert_feed_forward_length": 640, "hyper_connection.count": 4} + if any(type(metadata.get("qwen4exp." + key)) is not int + or metadata["qwen4exp." + key] != value for key, value in dimensions.items()): + return None + if not isinstance(tensors, list) or len(tensors) != 31: + return None + layout = [] + for tensor in tensors: + if not isinstance(tensor, dict): + return None + shape = tensor.get("shape") + if (not isinstance(tensor.get("name"), str) or tensor.get("dtype") != "BF16" + or not isinstance(shape, list) or not 1 <= len(shape) <= 3 + or any(type(n) is not int or n <= 0 for n in shape) + or type(tensor.get("bytes")) is not int or tensor["bytes"] != math.prod(shape) * 2): + return None + if ".mlp.experts." in tensor["name"]: + if len(shape) != 3 or shape[-1] % 64 or (tensor["name"].endswith("gate_up_proj") and shape[1] % 2): + return None + layout.append({key: tensor[key] for key in ("name", "dtype", "shape", "bytes")}) + if len({item["name"] for item in layout}) != 31: + return None + encoded = json.dumps(sorted(layout, key=lambda item: item["name"]), sort_keys=True, separators=(",", ":")) + if hashlib.sha256(encoded.encode()).hexdigest() != _MTP_LAYOUT: + return None + total = 0 + for tensor in layout: + if ".mlp.experts." in tensor["name"]: + count = math.prod(tensor["shape"]) + # Four-bit weights, plus one float16 scale and bias per group of 64. + total += count // 8 * 4 + count // 64 * 4 + else: + total += tensor["bytes"] + return total + + +def _mtp_savings(model, speculation): + raw, packed = model.get("mtp_bytes", 0), model.get("mtp_parameter_bytes") + if speculation and type(raw) is int and type(packed) is int and 0 < packed <= raw: + return raw - packed + return 0 + + def read_model(path): root = Path(path).expanduser().absolute() try: @@ -133,6 +183,8 @@ def read_model(path): from mlx_agent.gguf import read_gguf_header for index, weight in enumerate((first, second)): header = read_gguf_header(weight) + if index == 0: + text_metadata = header["metadata"] architecture = header["metadata"].get("general.architecture") if architecture != "qwen4exp" and not (index == 1 and architecture is None and header["tensor_count"] == 1): raise ValueError("GGUF architecture is not Qwen3.8-Flash-Next") @@ -142,6 +194,7 @@ def read_model(path): assets.append(_local(root, "tokenizer/" + name)) mtp = None mtp_bytes = 0 + mtp_parameter_bytes = 0 if profile["mtp"] is not None: mtp = _local(root, profile["mtp"], directory=True) manifest_path = _local(root, str(mtp.relative_to(root) / "mtp-manifest.json")) @@ -159,6 +212,7 @@ def read_model(path): raise ValueError("MTP tensor size changed") mtp_bytes += location.stat().st_size assets.append(location) + mtp_parameter_bytes = _mtp_parameter_bytes(tensors, text_metadata) or mtp_bytes identities = {str(asset.relative_to(root)): file_identity(asset) for asset in assets} fingerprint = hashlib.sha256(json.dumps(identities, sort_keys=True).encode()).hexdigest() # The second shard is the on-disk n-gram lookup table, not resident @@ -169,6 +223,7 @@ def read_model(path): return {"root": str(root), "gguf": str(first), "tokenizer": str(tokenizer), "mtp": str(mtp) if mtp else None, "quantization": "GSQ-RCO " + _FIRST.fullmatch(first.name).group(1), "mtp_bytes": mtp_bytes, + "mtp_parameter_bytes": mtp_parameter_bytes, "fingerprint": fingerprint, "weight_bytes": first.stat().st_size + second.stat().st_size, "memory_estimate_bytes": memory_estimate} except StrataError: @@ -194,7 +249,8 @@ def memory_estimate(model, expert_memory_gb=None, context_tokens=131072, specula or not 0.5 <= expert_memory_gb <= 64): raise StrataError("invalid_arguments", "Expert memory must be a finite number from 0.5 to 64 GB.") fixed, experts = _memory_parts(model, context_tokens, speculation) - return math.ceil(min(experts, expert_memory_gb * 1e9) + fixed) + steady = fixed - _mtp_savings(model, speculation) + min(experts, expert_memory_gb * 1e9) + return math.ceil(max(steady, fixed + min(experts, 500_000_000))) def _memory_parts(model, context_tokens, speculation): @@ -225,6 +281,17 @@ def _memory_parts(model, context_tokens, speculation): raise StrataError("strata_memory_unknown", "Cannot estimate paged Strata memory: " + str(error)) from error +def memory_growth_allowance(model, context_tokens=131072, cache_capacity_gb=None, speculation=False): + """Reserve runtime, context and expert-cache capacity not measured in the worker.""" + _validate_context(context_tokens) + if cache_capacity_gb is not None and (type(cache_capacity_gb) not in (int,float) + or not math.isfinite(cache_capacity_gb) or not 0 <= cache_capacity_gb <= 64): + raise StrataError('invalid_arguments','Invalid expert-cache growth allowance.') + _, experts = _memory_parts(model,context_tokens,speculation) + growth = experts if cache_capacity_gb is None else min(experts,cache_capacity_gb*1e9) + return math.ceil(5e9 + context_tokens*30000 + growth) + + def memory_allocation(model, budget_gb, context_tokens=131072, speculation=False): """Resolve an estimated total allowance without changing native expert selection.""" if type(budget_gb) not in (int, float) or not math.isfinite(budget_gb) or not 1 <= budget_gb <= 1024: @@ -236,12 +303,17 @@ def memory_allocation(model, budget_gb, context_tokens=131072, speculation=False if whole <= budget: cap, estimate, mode = None, whole, "resident" else: - remaining = budget - fixed - if remaining < min(experts, 500_000_000): + # Native paging loads the head before populating the expert cache. Keep + # the raw startup floor and resident threshold, then size the paged + # cache beside the packed head. The 5 GB working allowance is retained. + startup_floor = fixed + min(experts, 500_000_000) + if budget < startup_floor: raise StrataError("memory_budget_too_small", "Model memory budget cannot hold fixed weights, context and the minimum expert cache.") + fixed -= _mtp_savings(model, speculation) + remaining = budget - fixed # Round down before converting to native decimal GB; never overspend on rounding. cap = max(.5, min(64, remaining // 1_000_000 / 1000)) - estimate, mode = math.ceil(fixed + min(experts, cap * 1e9)), "paged" + estimate, mode = math.ceil(max(fixed + min(experts, cap * 1e9), startup_floor)), "paged" return {"budget_bytes": budget, "estimated_resident_bytes": estimate, "expert_memory_gb": cap, "mode": mode} @@ -270,7 +342,7 @@ def frontend_config(model, runtime, speculation=False, expert_memory_gb=None, co expert_memory_gb = memory_allocation(model, memory_budget_gb, context_tokens, speculation)["expert_memory_gb"] else: memory_estimate(model, expert_memory_gb, context_tokens, speculation) - args = ["--native", model["gguf"], "--spec", "4" if speculation else "1", + args = ["--native", model["gguf"], "--dtype", "float16", "--spec", "4" if speculation else "1", "--suffix-draft", "1" if mode == "lookup" else "0", "--max-context", str(context_tokens)] if expert_memory_gb is not None: args += ["--expert-memory", str(expert_memory_gb)] @@ -327,6 +399,57 @@ def main(): return 0 +def plan_contribution(local_path, has_path, adapter_path, strata_speculation, strata_decoding, + strata_context_tokens, strata_expert_memory_gb, memory_policy, runtime_executable): + """Strata's part of a serving plan. Raises StrataError; the caller maps it.""" + # This file is also executed by path, so the package import stays inside the function. + from .serving_plan import Contribution + if not has_path or adapter_path is not None or type(strata_speculation) is not bool: + raise StrataError("strata_model_required", "Strata requires a local GGUF profile without a LoRA adapter.") + model = read_model(local_path) + context = 131072 if strata_context_tokens is None else strata_context_tokens + decoding = resolve_decoding(model, strata_speculation, strata_decoding) + uses_draft = decoding == "mtp" + budget = (memory_policy or {}).get("model_memory_budget_gb") + allocation = None + if budget is not None: + if strata_expert_memory_gb is not None: + raise StrataError("invalid_arguments", "Choose a total model memory budget or an expert budget.") + allocation = memory_allocation(model, budget, context, uses_draft) + memory_bytes = allocation["estimated_resident_bytes"] + else: + memory_bytes = memory_estimate(model, strata_expert_memory_gb, context, uses_draft) + runtime = installed_runtime() + if runtime_executable is not None and runtime_executable != runtime["python"]: + raise StrataError("strata_not_installed", "The reviewed Strata executable changed.") + argv = ["--runtime-root", runtime["root"], "--speculation", "on" if strata_speculation else "off", + "--decoding", decoding, "--context-tokens", str(context), + "--expected-model-fingerprint", model["fingerprint"], + "--expected-runtime-fingerprint", runtime["fingerprint"]] + if strata_expert_memory_gb is not None: + argv += ["--expert-memory-gb", str(strata_expert_memory_gb)] + if allocation is not None: + argv += ["--memory-budget-gb", str(budget)] + if allocation is not None: + capacity = 0 if allocation["mode"] == "resident" else allocation["expert_memory_gb"] + else: + capacity = strata_expert_memory_gb + try: + growth = memory_growth_allowance(model, context, capacity, uses_draft) + except StrataError: + growth = None + fields = {"strata_model_fingerprint": model["fingerprint"], "strata_runtime_fingerprint": runtime["fingerprint"], + "weight_format": "gguf", "weight_quantization": model["quantization"], "weights_preserved": True, + "strata_speculation": strata_speculation, "strata_decoding": decoding, + "strata_expert_memory_gb": strata_expert_memory_gb, "strata_context_tokens": context, + "strata_memory_estimate_bytes": memory_bytes, "readiness_deadline": 900} + if growth is not None: + fields["strata_memory_growth_bytes"] = growth + if allocation is not None: + fields["strata_memory_allocation"] = allocation + return Contribution(argv, {"executable": runtime["python"]}, fields) + + if __name__ == "__main__": # The Strata interpreter gets this package alone, never the installing environment's site-packages. _package = Path(__file__).resolve().parent diff --git a/packages/codex/mlx-agent/src/mlx_agent/task_cli.py b/packages/codex/mlx-agent/src/mlx_agent/task_cli.py index 1bc2ce4..2fde5b3 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/task_cli.py +++ b/packages/codex/mlx-agent/src/mlx_agent/task_cli.py @@ -32,6 +32,8 @@ def add_arguments(parser): action.add_argument("--id", required=True, help="task UUID returned by start") elif command == "list": action.add_argument("--limit", type=int, default=20, help="maximum recent records, 1..100 (default: 20)") + elif command == "capabilities": + action.add_argument("--model-path", type=Path, help="inspect optional model-specific settings without loading weights") def summary(record): @@ -66,9 +68,9 @@ def run(arguments): action = arguments.task_command operation = "task." + action try: - store = TaskStore(arguments.state_dir) + store = TaskStore(arguments.state_dir) if action != "capabilities" else None if action == "capabilities": - data = capabilities() + data = capabilities(model_path=getattr(arguments, "model_path", None)) elif action == "verify-model": data = verify_task_model(arguments.id, store.root) elif action == "list": diff --git a/packages/codex/mlx-agent/src/mlx_agent/task_contracts.py b/packages/codex/mlx-agent/src/mlx_agent/task_contracts.py index c114534..ecb9a97 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/task_contracts.py +++ b/packages/codex/mlx-agent/src/mlx_agent/task_contracts.py @@ -196,10 +196,17 @@ def _artifact_reference(value): raise TaskError("invalid_task_record", "Task artifact evidence is invalid.") -def capabilities(): +def capabilities(model_path=None): from .task_kinds import KINDS - return {"schema": "task-capabilities/1", "request_schema": REQUEST_SCHEMA, "run_schema": RUN_SCHEMA, - "tasks": [kind.capability() for kind in KINDS.values()]} + result = {"schema": "task-capabilities/1", "request_schema": REQUEST_SCHEMA, "run_schema": RUN_SCHEMA, + "tasks": [kind.capability() for kind in KINDS.values()]} + if model_path is not None: + from .media_settings import model_settings + result["model"], settings = model_settings(model_path) + for task in result["tasks"]: + if task["kind"] in settings: + task["denoiser_cache"] = settings[task["kind"]] + return result def finite_number(value): diff --git a/packages/codex/mlx-agent/src/mlx_agent/task_kinds.py b/packages/codex/mlx-agent/src/mlx_agent/task_kinds.py index e5cdf46..660fb4a 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/task_kinds.py +++ b/packages/codex/mlx-agent/src/mlx_agent/task_kinds.py @@ -12,10 +12,12 @@ from .backends import backend_environment from .decide import plan_decide, run_decide, validate_request as validate_decision +from .embed import plan_embed, run_embed, validate_parameters as validate_embedding from .describe import plan_describe, run_describe from .generate import plan_generate, run_generate from .inference_runner import InferenceError from .music import plan_music, run_music, validate_parameters as validate_music +from .mesh import MeshError, plan_mesh, run_mesh, validate_glb from .speak import plan_speak, run_speak from .task_contracts import (MEDIA_REQUEST_SCHEMA, MEDIA_RUN_SCHEMA, REQUEST_SCHEMA, RUN_SCHEMA, TaskError, absolute_path, encoded, finite_number) @@ -53,8 +55,8 @@ def plan(self, request, directory, input_path=None): output = str(Path(directory) / self.output) if self.output else None return self.planner(request["model_path"], parameters, output, media, Path(directory)) - def run(self, plan): - return self.runner(plan) + def run(self, plan, runner=None): + return self.runner(plan, **({"runner": runner} if runner is not None else {})) def check_output(self, path, plan): """Fail closed unless the run left a usable output artifact at `path`.""" @@ -122,10 +124,12 @@ def _validate_classification(parameters): def _validate_music(parameters): - if "caption" not in parameters or set(parameters) - {"caption", "lyrics", "duration", "steps", "seed"}: + allowed = {"caption", "lyrics", "duration", "steps", "seed", "bpm", "time_signature", "reference"} + if "caption" not in parameters or set(parameters) - allowed: raise _invalid("Music parameters need a caption and supported generation settings.") return validate_music(parameters["caption"], parameters.get("lyrics", "[instrumental]"), - parameters.get("duration", 15.0), parameters.get("steps", 30), parameters.get("seed", 42)) + parameters.get("duration", 15.0), parameters.get("steps", 30), parameters.get("seed", 42), + parameters.get("bpm"), parameters.get("time_signature"), parameters.get("reference")) def _validate_transcribe(parameters): @@ -164,10 +168,16 @@ def _validate_image_understanding(parameters): def _validate_video_generation(parameters): - _require_keys(parameters, ("prompt",), ("width", "height", "frames", "steps", "seed", "fps"), + _require_keys(parameters, ("prompt",), ("width", "height", "frames", "steps", "seed", "fps", "denoiser_cache", "cache_memory_mib"), "Video-generation parameters need prompt and supported options.") _require_string(parameters, "prompt") - _require_integer(parameters, "width", "height", "frames", "steps", "seed") + _require_integer(parameters, "width", "height", "frames", "steps", "seed", "cache_memory_mib") + if "cache_memory_mib" in parameters and not 8 <= parameters["cache_memory_mib"] <= 4096: + raise TaskError("invalid_parameters", "cache_memory_mib must be 8..4096.") + if "denoiser_cache" in parameters: + _require_string(parameters, "denoiser_cache") + if parameters["denoiser_cache"] not in ("off", "adaptive"): + raise TaskError("invalid_parameters", "denoiser_cache must be off or adaptive.") _require_finite(parameters, "fps") return parameters @@ -182,6 +192,27 @@ def _validate_video_understanding(parameters): return parameters +def _validate_mesh(parameters): + _require_keys(parameters, ("image_path",), ("steps", "seed", "resolution", "guidance", "max_faces", "denoiser_cache", "cache_memory_mib"), + "Mesh-generation parameters need image_path and supported generation settings.") + _require_absolute(parameters, "image_path") + _require_integer(parameters, "steps", "seed", "resolution", "max_faces", "cache_memory_mib") + if 'cache_memory_mib' in parameters and not 8 <= parameters['cache_memory_mib'] <= 4096: + raise TaskError('invalid_parameters', 'cache_memory_mib must be 8..4096.') + if 'denoiser_cache' in parameters: + _require_string(parameters, 'denoiser_cache') + if parameters['denoiser_cache'] not in ('off','adaptive'): + raise TaskError('invalid_parameters', 'denoiser_cache must be off or adaptive.') + _require_finite(parameters, "guidance") + return parameters + + +def _plan_embedding(model, parameters, output, media, directory): + path = directory / "embedding.json" + write_json(path, parameters) + return plan_embed(model, str(path)) + + def _plan_classification(model, parameters, output, media, directory): path = directory / "decision.json" write_json(path, parameters) @@ -190,7 +221,9 @@ def _plan_classification(model, parameters, output, media, directory): def _plan_music(model, parameters, output, media, directory): return plan_music(model, parameters["caption"], parameters["lyrics"], output, - duration=parameters["duration"], steps=parameters["steps"], seed=parameters["seed"]) + duration=parameters["duration"], steps=parameters["steps"], seed=parameters["seed"], + bpm=parameters.get("bpm"), time_signature=parameters.get("time_signature"), + reference=parameters.get("reference")) def _plan_transcribe(model, parameters, output, media, directory): @@ -212,7 +245,7 @@ def _plan_image_understanding(model, parameters, output, media, directory): def _plan_video_generation(model, parameters, output, media, directory): return plan_video(model, parameters["prompt"], output, - **_options(parameters, ("width", "height", "frames", "fps", "steps", "seed"))) + **_options(parameters, ("width", "height", "frames", "fps", "steps", "seed", "denoiser_cache", "cache_memory_mib"))) def _plan_video_understanding(model, parameters, output, media, directory): @@ -220,6 +253,17 @@ def _plan_video_understanding(model, parameters, output, media, directory): **_options(parameters, ("fps", "max_tokens", "temperature", "max_pixels"))) +def _plan_mesh(model, parameters, output, media, directory): + return plan_mesh(model, media, output, **_options(parameters, ("steps", "seed", "resolution", "guidance", "max_faces", "denoiser_cache", "cache_memory_mib"))) + + +def _check_mesh_output(path, plan): + try: + validate_glb(path) + except MeshError as error: + raise TaskError("invalid_mesh_output", str(error), error.remediation) from error + + def _wav_check(activity): def check(path, plan): try: @@ -267,22 +311,25 @@ def check(path, plan, runner=subprocess.run): KINDS: Dict[str, TaskKind] = {kind.name: kind for kind in ( + TaskKind("embedding", "embed/1", False, validate_embedding, _plan_embedding, lambda plan, **options: run_embed(plan, **options)), TaskKind("classification", "decide/1", True, _validate_classification, _plan_classification, - lambda plan: run_decide(plan)), - TaskKind("music_generation", "music/1", True, _validate_music, _plan_music, lambda plan: run_music(plan), + lambda plan, **options: run_decide(plan, **options)), + TaskKind("music_generation", "music/1", True, _validate_music, _plan_music, lambda plan, **options: run_music(plan, **options), output="output.wav", output_check=_wav_check("Music generation")), TaskKind("transcribe", "transcribe/1", False, _validate_transcribe, _plan_transcribe, - lambda plan: run_transcribe(plan), input_field="audio_path", input_media="audio"), - TaskKind("speak", "speak/1", False, _validate_speak, _plan_speak, lambda plan: run_speak(plan), + lambda plan, **options: run_transcribe(plan, **options), input_field="audio_path", input_media="audio"), + TaskKind("speak", "speak/1", False, _validate_speak, _plan_speak, lambda plan, **options: run_speak(plan, **options), output="output.wav", output_check=_wav_check("Speech synthesis")), TaskKind("image_generation", "generate/1", False, _validate_image_generation, _plan_image_generation, - lambda plan: run_generate(plan), output="output.png", output_check=lambda path, plan: check_png(path, plan)), + lambda plan, **options: run_generate(plan, **options), output="output.png", output_check=lambda path, plan: check_png(path, plan)), TaskKind("image_understanding", "describe/1", False, _validate_image_understanding, _plan_image_understanding, - lambda plan: run_describe(plan), input_field="image_path", input_media="image"), + lambda plan, **options: run_describe(plan, **options), input_field="image_path", input_media="image"), TaskKind("video_generation", "video/1", False, _validate_video_generation, _plan_video_generation, - lambda plan: run_video(plan), output="output.mp4", output_check=lambda path, plan: check_mp4(path, plan)), + lambda plan, **options: run_video(plan, **options), output="output.mp4", output_check=lambda path, plan: check_mp4(path, plan)), TaskKind("video_understanding", "describe/1", False, _validate_video_understanding, _plan_video_understanding, - lambda plan: run_describe(plan), input_field="video_path", input_media="video"), + lambda plan, **options: run_describe(plan, **options), input_field="video_path", input_media="video"), + TaskKind("mesh_generation", "mesh/1", False, _validate_mesh, _plan_mesh, lambda plan, **options: run_mesh(plan, **options), + input_field="image_path", input_media="image", output="output.glb", output_check=_check_mesh_output), )} diff --git a/packages/codex/mlx-agent/src/mlx_agent/task_serve.py b/packages/codex/mlx-agent/src/mlx_agent/task_serve.py new file mode 100644 index 0000000..d67267c --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/task_serve.py @@ -0,0 +1,218 @@ +"""Loopback HTTP interface for typed model jobs and model residency controls.""" +import argparse +import base64 +import json +import hashlib +import os +from pathlib import Path +import signal +import struct +import sys +import threading +import time + +if __package__ in (None, ''): + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from mlx_agent.jit_serve import GatewayError, GatewayHandler, GatewayServer, MAX_BODY, model_aliases +from mlx_agent.task_contracts import TaskError +from mlx_agent.task_runtime import task_result +from mlx_agent.task_serving import TaskModelWorker +from mlx_agent import task_kinds + +EMBEDDING_BATCH = 128 +EMBEDDING_FIELDS = frozenset(('model', 'input', 'encoding_format', 'dimensions', 'user')) +SYSTEMONE_FIELDS = frozenset(('model', 'state', 'questions')) + + +class TaskHandler(GatewayHandler): + def _settled(self, identifier, failure, message): + """The result of a submitted job once it has settled; the caller holds the job lock.""" + controller = self.server.controller + # The job settles its record before releasing the model. + with controller.condition: + controller.condition.wait_for(lambda: controller.active_requests == 0) + record = controller.record(identifier) + if record['state'] != 'succeeded': + error = record.get('error') or {} + raise GatewayError(503, error.get('code', failure), error.get('message', message)) + outcome = task_result(identifier, controller.store.root) + result = outcome['result'] + if result is None: + result = json.loads(Path(outcome['artifact']['path']).read_bytes()) + return result + + def _systemone(self, body): + """TypeSafe System One decisions: typed questions about one state, answered synchronously.""" + config = self.server.config + if 'classification' not in config['task_kinds']: + raise GatewayError(404, 'not_found', 'This endpoint does not serve decisions.') + if set(body) - SYSTEMONE_FIELDS: + raise GatewayError(400, 'invalid_request', 'Decisions take a model, a state and questions.') + if not isinstance(body.get('model'), str) or body['model'] not in model_aliases(config): + raise GatewayError(404, 'model_not_found', 'This endpoint serves a different model.') + started = time.monotonic() + with self.server.job_lock: + identifier = self.server.controller.submit({'kind': 'classification', 'parameters': { + 'state': body.get('state'), 'questions': body.get('questions')}})['id'] + result = self._settled(identifier, 'decision_failed', 'The decision job did not finish.') + return {'model': body['model'], 'answers': result['answers'], 'usage': result.get('usage'), + 'latency_ms': round((time.monotonic() - started) * 1000, 1)} + + def _embeddings(self, body): + config, controller = self.server.config, self.server.controller + if 'embedding' not in config['task_kinds']: + raise GatewayError(404, 'not_found', 'This endpoint does not serve text embeddings.') + texts = [body.get('input')] if isinstance(body.get('input'), str) else body.get('input') + dimensions = body.get('dimensions') + if (set(body) - EMBEDDING_FIELDS or not isinstance(texts, list) or not texts + or any(not isinstance(text, str) for text in texts) + or body.get('encoding_format', 'float') not in ('float', 'base64') + or dimensions is not None and (type(dimensions) is not int or dimensions < 1)): + raise GatewayError(400, 'invalid_request', 'Embeddings take text input with float or base64 encoding.') + if not isinstance(body.get('model'), str) or body['model'] not in model_aliases(config): + raise GatewayError(404, 'model_not_found', 'This endpoint serves a different model.') + vectors = [] + with self.server.job_lock: + for start in range(0, len(texts), EMBEDDING_BATCH): + identifier = controller.submit({'kind': 'embedding', 'parameters': { + 'input': texts[start:start + EMBEDDING_BATCH], 'max_length': 8192}})['id'] + result = self._settled(identifier, 'embedding_failed', 'The embedding job did not finish.') + vectors.extend(result['embeddings']) + if dimensions is not None and dimensions != len(vectors[0]): + raise GatewayError(400, 'unsupported_dimensions', + 'This model returns {0}-dimensional embeddings.'.format(len(vectors[0]))) + encode = body.get('encoding_format') == 'base64' + return {'object': 'list', 'model': body['model'], 'data': [{'object': 'embedding', 'index': index, + 'embedding': base64.b64encode(struct.pack('<%df' % len(vector), *vector)).decode() if encode else vector} + for index, vector in enumerate(vectors)]} + + def _artifact(self, identifier, name): + record = self.server.controller.record(identifier) + outcome = task_result(identifier, self.server.controller.store.root) + if name == 'result': + reference, filename, content_type = outcome['artifact'], 'result.json', 'application/json' + elif name == 'output' and task_kinds.get(record['kind']).output: + result = outcome['result'] + if result is None: + result = json.loads(Path(outcome['artifact']['path']).read_bytes()) + reference = result['output_artifact'] + filename = task_kinds.get(record['kind']).output + content_type = {'.wav': 'audio/wav', '.png': 'image/png', '.mp4': 'video/mp4', '.glb': 'model/gltf-binary'}[Path(filename).suffix] + else: + raise GatewayError(404, 'not_found', 'No artifact with that name.') + path = self.server.controller.store.artifact_path(identifier, filename) + descriptor = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0)) + with os.fdopen(descriptor, 'rb') as stream: + digest = hashlib.sha256() + size = 0 + for chunk in iter(lambda: stream.read(65536), b''): + digest.update(chunk) + size += len(chunk) + if size != reference['bytes'] or digest.hexdigest() != reference['sha256']: + raise TaskError('artifact_changed', 'The saved task artifact changed.') + stream.seek(0) + self.send_response(200) + self.send_header('Content-Type', content_type) + self.send_header('Content-Length', str(size)) + self.send_header('Connection', 'close') + self.end_headers() + self.close_connection = True + for chunk in iter(lambda: stream.read(65536), b''): + self.wfile.write(chunk) + + def do_GET(self): + try: + self._guard(control=self.path == '/_mlx/status') + controller = self.server.controller + if self.path == '/_mlx/status': + self._json(200, controller.status()) + elif self.path == '/v1/models': + self._json(200, {'object': 'list', 'data': [{'id': self.server.config['model'], 'object': 'model', + 'task_kinds': self.server.config['task_kinds'], 'api': '/v1/tasks'}]}) + elif self.path.startswith('/v1/tasks/'): + parts = self.path.split('/') + identifier = parts[3] + controller.record(identifier) + if len(parts) == 4: + self._json(200, controller.record(identifier)) + elif len(parts) == 6 and parts[4] == 'artifacts': + self._artifact(identifier, parts[5]) + elif len(parts) == 5 and parts[4] == 'result': + self._json(200, task_result(identifier, controller.store.root)) + else: + raise GatewayError(404, 'not_found', 'Unknown task endpoint.') + else: + raise GatewayError(404, 'not_found', 'Unknown endpoint.') + except (GatewayError, TaskError) as error: + self._error(error if isinstance(error, GatewayError) else GatewayError(404, error.code, str(error))) + + def do_POST(self): + try: + self._guard(control=self.path in ('/_mlx/unload', '/_mlx/policy', '/_mlx/cache')) + if self.headers.get('Transfer-Encoding'): + raise GatewayError(400, 'invalid_body', 'Use a bounded Content-Length request.') + try: + length = int(self.headers.get('Content-Length', '0')) + if not 0 <= length <= 1024 * 1024: + raise ValueError() + body = json.loads(self.rfile.read(length)) if length else {} + if not isinstance(body, dict): + raise ValueError() + except (ValueError, UnicodeError): + raise GatewayError(400, 'invalid_body', 'Expected a JSON object of at most 1 MiB.') from None + if self._dispatch_control(body): + return + controller = self.server.controller + if self.path == '/v1/tasks': + self._json(202, controller.submit(body)) + elif self.path == '/v1/embeddings': + self._json(200, self._embeddings(body)) + elif self.path == '/v1/systemone': + self._json(200, self._systemone(body)) + elif self.path.startswith('/v1/tasks/') and self.path.endswith('/cancel'): + parts = self.path.split('/') + if len(parts) != 5 or body: + raise GatewayError(400, 'invalid_request', 'Cancel requires an empty object and a task ID.') + controller.record(parts[3]) + self._json(200, controller.store.request_cancel(parts[3])) + else: + raise GatewayError(404, 'not_found', 'Unknown inference endpoint.') + except (GatewayError, TaskError) as error: + self._error(error if isinstance(error, GatewayError) else GatewayError(400, error.code, str(error))) + except OSError: + self._error(GatewayError(503, 'task_unavailable', 'The local model job could not be started.')) + + +class TaskServer(GatewayServer): + def __init__(self, address, config): + super().__init__(address, config) + self.RequestHandlerClass = TaskHandler + self.controller = TaskModelWorker(config) + self.job_lock = threading.Lock() + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--model', required=True) + parser.add_argument('--port', type=int, required=True) + parser.add_argument('--config', required=True) + args = parser.parse_args() + path = Path(args.config) + if path.is_symlink(): + raise ValueError('Refusing a symbolic-link endpoint configuration.') + config = json.loads(path.read_text()) + if args.model != config['model'] or args.port != config['port']: + raise ValueError('Endpoint configuration identity changed.') + server = TaskServer(('127.0.0.1', args.port), config) + for sig in (signal.SIGINT, signal.SIGTERM): + signal.signal(sig, lambda *_: threading.Thread(target=server.shutdown, daemon=True).start()) + try: + server.serve_forever() + finally: + server.controller.close() + server.server_close() + + +if __name__ == '__main__': + main() diff --git a/packages/codex/mlx-agent/src/mlx_agent/task_serving.py b/packages/codex/mlx-agent/src/mlx_agent/task_serving.py new file mode 100644 index 0000000..6b0116b --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/task_serving.py @@ -0,0 +1,541 @@ +"""Capability-bound serving plans and durable inference over a resident backend.""" +import json +import math +import hashlib +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import threading + +from . import task_kinds +from .backends import backend_environment, backend_python, load_manifests, load_registries, lookup, normalize_type +from .compute import ComputeBusy, ComputeLease, process_identity +from . import allocator_cache +from .inference_runner import InferenceError +from .identity_pass import recheck_bound_identity +from .jit_serve import GatewayError, ModelWorker, model_fingerprint +from .memory_policy import (PolicyRejected, TASK_CONTEXT, execution_wait_seconds, reject_task_context, + validate as validate_memory_policy) +from .resident_runner import ResidentRunner +from .residency import MemoryAdmissionError +from .task_contracts import TaskError, validate_request +from .task_identity import capture_identity, check_identity +from .task_runtime import _artifact_reference, _error, _finish, task_result, task_status +from .task_store import TaskStore + +def runtime_fingerprint(backend): + source = Path(__file__).parent + from .resident_worker import RUNNERS + files = [source / (name + '.py') for name in sorted(RUNNERS)] + files += [source / name for name in ('resident_worker.py', 'runner_model_cache.py','worker_telemetry.py','allocator_cache.py')] + files += sorted((source / 'resources' / 'ports' / backend).rglob('*.py')) + digest = hashlib.sha256() + for path in files: + digest.update(str(path.relative_to(source)).encode()) + digest.update(hashlib.sha256(path.read_bytes()).digest()) + return digest.hexdigest() + + +def _trellis_component_budget(model_path, kind, plan, telemetry, *, warm): + """Return selected cold checkpoint bytes and missing warm checkpoint bytes.""" + if kind != 'mesh_generation': + return None + path = Path(model_path) + config = json.loads((path / 'config.json').read_text()) + if config.get('model_type') != 'trellis2': + return None + from importlib import import_module + components = import_module('mlx_agent.resources.ports.mlx-3d.trellis2.components') + argv = plan['argv'] + resolution = int(argv[argv.index('--resolution') + 1]) + names = components.required_components(config, resolution) + sizes = components.checkpoint_bytes(path, names) + if not warm: + return sum(sizes.values()), 0 + resident = None if not isinstance(telemetry, dict) else telemetry.get('components') + if resident is None: + from .memory_policy import _weight_bytes + missing = _weight_bytes(path) + else: + from .worker_telemetry import validate + validate(telemetry) + missing = sum(size for name, size in sizes.items() if name not in resident['resident']) + return sum(sizes.values()), math.ceil(missing * 1.10) + + +TASKS = {'speech_to_text': ['transcribe'], 'text_to_speech': ['speak'], 'embedding': ['embedding'], + 'classification': ['classification'], 'music_generation': ['music_generation'], + 'image_generation': ['image_generation'], 'video_generation': ['video_generation'], + 'mesh_generation': ['mesh_generation']} + + +def resolve_model(path, manifests=None, registries=None, root=None, capture=True): + from .serve import ServeError + from .taxonomy import classify + manifests = load_manifests() if manifests is None else manifests + registries = load_registries(manifests, root) if registries is None else registries + if path is None: + raise ServeError("model_not_local", "Select an existing local model.", "Serving never downloads models.") + local = Path(path).expanduser().resolve() + try: + config_path = local / 'config.json' + if config_path.stat().st_size > 1024 * 1024: + raise ValueError('config too large') + config = json.loads(config_path.read_text()) + name = local.name + ' ' + str(config.get('_name_or_path', '')) + if local.parent.name == 'snapshots': + name += ' ' + local.parent.parent.name + task = classify(name, model_type=config.get('model_type'), config_keys=config.keys(), + manifests=manifests, registries=registries, local=True) + task_type = task['type'] + if (local / 'modules.json').is_file() and task_type == 'text_llm': + task_type = 'embedding' + hits = [hit for hit in lookup(config.get('model_type'), manifests, registries) if hit['category'] == task_type] + if task_type not in TASKS or not hits: + raise ValueError('No vetted task adapter implements this model type.') + if task_type == 'embedding': + from .embed import TEXT_MODELS + if normalize_type(config.get('model_type')) not in TEXT_MODELS: + raise ValueError('No vetted text embedding adapter implements this architecture.') + manifest = manifests[sorted(hits, key=lambda hit: hit['backend'])[0]['backend']] + if not manifest['builtin'] and not registries.get(manifest['id'], {}).get('installed'): + raise ServeError('runtime_not_installed', 'The model backend is not installed.', 'Install ' + manifest['id'] + ' first.') + executable = str(backend_python(manifest, root)) + evidence = capture_identity(local, manifest, Path(executable)) if capture else None + return TASKS[task_type], executable, evidence + except (OSError, ValueError, TypeError, AttributeError) as error: + raise ServeError('unsupported_runtime', str(error), 'Select a supported local model with an installed backend.') from error + + +def plan_start(repo, path, port, receipts_dir, hf_cache, memory_policy): + from .convert import cached_snapshot + from .serve import ServeError, _preview_hash, receipts_root + has_repo, has_path = isinstance(repo, str) and bool(repo.strip()), isinstance(path, str) and bool(path.strip()) + if has_repo == has_path: + raise ServeError('invalid_arguments', 'Select exactly one local path or cached repository.', 'Use --path or --repo.') + if has_repo and '/' not in repo: + raise ServeError('invalid_repo', 'A repository ID must be publisher/model.', 'Select an existing cached repository.') + local = Path(path).expanduser() if path else cached_snapshot(repo, hf_cache) if repo else None + if local is None or not local.is_dir(): + raise ServeError('model_not_local', 'Task serving needs existing local model files.', 'Select a local model; serving never downloads weights.') + local = local.resolve() + kinds, executable, identity = resolve_model(local) + port = 8085 if port is None else port + if type(port) is not int or not 1 <= port <= 65535: + raise ServeError('invalid_arguments', 'Port must be between 1 and 65535.', 'Choose a valid loopback port.') + try: + policy = validate_memory_policy({'release_after_request': True} if memory_policy is None else memory_policy) + if policy.get('context_tokens') is not None: + raise ValueError(TASK_CONTEXT) + except ValueError as error: + raise ServeError('invalid_arguments', str(error), 'Review the memory policy.') from error + root = receipts_root(receipts_dir).absolute() + config = str(root / '{}.jit-config.json'.format(port)) + model = repo or str(local) + plan = {'repo': repo, 'path': str(local), 'runtime': 'tasks', 'port': port, 'max_tokens': 0, 'adapter_path': None, + 'jit': True, 'local_path': str(local), 'fingerprint': model_fingerprint(local), 'task_identity': identity, + 'task_kinds': kinds, 'task_runtime_fingerprint': runtime_fingerprint(identity['backend']), 'memory_policy': policy, 'control_config': config, 'bind': '127.0.0.1', + 'worker_argv': [executable, str(Path(__file__).with_name('resident_worker.py')), '--model', str(local), '--port', str(port)], + 'argv': [sys.executable, str(Path(__file__).with_name('task_serve.py')), '--model', model, '--port', str(port), '--config', config], + 'readiness': 'http://127.0.0.1:{}/v1/models'.format(port)} + plan['preview_hash'] = _preview_hash(plan) + return plan + + +class TaskModelWorker(ModelWorker): + def __init__(self, config): + super().__init__(config) + self.store = TaskStore(config['task_state_dir']) + self.resident = ResidentRunner(config['worker_argv'][0], config['local_path'], + environment=dict(backend_environment(), HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', HF_DATASETS_OFFLINE='1'), + log_path=config.get('log_path'), port=config['port']) + self.job_thread = None + + def _recheck_identity(self): + from .serve import ServeError + try: + recheck_bound_identity(self.config) + except ServeError as error: + raise TaskError(error.code, str(error), error.remediation) from error + + def _allocator_cache_status(self): + desired = allocator_cache.from_memory(self.memory_policy) + state = self.resident.cache_state or {} + applied = state.get('applied_policy') + pending = (allocator_cache.requested(desired) if applied is None else applied != desired) + return {'supported': True, 'available': state.get('available'), + 'policy_fields': sorted(allocator_cache.FIELDS), 'reclaim_modes': list(allocator_cache.MODES), + 'control_path': '/_mlx/cache', 'configured_policy': desired, 'applied_policy': applied, + 'pending': pending or bool(state.get('error')), 'active': self.cache_control_active, + 'last_reclaim': state.get('last_reclaim'), 'error': state.get('error')} + + def configure(self, changes): + try: + reject_task_context(changes) + except PolicyRejected as error: + raise GatewayError(400, error.code, str(error)) from error + try: + desired = validate_memory_policy(dict(self.memory_policy, **changes)) + except (ValueError, TypeError) as error: + raise GatewayError(400, 'invalid_policy', str(error)) from error + if (self.resident.loaded and (self.resident.cache_state or {}).get('available') is False + and allocator_cache.requested(desired)): + raise GatewayError(400, 'cache_control_unavailable', 'This worker does not expose allocator cache controls.') + super().configure(changes) + if self._allocator_cache_status()['pending']: + self._cache_operation(None) + return self.status() + + def _control_cache_in_lease(self, lease, desired, reason): + """Run cache control on the owned worker under an existing compute lease.""" + try: + lease.bind_process_group(self.resident.process.pid) + success = self.resident.control_cache(desired, reclaim=reason) + lease.release_idle_process_group(self.resident.process.pid, self.resident.idle_members()) + except (OSError, ValueError, subprocess.SubprocessError): + self._stop_worker() + with self.condition: + self.model_state = 'unloaded' + raise + return success, self._settle_task_memory() + + def _cache_operation(self, reason, manual=False, expected=None): + with self.condition: + if (self.closed or self.active_requests or self.cache_control_active + or self.model_state != 'loaded' or not self.resident.loaded): + if manual: + raise GatewayError(409, 'model_busy', 'Cache reclaim requires an idle loaded worker.') + return False + if expected is not None and expected != (self.process, self.activity_revision, self.policy_revision): + return False + self.cache_control_active = True + desired = allocator_cache.from_memory(self.memory_policy) + if reason is None and desired['cache_reclaim'] == 'idle': + reason = 'policy' + try: + with ComputeLease('cache:' + self.config['local_path'], self.config.get('compute_state_dir')) as lease: + success, settled = self._control_cache_in_lease(lease, desired, reason) + if success and settled: + self.last_error = None + if not success: + self.last_error = (self.resident.cache_state or {}).get('error') or 'Allocator cache control is unavailable.' + if manual: + raise GatewayError(503, 'cache_control_unavailable', self.last_error) + return False + return True + except ComputeBusy as error: + if manual: + raise GatewayError(503, 'compute_busy', str(error)) from error + return False + except (OSError, ValueError, subprocess.SubprocessError) as error: + with self.condition: + self.process = self.resident.process + self.model_state = 'failed' if self.process else 'unloaded' + self.execution_unresolved = self.process is not None + self.last_error = str(error) + if self.process is None: + self._release_memory() + if manual: + raise GatewayError(503, 'cache_control_failed', str(error)) from error + return False + finally: + with self.condition: + self.cache_control_active = False + self.condition.notify_all() + + def reclaim_cache(self): + self._cache_operation('manual', manual=True) + return self.status() + + def unload_if_idle(self): + with self.condition: + state = self._allocator_cache_status() + if (self.model_state == 'loaded' and not self.active_requests and not self.cache_control_active + and not state['error']): + pending = state['pending'] + pressure = (state['available'] and self.memory_policy.get('cache_reclaim') == 'pressure' + and (self.worker_memory or {}).get('cache_bytes', 0)) + expected = (self.process, self.activity_revision, self.policy_revision) + reserve = self.memory_policy['minimum_headroom_gb'] + else: + pending = pressure = False + if pending: + return self._cache_operation(None, expected=expected) + if pressure: + available = self.memory_probe() + if type(available) is int and available < reserve * 1e9: + if self._cache_operation('pressure', expected=expected): + return True + return super().unload_if_idle() + + def _stop_worker(self): + try: + self.resident.close() + self.execution_unresolved = False + self._release_memory() + finally: + with self.condition: + self.process = self.resident.process + self.worker_argv = list(self.process.args) if self.process is not None else None + + def _settle_task_memory(self): + memory = self.resident.telemetry + self.worker_memory = memory + resident = None + if memory['active_bytes'] is not None and memory['cache_bytes'] is not None: + resident = memory['active_bytes'] + memory['cache_bytes'] + if memory['peak_bytes'] is not None: + self.workspace_bytes = max(self.workspace_bytes,memory['peak_bytes']-memory['active_bytes']) + try: + self.memory_reservation = self.memory_registry.settle(self.memory_token,resident_bytes=resident,telemetry=memory) + except MemoryAdmissionError as error: + if error.code != 'memory_registry_busy': + raise + self.last_error = 'Memory reservation remains pending: ' + str(error) + return False + self.memory_materialized = True + return True + + def submit(self, body): + if set(body) != {'kind', 'parameters'} or body['kind'] not in self.config['task_kinds']: + raise GatewayError(400, 'unsupported_task', 'Use a kind advertised by this model endpoint and its parameters.') + kind = task_kinds.get(body['kind']) + request = validate_request({'schema': kind.request_schema, 'kind': kind.name, + 'model_path': self.config['local_path'], 'parameters': body['parameters']}) + with self.condition: + if self.closed or self.active_requests or self.cache_control_active or self.execution_unresolved or self.model_state == 'unloading': + raise GatewayError(409, 'model_busy', 'Finish the active model job before starting another.') + self.active_requests = 1 + self.activity_revision += 1 + staged = None + record = None + try: + self._recheck_identity() + if kind.input_media: + staged = self.store.stage_input(request['parameters'][kind.input_field], kind.input_media) + with tempfile.TemporaryDirectory(prefix='mlx-task-endpoint-plan-') as directory: + plan = kind.plan(request, Path(directory), staged['staging_path'] if staged else None) + if plan['backend'] != self.config['task_identity']['backend'] or plan['argv'][0] != self.resident.executable: + raise TaskError('identity_changed', 'The model task backend changed; review serving again.') + record = self.store.create(request, self.config['task_identity'], + input_artifact=staged['reference'] if staged else None, staged_input=staged) + staged = None + owner = process_identity(os.getpid()) + if not owner: + raise TaskError('task_identity_unavailable', 'Cannot establish the serving process identity.') + record = self.store.transition(record['id'], ('starting',), {'supervisor': {'pid': os.getpid(), 'identity': owner}}) + self.job_thread = threading.Thread(target=self._execute, args=(record['id'],), daemon=True) + self.job_thread.start() + return record + except BaseException as error: + unresolved = False + try: + try: + self._stop_worker() + except (OSError, subprocess.SubprocessError): + unresolved = True + error = TaskError('task_stop_unconfirmed', 'The owned model worker has not stopped safely.') + with self.condition: + self.model_state = 'failed' if unresolved else 'unloaded' + self.last_error = str(error) + self._persist() + if record is not None: + _finish(self.store, record['id'], 'failed', error=_error(error), execution_unresolved=unresolved) + if staged: + self.store.discard_staged_input(staged) + finally: + self.release() + raise error + + def _admit_task_memory(self, request, plan, budget_gb, lease, check_cancelled): + """Retry complete admission once after an opted-in idle cache reclaim.""" + for attempt in range(2): + try: + component_budget = _trellis_component_budget(self.config['local_path'], request['kind'], plan, + self.resident.telemetry if self.resident.loaded else None, warm=self.resident.loaded) + if self.resident.loaded: + self._reserve_workspace(0 if component_budget is None else component_budget[1]) + else: + self._check_memory(weight_bytes=None if component_budget is None else component_budget[0]) + try: + return self.memory_registry.reserve_execution(self.memory_token, + None if budget_gb is None else math.ceil(budget_gb * 1e9), self.memory_probe) + except MemoryAdmissionError as error: + self._record_memory_failure('task_admission', error.code, error.details) + raise GatewayError(503, error.code, str(error)) from error + except GatewayError as error: + if attempt or error.code not in ('insufficient_headroom', 'agent_memory_budget_exceeded', 'job_memory_cap_exceeded'): + raise + with self.condition: + desired = allocator_cache.from_memory(self.memory_policy) + cache = self.resident.cache_state or {} + memory = self.resident.telemetry or {} + eligible = (not self.closed and self.active_requests == 1 and not self.cache_control_active + and self.model_state == 'loaded' and self.resident.loaded and self.resident.process is not None + and desired['cache_reclaim'] == 'pressure' and cache.get('available') is True + and type(memory.get('cache_bytes')) is int and memory['cache_bytes'] > 0) + if eligible: + self.cache_control_active = True + if not eligible: + raise + try: + check_cancelled() + success, settled = self._control_cache_in_lease(lease, desired, 'pressure') + if not success: + raise error + if not settled: + raise GatewayError(503, 'memory_registry_busy', 'Memory reservation remains pending after cache reclaim.') + check_cancelled() + self._recheck_identity() + finally: + with self.condition: + self.cache_control_active = False + self.condition.notify_all() + + def _execute(self, identifier): + lease = None + leased = False + dispatched = False + cancelled_before_dispatch = False + try: + with self.condition: + self.memory_guard_error = None + budget_gb = self.memory_policy.get('model_memory_budget_gb') + lease = ComputeLease("task:" + identifier, self.config.get('compute_state_dir'), + shared=budget_gb is not None and self.memory_registry.shared_execution_enabled()) + lease.enter_wait(execution_wait_seconds(self.memory_policy), + cancelled=lambda: self.closed or self.store.get(identifier)['cancel_requested']) + leased = True + record = self.store.get(identifier) + if record['cancel_requested'] or self.closed: + cancelled_before_dispatch = True + raise InterruptedError('Inference cancelled.') + self._recheck_identity() + check_identity(record['identity']) + request = self.store.read_request(identifier) + kind = task_kinds.get(request['kind']) + directory = self.store.artifact_path(identifier, 'result.json').parent + media = str(self.store.verify_input_artifact(identifier, record['input_artifact'], kind.input_media)) if kind.input_media else None + plan = kind.plan(request, directory, media) + if plan['backend'] != record['identity']['backend'] or plan['argv'][0] != self.resident.executable: + raise TaskError('identity_changed', 'The model task backend changed.') + def check_cancelled(): + nonlocal cancelled_before_dispatch + if self.closed or self.store.get(identifier)['cancel_requested']: + cancelled_before_dispatch = True + raise InterruptedError('Inference cancelled.') + capacity = self._admit_task_memory(request, plan, budget_gb, lease, check_cancelled) + check_cancelled() + worker_limit = None if capacity is None else max(1, capacity - 512_000_000) + with self.condition: + if self.closed: + raise InterruptedError('Endpoint stopping.') + self.model_state = 'loading' if not self.resident.loaded else 'loaded' + if self.resident.process is None: + self._launching_memory() + self.resident._start(cancelled=lambda: self.closed or self.store.get(identifier)['cancel_requested']) + with self.condition: + if self.closed: + raise InterruptedError('Endpoint stopping.') + self.process = self.resident.process + self.worker_argv = list(self.process.args) + self._persist() + lease.bind_process_group(self.process.pid) + worker_identity = process_identity(self.process.pid) + if not worker_identity: + raise TaskError('task_identity_unavailable', 'Cannot establish the model worker identity.') + if not self.memory_materialized: + self._bind_memory(self.process, worker_identity) + self.store.transition(identifier, ('starting',), {'state': 'running', 'execution': {'pid': self.process.pid, 'identity': worker_identity}}) + dispatched = True + result = kind.run(plan, runner=lambda argv, **options: self.resident.run(argv, + cancelled=lambda: self.closed or self.store.get(identifier)['cancel_requested'], + cache_policy=allocator_cache.from_memory(self.memory_policy), memory_limit_bytes=worker_limit, **options)) + self._recheck_identity() + check_identity(record['identity']) + self.store.read_request(identifier) + if kind.input_media: + result['input_artifact'] = record['input_artifact'] + if kind.output: + output = self.store.artifact_path(identifier, kind.output) + kind.check_output(output, plan) + result['output_artifact'] = _artifact_reference(output) + if self.store.get(identifier)['cancel_requested']: + raise InterruptedError('Inference cancelled.') + reference = self.store.write_result(identifier, result) + desired = allocator_cache.from_memory(self.memory_policy) + if self.resident.cache_state and self.resident.cache_state['applied_policy'] != desired: + self.resident.control_cache(desired, reclaim='policy' if desired['cache_reclaim'] == 'idle' else None) + # The protocol acknowledges completion before retaining idle weights. + lease.release_idle_process_group(self.process.pid, self.resident.idle_members()) + memory_settled = self._settle_task_memory() + with self.condition: + self.model_state = 'loaded' if self.resident.loaded else 'unloaded' + self.last_error = None if memory_settled else self.last_error + self._persist() + _finish(self.store, identifier, 'succeeded', result=reference, error=None) + except BaseException as error: + unresolved = False + admission_denied = cancelled_before_dispatch or (isinstance(error, (ComputeBusy, InterruptedError)) and not leased) + admission_denied |= (not dispatched and isinstance(error,GatewayError) + and error.code in ('insufficient_headroom','memory_unknown','memory_registry_busy', 'agent_memory_budget_exceeded', 'job_memory_cap_exceeded')) + if admission_denied and leased and self.memory_reservation is not None: + if self.resident.process is None: + self._release_memory() + elif self.memory_materialized: + try: + self.memory_reservation = self.memory_registry.settle(self.memory_token) + except MemoryAdmissionError as settle_error: + if settle_error.code == 'memory_registry_busy': + error = GatewayError(503, 'memory_registry_busy', + 'Memory reservation remains pending: ' + str(settle_error)) + else: + admission_denied = False + error = GatewayError(503, settle_error.code, str(settle_error)) + # No work was dispatched when admission was denied or cancelled here. Keep the + # existing idle worker and its state available for the next request. + if not admission_denied: + try: + self._stop_worker() + except (OSError, subprocess.SubprocessError): + unresolved = True + if isinstance(error, ComputeBusy): + error = TaskError('compute_busy', str(error), 'Wait for the current host model operation to finish, then start a new job.') + if unresolved: + error = TaskError('task_stop_unconfirmed', 'The owned model worker has not stopped safely.', 'Inspect the worker and retry the owned endpoint stop; its identity is retained.') + if not unresolved and self.memory_guard_error is not None: + error = GatewayError(503, *self.memory_guard_error) + cancelled = self.store.get(identifier)['cancel_requested'] + if isinstance(error, InterruptedError) and not cancelled: + error = TaskError('endpoint_stopped', 'The model endpoint stopped during inference.', + 'Inspect its status, then restart the endpoint before starting a new job.') + with self.condition: + if not admission_denied: + self.model_state = 'failed' if unresolved else 'unloaded' + self.last_error = str(error) + self._persist() + _finish(self.store, identifier, 'cancelled' if cancelled and not unresolved else 'failed', + error=None if cancelled and not unresolved else _error(error), execution_unresolved=unresolved) + finally: + with self.condition: + self.memory_guard_error = None + if leased: + lease.__exit__(None, None, None) + self.release() + + def _halt(self): + with self.condition: + self.closed = True + if self.job_thread: + self.job_thread.join(timeout=10) + if self.job_thread and self.job_thread.is_alive(): + raise OSError('The owned model job is still stopping.') + super()._halt() + + def record(self, identifier): + record = task_status(identifier, self.store.root) + if record['model_path'] != self.config['local_path'] or record['kind'] not in self.config['task_kinds']: + raise TaskError('task_not_found', 'This endpoint does not own that model job.') + return record diff --git a/packages/codex/mlx-agent/src/mlx_agent/taxonomy.py b/packages/codex/mlx-agent/src/mlx_agent/taxonomy.py index 265c65f..f570915 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/taxonomy.py +++ b/packages/codex/mlx-agent/src/mlx_agent/taxonomy.py @@ -15,7 +15,7 @@ TASK_TYPES = ( "text_llm", "vision_language", "speech_to_text", "text_to_speech", - "embedding", "classification", "image_generation", "video_generation", "mesh_generation", "music_generation", "speculative_draft", "other", + "embedding", "classification", "image_generation", "video_generation", "mesh_generation", "music_generation", "speculative_draft", "vision_projector", "other", ) # Ordered specific-first; the last entry is the type's default use case. USE_CASES = { @@ -30,6 +30,7 @@ "mesh_generation": ("mesh_generation",), "music_generation": ("music_generation",), "speculative_draft": ("speculative_decoding",), + "vision_projector": (), "other": (), } PIPELINE_TYPES = { @@ -101,6 +102,8 @@ def use_cases_for(task_type, haystack): def _type_from_hits(hits, config_keys, haystack, vision_module=False, allow_vision=True): preferred = [hit for hit in hits if hit["match"] != "remap"] or hits categories = {hit["category"] for hit in preferred} + if "embedding" in categories and (not categories & {"text_llm", "vision_language"} or _EMBEDDING_NAME.search(haystack)): + return "embedding" if "music_generation" in categories: return "music_generation" if "text_llm" in categories and categories & {"speech_to_text", "text_to_speech"}: @@ -147,6 +150,8 @@ def _type_from_name(haystack): def _task_type(haystack, pipeline_tag, model_type, config_keys, gguf_architecture, manifests, registries, local, draft=False): + if gguf_architecture and squash_type(gguf_architecture) in _GGUF_PROJECTOR_ARCHITECTURES: + return "vision_projector", "gguf_metadata", "confirmed" # A drafter is tagged like its target (text-generation) but cannot run alone. if draft or gguf_architecture and squash_type(gguf_architecture) in DRAFT_ARCHITECTURES: return "speculative_draft", "gguf_architecture", "confirmed" @@ -222,10 +227,15 @@ def annotate_inventory(report, manifests=None, registries=None): if registries is None: registries = load_registries(manifests) for item in report.get("models", []): - item["task"] = classify( + if (item.get("identity") or {}).get("artifact_kind") == "mmproj": + item["task"] = {"type": "vision_projector", "use_cases": [], "source": "gguf_metadata", "confidence": "confirmed"} + continue + item["task"] = ({"type": "vision_projector", "use_cases": [], "source": "name", "confidence": "likely"} + if item.get("companion") and str(item.get("architecture") or "").lower() not in _GGUF_PROJECTOR_ARCHITECTURES + and (item.get("identity") or {}).get("artifact_kind") != "mmproj" else classify( item.get("name"), gguf_architecture=item.get("architecture"), manifests=manifests, registries=registries, local=True, draft=item.get("draft") is not None, - ) + )) for output in report.get("outputs", []): model_type, keys = read_config_type(output.get("path", "")) name = _output_name(output) diff --git a/packages/codex/mlx-agent/src/mlx_agent/transactions.py b/packages/codex/mlx-agent/src/mlx_agent/transactions.py index e90d517..794bbe5 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/transactions.py +++ b/packages/codex/mlx-agent/src/mlx_agent/transactions.py @@ -384,7 +384,8 @@ def _read_legacy_migration_state(lock_root): return {"version": LEGACY_LOCK_MIGRATION, "targets": {}, "parents": {}, "unscoped": False} if not stat.S_ISREG(os.fstat(descriptor).st_mode): raise ValueError("legacy lock migration marker is not a regular file") - value = json.loads(os.read(descriptor, 1048576).decode("utf-8")) + with os.fdopen(descriptor, "r", encoding="utf-8", closefd=False) as source: + value = json.load(source) # The prior release-candidate marker had no target map. Treat it as # an unscoped barrier: it cannot prove which physical parents migrated. if value == {"version": LEGACY_LOCK_MIGRATION}: @@ -864,7 +865,13 @@ def from_dict(cls, value, receipt_path=""): validations_redacted = False if isinstance(value["validations"], dict): try: - validations_redacted = json.loads(redact_secrets(json.dumps(value["validations"]))) == value["validations"] + # Declared target paths are labels, not credential field names. + # Check their values and all other validation metadata for secrets. + probe = { + "artifacts": [{"path": name, "result": checks} for name, checks in value["validations"].items() if name in targets], + "metadata": {name: checks for name, checks in value["validations"].items() if name not in targets}, + } + validations_redacted = json.loads(redact_secrets(json.dumps(probe))) == probe except (TypeError, ValueError, json.JSONDecodeError): validations_redacted = False if not isinstance(value["validations"], dict) or not validations_redacted or not isinstance(value["preview"], str) or len(value["preview"]) > MAX_PREVIEW_CHARS + 32 or redact_secrets(value["preview"]) != value["preview"] or not isinstance(value["preview_hash"], str) or not _HASH.fullmatch(value["preview_hash"]): diff --git a/packages/codex/mlx-agent/src/mlx_agent/transcribe_runner.py b/packages/codex/mlx-agent/src/mlx_agent/transcribe_runner.py index 194e9ef..e793124 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/transcribe_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/transcribe_runner.py @@ -6,6 +6,11 @@ import sys import time +if __package__: + from .runner_model_cache import load_model as retained_load +else: + from runner_model_cache import load_model as retained_load + def _restore_whisper_end_token(model): """Give a Whisper tokenizer the no-speech token its vocabulary has. @@ -46,7 +51,7 @@ def main(argv=None): from mlx_audio.stt.utils import load_audio, load_model started = time.time() - model = load_model(arguments.model) + model = retained_load(load_model, arguments.model) _restore_whisper_end_token(model) samples = load_audio(arguments.audio) kwargs = {} diff --git a/packages/codex/mlx-agent/src/mlx_agent/video.py b/packages/codex/mlx-agent/src/mlx_agent/video.py index b4bf0a3..0cbf7bf 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/video.py +++ b/packages/codex/mlx-agent/src/mlx_agent/video.py @@ -14,6 +14,7 @@ lookup, ) from .inference_runner import InferenceError, RunnerContract, invoke +from .media_settings import supports_adaptive_reuse VIDEO_SCHEMA = "video/1" VIDEO_RUNNER = Path(__file__).resolve().with_name("video_runner.py") @@ -52,7 +53,8 @@ def _config_int(config, key, default): def plan_video(model_path, prompt, out, width=DEFAULT_WIDTH, height=DEFAULT_HEIGHT, frames=DEFAULT_FRAMES, - fps=None, steps=None, seed=42, manifests=None, registries=None, root=None): + fps=None, steps=None, seed=42, manifests=None, registries=None, root=None, + denoiser_cache="off", cache_memory_mib=256): """Pick the video backend for a converted model directory; pure apart from reading config.json. The size alignment, the frame rule, the area cap, and the step and rate defaults come from the @@ -101,6 +103,12 @@ def plan_video(model_path, prompt, out, width=DEFAULT_WIDTH, height=DEFAULT_HEIG raise _invalid("--steps must be 1..100.", "Pass --steps 30, for example.") if not _is_int(seed) or not 0 <= seed < 2 ** 32: raise _invalid("--seed must be 0..4294967295.", "Pass --seed 42, for example.") + if denoiser_cache not in ("off", "adaptive"): + raise _invalid("--denoiser-cache must be off or adaptive.", "Pass --denoiser-cache adaptive to enable residual reuse.") + if not _is_int(cache_memory_mib) or not 8 <= cache_memory_mib <= 4096: + raise _invalid("--cache-memory-mib must be 8..4096.", "Pass --cache-memory-mib 256, for example.") + if denoiser_cache == "adaptive" and not supports_adaptive_reuse(config, "video_generation"): + raise _invalid("Adaptive denoiser caching requires single-model Wan2.1 T2V.", "Use --denoiser-cache off for this model.") model_type = config.get("model_type") manifests = load_manifests() if manifests is None else manifests registries = load_registries(manifests, root) if registries is None else registries @@ -124,6 +132,8 @@ def plan_video(model_path, prompt, out, width=DEFAULT_WIDTH, height=DEFAULT_HEIG "--prompt=" + prompt, "--out", str(target), "--width", str(width), "--height", str(height), "--frames", str(frames), "--fps", str(fps), "--steps", str(steps), "--seed", str(seed), ] + if denoiser_cache == "adaptive": + argv.extend(["--denoiser-cache", denoiser_cache, "--cache-memory-mib", str(cache_memory_mib)]) return { "backend": manifest["id"], "model": str(model), "out": str(target), "width": width, "height": height, "frames": frames, "fps": fps, "steps": steps, "seed": seed, "argv": argv, @@ -144,5 +154,8 @@ def run_video(plan, manifests=None, root=None, timeout=DEFAULT_TIMEOUT_SECONDS, "path", "width", "height", "frames", "fps", "duration_seconds", "steps", "seed", "seconds", "load_seconds", "seconds_per_frame", "peak_memory_gb", "pixel_std", ) - return dict({"schema": VIDEO_SCHEMA, "backend": plan["backend"], "model": plan["model"]}, - **{key: result.get(key) for key in keys}) + output = dict({"schema": VIDEO_SCHEMA, "backend": plan["backend"], "model": plan["model"]}, + **{key: result.get(key) for key in keys}) + if "denoiser_cache" in result: + output["denoiser_cache"] = result["denoiser_cache"] + return output diff --git a/packages/codex/mlx-agent/src/mlx_agent/video_runner.py b/packages/codex/mlx-agent/src/mlx_agent/video_runner.py index 72e6caa..67627c2 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/video_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/video_runner.py @@ -6,6 +6,11 @@ import sys import time +if __package__: + from .runner_model_cache import load_model, enabled +else: + from runner_model_cache import load_model, enabled + def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) @@ -19,15 +24,20 @@ def main(argv=None): parser.add_argument("--fps", type=int, required=True) parser.add_argument("--steps", type=int, required=True) parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--denoiser-cache", choices=("off", "adaptive"), default="off") + parser.add_argument("--cache-memory-mib", type=int, default=256) arguments = parser.parse_args(argv) port = importlib.import_module(arguments.module) started = time.time() - model = port.load(arguments.model) + model = load_model(port.load, arguments.model) + model.retain_weights = enabled() open_seconds = time.time() - started result = port.generate( model, arguments.prompt, arguments.out, width=arguments.width, height=arguments.height, frames=arguments.frames, fps=arguments.fps, steps=arguments.steps, seed=arguments.seed, + **({"denoiser_cache": arguments.denoiser_cache, "cache_memory_mib": arguments.cache_memory_mib} + if arguments.denoiser_cache != "off" else {}), ) result["load_seconds"] = round(float(result.get("load_seconds", 0.0)) + open_seconds, 3) print(json.dumps(result), flush=True) diff --git a/packages/codex/mlx-agent/src/mlx_agent/worker_telemetry.py b/packages/codex/mlx-agent/src/mlx_agent/worker_telemetry.py new file mode 100644 index 0000000..e7a8fee --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/worker_telemetry.py @@ -0,0 +1,51 @@ +"""Versioned optional allocator telemetry; never import an inference runtime.""" +import math +import sys +import time + + +def validate(value): + fields={'schema','active_bytes','cache_bytes','peak_bytes','loads','cache_hits','load_seconds','captured_at'} + if not isinstance(value,dict) or set(value) not in (fields, fields | {'components'}) or value['schema']!='worker-memory/1': + raise ValueError('Invalid worker memory telemetry.') + for name in ('active_bytes','cache_bytes','peak_bytes','loads','cache_hits'): + item=value[name] + if item is None and name.endswith('_bytes'):continue + if type(item) is not int or not 0<=item<=2**60: + raise ValueError('Invalid worker allocation counter.') + for name in ('load_seconds','captured_at'): + seconds=value[name] + if type(seconds) not in (int,float) or not math.isfinite(seconds) or seconds<0: + raise ValueError('Invalid worker telemetry time.') + if 'components' in value: + from importlib import import_module + names = import_module('mlx_agent.resources.ports.mlx-3d.trellis2.components').NAMES + component = value['components'] + if not isinstance(component, dict) or set(component) != {'schema', 'resident', 'loads', 'load_seconds', 'checkpoint_bytes'} or component['schema'] != 'resident-components/1': + raise ValueError('Invalid resident component telemetry.') + resident = component['resident'] + if not isinstance(resident, list) or any(not isinstance(name, str) or name not in names for name in resident) or len(set(resident)) != len(resident): + raise ValueError('Invalid resident components.') + for field in ('loads', 'load_seconds', 'checkpoint_bytes'): + values = component[field] + if not isinstance(values, dict) or set(values) != set(resident): + raise ValueError('Invalid resident component counters.') + for item in values.values(): + if field == 'load_seconds': + if type(item) not in (int, float) or not math.isfinite(item) or item < 0: + raise ValueError('Invalid component load time.') + elif type(item) is not int or not 0 <= item <= 2**60: + raise ValueError('Invalid component counter.') + return value + + +def capture(statistics): + core=sys.modules.get('mlx.core') + result={'schema':'worker-memory/1','captured_at':time.time(),**statistics} + for field,method in (('active_bytes','get_active_memory'),('cache_bytes','get_cache_memory'),('peak_bytes','get_peak_memory')): + function=getattr(core,method,None) + try: + result[field]=function() if callable(function) else None + except (RuntimeError,NotImplementedError): + result[field]=None + return validate(result) diff --git a/packages/codex/mlx-agent/src/mlx_agent/worker_transport.py b/packages/codex/mlx-agent/src/mlx_agent/worker_transport.py new file mode 100644 index 0000000..d923f3b --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/worker_transport.py @@ -0,0 +1,66 @@ +"""How a reviewed serving plan reaches its model worker. + +The interface is `choose`: one of inherited Unix, loopback key, resident task, +or an open worker. `gateway_config` is that plan's worker config, shared by +the supervised start and the foreground protected endpoint. +""" +from pathlib import Path +from typing import Protocol + +from .serving_plan import worker_config + + +class WorkerTransport(Protocol): + name: str + + def mark(self, plan) -> None: + """Record this transport on the plan. Must not copy the endpoint key.""" + + +class _InheritedUnix: + name = "inherited-unix" + + def mark(self, plan): + from .private_serve import identity + plan["private_worker"] = identity() + + +class _LoopbackKey: + name = "loopback-key" + + def mark(self, plan): + """The endpoint key stays off the worker. The worker gets its own digest at launch.""" + return plan + + +class _ResidentTask: + name = "resident" + + def mark(self, plan): + """A task worker has no private HTTP port. Gateway auth is the whole transport.""" + return plan + + +class _OpenWorker: + name = "open" + + def mark(self, plan): + return plan + + +def choose(plan): + """Return the transport for a plan that already carries its endpoint digest, if any.""" + if plan.get("api_key_sha256") is None: + return _OpenWorker() + if plan.get("runtime") == "tasks": + return _ResidentTask() + if (plan.get("runtime") == "mlx_lm" and Path(plan["worker_argv"][0]).name == "mlx_lm.server" + and not any(plan.get(key) for key in ("prefill_kernel", "decode_profile", "vision_profile"))): + return _InheritedUnix() + return _LoopbackKey() + + +def gateway_config(plan, *, control_token, state_path, log_path=None, config_path=None, task_state_dir=None): + """Worker config for a reviewed plan. The key set lives on the serving plan.""" + return worker_config(plan, control_token=control_token, state_path=state_path, log_path=log_path, + config_path=config_path, task_state_dir=task_state_dir) diff --git a/packages/codex/mlx-agent/src/mlx_agent/workflow_activation.py b/packages/codex/mlx-agent/src/mlx_agent/workflow_activation.py new file mode 100644 index 0000000..666914b --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/workflow_activation.py @@ -0,0 +1,255 @@ +"""Identity-bound activation of reviewed local serving workflows.""" +import json +import os +from pathlib import Path +import uuid + +from . import workflow_sets +from .serve import (SERVE_RECEIPT_KIND, SERVE_RECEIPT_SCHEMA_VERSION, + _argv_matches, _jit_control, _pid_alive, _pid_command, _pid_start, + receipts_root, start_serve, stop_serve, _default_port_free) +from .transactions import _atomic_in_directory, _target_locks + +SCHEMA = 'serving-workflow-activation/1' + + +def _path(name, root): + workflow_sets._name(name) + return receipts_root(root) / 'workflow-activations' / (name + '.json') + + +def _read(path): + value = workflow_sets._private_json(path) + if (value.get('schema') != SCHEMA or value.get('state') not in ('active', 'partial', 'stopped') + or not isinstance(value.get('members'), dict) or len(value['members']) > 32 + or not isinstance(value.get('definition_hash'), str) or not isinstance(value.get('preview_hash'), str) + or not isinstance(value.get('activation_id'), str) or value.get('name') != path.stem): + raise ValueError('Invalid workflow activation receipt.') + for role, row in value['members'].items(): + workflow_sets._name(role) + if (not isinstance(row, dict) or row.get('role') != role + or row.get('ownership') not in ('created', 'reused') + or row.get('state') not in ('launching', 'launch_failed', 'active', 'stopped') + or type(row.get('port')) is not int or not 1 <= row['port'] <= 65535 + or not isinstance(row.get('member_plan_hash'), str)): + raise ValueError('Invalid workflow activation member.') + return value + + +def _write(path, value): + data = (json.dumps(value, sort_keys=True, allow_nan=False) + '\n').encode() + if len(data) > workflow_sets.MAX_BYTES: + raise ValueError('Workflow activation receipt is too large.') + _atomic_in_directory(path.parent, path.name, data, 0o600) + + +def _owned_receipt(member, root): + port, pid, start = member['port'], member['pid'], member['process_started_at'] + if type(pid) is not int or pid <= 0 or not isinstance(start, str) or not start: + raise ValueError('Service process identity is unavailable.') + receipt = workflow_sets._private_json(receipts_root(root) / (str(port) + '.json')) + if (receipt.get('kind') != SERVE_RECEIPT_KIND or receipt.get('schema_version') != SERVE_RECEIPT_SCHEMA_VERSION + or receipt.get('port') != port or not receipt.get('jit') + or receipt.get('pid') != pid or receipt.get('process_started_at') != start + or receipt.get('preview_hash') != member['member_plan_hash'] + or not _pid_alive(pid) or _pid_start(pid) != start or not _argv_matches(receipt, _pid_command(pid))): + raise ValueError('Service process identity changed.') + return receipt + + +def _service_status(member, root, expected_plan=None): + receipt = _owned_receipt(member, root) + state = _jit_control(receipt, receipts_root(root), 'status') + if expected_plan is not None and (state.get('memory_policy') != expected_plan.get('memory_policy') + or state.get('api_key_sha256') != expected_plan.get('api_key_sha256')): + raise ValueError('Live service policy or credential identity changed.') + return {'endpoint_state': 'available', 'model_state': state['model_state'], + 'active_requests': state.get('active_requests')} + + +def _member_identity(role, plan, receipt, ownership): + if receipt.get('runtime') != plan['runtime'] or receipt.get('task_kinds', []) != plan.get('task_kinds', []): + raise ValueError('Service capabilities differ from the reviewed plan.') + return {'role': role, 'port': receipt['port'], 'pid': receipt['pid'], + 'process_started_at': receipt.get('process_started_at'), + 'member_plan_hash': plan['preview_hash'], 'ownership': ownership, 'state': 'active', + 'runtime': plan['runtime'], 'model_id': plan.get('repo') or plan.get('path'), + 'task_kinds': plan.get('task_kinds', []), 'credential_ref': plan.get('access_key_file')} + + +def _repeat_activation(value, name, preview_hash, root): + if value['state'] != 'active': + raise ValueError('A workflow activation still owns or references services.') + definition = workflow_sets.load_workflow(name, root) + if workflow_sets._hash(definition) != value.get('definition_hash') or set(definition['members']) != set(value['members']): + raise ValueError('Active workflow definition changed.') + if value.get('preview_hash') != preview_hash: + current = workflow_sets.preview_workflow(definition, receipts_dir=root) + if current['preview_hash'] != preview_hash or any(row['action'] != 'reuse' for row in current['members'].values()): + raise ValueError('Workflow preview changed; review it again.') + for role, row in current['members'].items(): + candidate = row['candidate'] + member = value['members'][role] + if candidate['pid'] != member.get('pid') or candidate['process_started_at'] != member.get('process_started_at'): + raise ValueError('Active workflow service identity changed: ' + role) + for role, definition_member in definition['members'].items(): + member = value['members'][role] + plan = workflow_sets._member_plan(definition_member, root) + if plan['preview_hash'] != member.get('member_plan_hash'): + raise ValueError('Active workflow member plan changed: ' + role) + candidate = workflow_sets._reuse_candidate(receipts_root(root), plan) + if candidate['pid'] != member.get('pid') or candidate['process_started_at'] != member.get('process_started_at'): + raise ValueError('Active workflow service identity changed: ' + role) + _service_status(member, root, plan) + return value + + +def start_workflow(name, preview_hash, *, receipts_dir=None): + path = _path(name, receipts_dir) + with _target_locks([path], create_parents=True): + if os.path.lexists(path): + previous = _read(path) + if previous['state'] != 'stopped': + return _repeat_activation(previous, name, preview_hash, receipts_dir) + definition = workflow_sets.load_workflow(name, receipts_dir) + preview = workflow_sets.preview_workflow(definition, receipts_dir=receipts_dir) + if preview_hash != preview['preview_hash']: + raise ValueError('Workflow preview changed; review it again.') + if any(row['action'] == 'blocked' for row in preview['members'].values()): + raise ValueError('A workflow member is blocked.') + for role, row in preview['members'].items(): + if row['action'] == 'start' and not _default_port_free(definition['members'][role]['port']): + raise ValueError('Workflow port is already occupied: ' + role) + result = {'schema': SCHEMA, 'name': name, 'activation_id': str(uuid.uuid4()), + 'definition_hash': preview['definition_hash'], 'preview_hash': preview_hash, + 'state': 'partial', 'members': {}, 'resource_forecast': preview['resource_forecast']} + _write(path, result) + try: + for role, member in sorted(definition['members'].items()): + reviewed = preview['members'][role] + plan = workflow_sets._member_plan(member, receipts_dir) + if plan['preview_hash'] != reviewed['member_plan_hash']: + raise ValueError('Member plan changed after review: ' + role) + if reviewed['action'] == 'reuse': + candidate = workflow_sets._reuse_candidate(receipts_root(receipts_dir), plan) + if candidate != reviewed['candidate']: + raise ValueError('Reused service identity changed: ' + role) + child = workflow_sets._private_json(Path(candidate['receipt'])) + item = _member_identity(role, plan, child, 'reused') + _service_status(item, receipts_dir, plan) + else: + # Mark in-flight before launch: an interruption must not silently discard ownership uncertainty. + result['members'][role] = {'role': role, 'port': member['port'], 'ownership': 'created', + 'state': 'launching', 'member_plan_hash': plan['preview_hash']} + _write(path, result) + outcome = start_serve(plan, receipts_dir=receipts_dir, confirm=True, preview_hash=plan['preview_hash']) + item = _member_identity(role, plan, outcome['receipt'], 'created') + result['members'][role] = item + _write(path, result) + if not item['process_started_at']: + raise ValueError('Service start identity is unavailable: ' + role) + result['state'] = 'active' + except (OSError, ValueError, TypeError, KeyError, RuntimeError) as error: + if getattr(error, 'code', None) == 'port_in_use' and result['members'].get(role, {}).get('state') == 'launching': + result['members'][role]['state'] = 'launch_failed' + result['members'][role]['error'] = str(error) + for item in result['members'].values(): + if item.get('ownership') == 'created' and item.get('state') == 'active': + item['cleanup_required'] = 'Endpoint retained; use workflow stop to clean up.' + elif item.get('state') == 'launching': + item['cleanup_required'] = 'Launch ownership is unresolved; inspect the service receipt.' + # No atomic idle-stop exists. Preserve created endpoints, even apparently idle ones. + result['error'] = str(error) + _write(path, result) + return result + _write(path, result) + return result + + +def status_workflow(name, *, receipts_dir=None): + value = _read(_path(name, receipts_dir)) + result = dict(value, recorded_state=value['state'], members={}) + for role, member in value['members'].items(): + item = dict(member) + try: + if member['state'] == 'stopped': + item.update(endpoint_state='stopped', model_state='unknown') + else: + item.update(_service_status(member, receipts_dir)) + except (OSError, ValueError, TypeError, KeyError, RuntimeError) as error: + item.update(endpoint_state='unknown', model_state='unknown', error=str(error)) + result['members'][role] = item + if value['state'] == 'active' and any( + item.get('endpoint_state') != 'available' for item in result['members'].values()): + result['state'] = 'partial' + return result + + +def resolve_workflow_role(name, role, *, receipts_dir=None): + workflow_sets._name(role) + value = _read(_path(name, receipts_dir)) + if value['state'] == 'stopped': + raise ValueError('Workflow activation is stopped.') + member = value['members'].get(role) + if not isinstance(member, dict) or member.get('state') != 'active': + raise ValueError('Workflow role is missing or not active.') + receipt = _owned_receipt(member, receipts_dir) + runtime, model, kinds = member.get('runtime'), member.get('model_id'), member.get('task_kinds') + credential = member.get('credential_ref') + if (runtime not in ('tasks', 'mlx_lm', 'mlx-vlm', 'strata', 'splash') + or not isinstance(model, str) or not model or not isinstance(kinds, list) + or any(not isinstance(kind, str) for kind in kinds) + or (credential is not None and (not isinstance(credential, str) or not Path(credential).is_absolute()))): + raise ValueError('Workflow role metadata is unavailable.') + if (receipt.get('runtime') != runtime or (receipt.get('repo') or receipt.get('path')) != model + or receipt.get('task_kinds', []) != kinds): + raise ValueError('Workflow role capability identity changed.') + config = workflow_sets._private_json(receipts_root(receipts_dir) / (str(member['port']) + '.jit-config.json')) + if (config.get('runtime') != runtime or config.get('model') != model + or config.get('task_kinds', []) != kinds or config.get('access_key_file') != credential + or config.get('api_key_sha256') != receipt.get('api_key_sha256')): + raise ValueError('Workflow role configuration changed.') + state = _jit_control(receipt, receipts_root(receipts_dir), 'status') + if state.get('api_key_sha256') != receipt.get('api_key_sha256'): + raise ValueError('Workflow role credential identity changed.') + if runtime == 'tasks': + operations = [{'method': method, 'path': path} for method, path in ( + ('POST', '/v1/tasks'), ('GET', '/v1/tasks/{id}'), ('GET', '/v1/tasks/{id}/result'), + ('GET', '/v1/tasks/{id}/artifacts/{name}'), ('POST', '/v1/tasks/{id}/cancel'))] + if 'embedding' in kinds: + operations.append({'method': 'POST', 'path': '/v1/embeddings'}) + else: + operations = [{'method': 'POST', 'path': path} for path in ( + '/v1/chat/completions', '/v1/messages', '/v1/responses')] + operations.append({'method': 'GET', 'path': '/v1/responses/{id}'}) + operations.append({'method': 'GET', 'path': '/v1/models'}) + origin = 'http://127.0.0.1:' + str(member['port']) + return {'schema': 'serving-workflow-role/1', 'workflow': name, 'activation_id': value['activation_id'], + 'workflow_state': value['state'], 'role': role, 'runtime': runtime, 'origin': origin, + 'base_url': origin + '/v1', 'model_id': model, 'operations': operations, + 'task_kinds': kinds, 'credential_ref': credential, 'model_state': state['model_state'], + 'endpoint_identity': {'pid': member['pid'], 'process_started_at': member['process_started_at'], + 'member_plan_hash': member['member_plan_hash']}} + + +def stop_workflow(name, *, receipts_dir=None): + path = _path(name, receipts_dir) + with _target_locks([path]): + result = _read(path) + for role, member in result['members'].items(): + if member.get('ownership') != 'created' or member.get('state') in ('stopped', 'launch_failed'): + continue + try: + _owned_receipt(member, receipts_dir) + stop_serve(member['port'], receipts_dir, expected_pid=member['pid'], + expected_start=member['process_started_at']) + member['state'] = 'stopped' + member.pop('error', None) + except (OSError, ValueError, TypeError, KeyError, RuntimeError) as error: + member['error'] = str(error) + _write(path, result) + pending = any(row.get('ownership') == 'created' and row.get('state') not in ('stopped', 'launch_failed') + for row in result['members'].values()) + result['state'] = 'partial' if pending else 'stopped' + _write(path, result) + return result diff --git a/packages/codex/mlx-agent/src/mlx_agent/workflow_sets.py b/packages/codex/mlx-agent/src/mlx_agent/workflow_sets.py new file mode 100644 index 0000000..a952c83 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/workflow_sets.py @@ -0,0 +1,355 @@ +"""Private workflow definitions and advisory, non-activating previews.""" +import hashlib +import json +import math +import os +from pathlib import Path +import re +import stat +from subprocess import SubprocessError +import time + +from .convert import cached_snapshot +from .jit_serve import available_memory_bytes +from .memory_policy import policy_from_profile, reservation, validate as validate_policy, enforce_launch, model_key as _model_key +from .residency import MemoryRegistry, SCHEMA as REGISTRY_SCHEMA +from .compute import process_identity +from .memory_budget import same_identity +from .serve import (SERVE_RECEIPT_KIND, SERVE_RECEIPT_SCHEMA_VERSION, load_recipes, plan_start, receipts_root, resolve_serve_runtime, + _argv_matches, _pid_alive, _pid_command, _pid_start) +from .serve_profiles import load_profile +from .transactions import _atomic_in_directory, _target_locks, _walk_directory +from .wiring import _MODEL + +SCHEMA = 'serving-workflow/1' +MAX_BYTES = 65536 +_NAME = re.compile(r'[a-z][a-z0-9_-]{0,63}\Z') + + +def _name(value): + if not isinstance(value, str) or not _NAME.fullmatch(value): + raise ValueError('Invalid workflow or role name.') + return value + + +def validate_workflow(value): + if not isinstance(value, dict) or set(value) != {'schema', 'name', 'members'} or value['schema'] != SCHEMA: + raise ValueError('Invalid workflow definition.') + _name(value['name']) + members = value['members'] + if not isinstance(members, dict) or not 1 <= len(members) <= 32: + raise ValueError('A workflow requires between 1 and 32 members.') + ports = set() + for role, member in members.items(): + _name(role) + required = {'runtime', 'port', 'profile'} + if not isinstance(member, dict) or not required <= set(member) or set(member) - required - {'path', 'repo', 'api_key_file'}: + raise ValueError('Invalid workflow member fields.') + if ('path' in member) == ('repo' in member): + raise ValueError('Select exactly one model path or cached repo.') + for field in ('path', 'repo', 'api_key_file'): + if field in member and (not isinstance(member[field], str) or not member[field] or len(member[field]) > 4096): + raise ValueError('Invalid workflow member reference.') + if 'repo' in member and not _MODEL.fullmatch(member['repo']): + raise ValueError('Invalid cached model repository.') + if member['runtime'] not in ('auto', 'mlx_lm', 'mlx-vlm', 'strata', 'splash', 'tasks'): + raise ValueError('Invalid workflow runtime.') + if member['runtime'] == 'strata' and 'repo' in member: + raise ValueError('Strata requires a local path.') + _name(member['profile']) + port = member['port'] + if type(port) is not int or not 1 <= port <= 65535 or port in ports: + raise ValueError('Workflow ports must be distinct valid ports.') + ports.add(port) + try: + if len(json.dumps(value, allow_nan=False).encode()) > MAX_BYTES: + raise ValueError('Workflow definition is too large.') + except (TypeError, OverflowError) as error: + raise ValueError('Invalid workflow definition.') from error + return value + + +def _path(name, root): + return receipts_root(root) / 'workflows' / (_name(name) + '.json') + + +def load_workflow(name, root=None): + path = _path(name, root) + _, directory = _walk_directory(path.parent) + try: + fd = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) + with os.fdopen(fd, 'rb') as stream: + info = os.fstat(stream.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_nlink != 1 or info.st_size > MAX_BYTES: + raise ValueError('Invalid workflow file.') + value = validate_workflow(json.loads(stream.read(MAX_BYTES + 1))) + if value['name'] != name: + raise ValueError('Workflow name does not match its file.') + return value + finally: + os.close(directory) + + +def save_workflow(name, value, root=None): + path = _path(name, root) + value = validate_workflow(value) + if value['name'] != name: + raise ValueError('Workflow name does not match the save name.') + with _target_locks([path.parent / '.workflows'], create_parents=True): + if os.path.lexists(path): + raise ValueError('Workflow already exists.') + if len(list_workflows(root)) >= 100: + raise ValueError('Too many workflows.') + _atomic_in_directory(path.parent, path.name, (json.dumps(value, sort_keys=True) + '\n').encode(), 0o600) + return value + + +def list_workflows(root=None): + path = _path('unused', root).parent + if not path.exists() and not path.is_symlink(): + return {} + _, fd = _walk_directory(path) + try: + names = sorted(name[:-5] for name in os.listdir(fd) if name.endswith('.json')) + if len(names) > 100: + raise ValueError('Too many workflows.') + return {name: load_workflow(name, root) for name in names} + finally: + os.close(fd) + + +def delete_workflow(name, root=None): + path = _path(name, root) + with _target_locks([path.parent / '.workflows']): + load_workflow(name, root) + _, fd = _walk_directory(path.parent) + try: + os.unlink(path.name, dir_fd=fd) + os.fsync(fd) + finally: + os.close(fd) + + +def _member_plan(member, root): + repo, path = member.get('repo'), member.get('path') + if repo is not None and cached_snapshot(repo) is None: + raise ValueError('Model repository is not cached locally.') + profile = load_profile(member['profile'], root) + recipes = load_recipes() + runtime, executable = resolve_serve_runtime(repo, path, member['runtime'], recipes) + if runtime != 'strata' and ('strata_context_tokens' in profile or 'strata_decoding' in profile): + raise ValueError('Strata profile requires a Strata runtime.') + policy = validate_policy(policy_from_profile(profile)) + if runtime != 'tasks': + enforce_launch(policy, runtime, True) + return plan_start(repo, runtime, recipes, port=member['port'], path=path, jit=True, + receipts_dir=root, runtime_executable=executable, memory_policy=policy, + api_key_file=member.get('api_key_file'), + strata_context_tokens=profile.get('strata_context_tokens'), + strata_decoding=profile.get('strata_decoding')) + + +def _hash(value): + return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest() + + +def _private_json(path): + _, directory = _walk_directory(path.parent) + try: + fd = os.open(path.name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) + with os.fdopen(fd, 'rb') as stream: + info = os.fstat(stream.fileno()) + if (not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077 + or info.st_nlink != 1 or info.st_size > 1024 * 1024): + raise ValueError('Unsafe service sidecar.') + value = json.loads(stream.read(1024 * 1024 + 1)) + if not isinstance(value, dict): + raise ValueError('Invalid service sidecar.') + return value + finally: + os.close(directory) + + +def _reuse_candidate(root, plan): + port = plan['port'] + receipt = _private_json(root / (str(port) + '.json')) + config = _private_json(root / (str(port) + '.jit-config.json')) + try: + state = _private_json(root / (str(port) + '.jit-state.json')) + except FileNotFoundError: + state = None + pid = receipt.get('pid') + if type(pid) is not int or pid <= 0 or not _pid_alive(pid): + raise ValueError('Service gateway identity is unavailable.') + start, command = _pid_start(pid), _pid_command(pid) + if (not start or receipt.get('process_started_at') != start or not _argv_matches(receipt, command) + or (state is not None and state.get('gateway_pid') != pid)): + raise ValueError('Service gateway identity does not match its receipt and state.') + if (receipt.get('kind') != SERVE_RECEIPT_KIND or receipt.get('schema_version') != SERVE_RECEIPT_SCHEMA_VERSION + or receipt.get('preview_hash') != plan['preview_hash'] or receipt.get('port') != port + or receipt.get('runtime') != plan['runtime'] or not receipt.get('jit')): + raise ValueError('Service receipt does not match the reviewed member plan.') + for field in ('local_path', 'fingerprint', 'runtime', 'worker_argv', 'memory_policy'): + if config.get(field) != plan.get(field): + raise ValueError('Persisted service configuration differs: ' + field) + if config.get('api_key_sha256') != plan.get('api_key_sha256'): + raise ValueError('Persisted service credential identity differs.') + return {'pid': pid, 'process_started_at': start, 'receipt': str(root / (str(port) + '.json')), + 'receipt_preview_hash': receipt['preview_hash'], 'memory_policy': config['memory_policy']} + + + +def _resource_forecast(members, inspection, available, root): + """Project only identity-qualified reservations; unknowns stay unknown.""" + def valid(value): + return type(value) is int and 0 <= value <= 2**60 + result = {'status':'unknown', 'reason':'Insufficient reliable accounting for a joint estimate.', + 'captured_at':time.time(), 'members':{}, 'estimates':{'incremental_bytes':None, + 'available_bytes':available if valid(available) else None, 'agent_budget':inspection.get('agent_budget')}} + try: + if inspection.get('state') not in ('ok','uninitialized') or inspection.get('errors'): + raise ValueError('Memory registry inspection is uncertain.') + entries = inspection.get('entries') + if not isinstance(entries, dict): raise ValueError('Memory registry entries are unavailable.') + MemoryRegistry._validate({'schema': REGISTRY_SCHEMA, 'entries': entries}) + budget = inspection.get('agent_budget') + if budget is not None: + if not isinstance(budget,dict) or any(not valid(budget.get(k)) for k in ('accounted_bytes','admission_bytes')): + raise ValueError('Shared budget accounting is unavailable.') + if entries and (any(not valid(budget.get(k)) for k in ('pending_bytes','resident_bytes','external_bytes','overhead_bytes','observed_bytes','limit_bytes','reserve_bytes')) + or not isinstance(budget.get('allocations'),dict)): + raise ValueError('Shared budget allocations are unavailable.') + if entries and any(not isinstance(budget['allocations'].get(key),dict) or any( + not valid(budget['allocations'][key].get(field)) for field in ('resident_bytes','pending_bytes','observed_bytes')) + for key in entries): + raise ValueError('Shared budget allocation is invalid.') + baseline = budget.get('pending_bytes', 0) + if not valid(baseline): raise ValueError('Shared pending allocation is invalid.') + else: + baseline = sum(row['reserved_bytes'] for row in entries.values()) + floors = [row['headroom_bytes'] for row in entries.values()] + total = 0 + cap_failure = None + for role, member in members.items(): + plan, estimate, action = member.get('plan'), member.get('estimate'), member['action'] + if action == 'blocked' or not isinstance(plan,dict) or not isinstance(estimate,dict) or not valid(estimate.get('size')): + raise ValueError(role + ': member estimate unavailable.') + policy = plan.get('memory_policy') or {} + floor = policy.get('minimum_headroom_gb') or 0 + cap = policy.get('model_memory_budget_gb') + if isinstance(floor,bool) or not isinstance(floor,(int,float)) or not math.isfinite(floor) or floor < 0: + raise ValueError(role + ': headroom is invalid.') + floors.append(math.ceil(floor * 1e9)) + if cap is not None and (isinstance(cap,bool) or not isinstance(cap,(int,float)) or not math.isfinite(cap) or cap <= 0): + raise ValueError(role + ': route cap is invalid.') + cap_bytes = math.ceil(cap * 1e9) if cap is not None else None + envelope = max(estimate['size'], cap_bytes or 0) + delta, source = envelope, 'configured_reservation' if cap_bytes is None else 'route_cap' + required_cap = estimate['size'] + if action == 'reuse': + candidate = member['candidate']; pid = candidate['pid'] + try: + state = _private_json(root / (str(plan['port']) + '.jit-state.json')) + except (OSError, ValueError): + raise ValueError(role + ': service state is unavailable or unsafe.') from None + if state.get('gateway_pid') != pid or _pid_start(pid) != candidate['process_started_at']: + raise ValueError(role + ': gateway state identity is uncertain.') + identity = process_identity(pid) + owned = [(key,row) for key,row in entries.items() if isinstance(row.get('owner'),(list,tuple)) and len(row['owner']) == 2 and row['owner'][0] == pid] + if not identity or any(not same_identity(row['owner'][1],identity) for _,row in owned): + raise ValueError(role + ': gateway ownership is uncertain.') + if state.get('model_state') == 'unloaded' and state.get('worker_pid') is None and not owned: + source = 'unloaded_reservation' + else: + if len(owned) != 1: raise ValueError(role + ': allocation is missing or ambiguous.') + key,row = owned[0]; worker = row.get('worker') + if row.get('phase') != 'resident' or 'execution_bytes' in row or row.get('model_key') != _model_key(plan): + raise ValueError(role + ': allocation is active or mismatched.') + if any(not valid(row.get(k)) for k in ('resident_bytes','workspace_bytes','growth_bytes','reserved_bytes')): + raise ValueError(role + ': workspace or residency is invalid.') + if not isinstance(worker,dict) or type(worker.get('pid')) is not int or worker['pid'] <= 0: + raise ValueError(role + ': worker identity is unavailable.') + wp = worker['pid']; current = process_identity(wp) + if (state.get('model_state') != 'loaded' or state.get('worker_pid') != wp or not current + or not same_identity(worker.get('identity'),current) or _pid_start(wp) != state.get('worker_started_at') + or not state.get('worker_started_at') or os.getpgid(wp) != worker.get('pgid')): + raise ValueError(role + ': worker identity is uncertain.') + workspace = row['workspace_bytes']; telemetry = row.get('telemetry') + if isinstance(telemetry,dict) and valid(telemetry.get('peak_bytes')) and valid(telemetry.get('active_bytes')): + workspace = max(workspace, max(0,telemetry['peak_bytes']-telemetry['active_bytes'])) + workspace_source = 'allocator_peak_delta' + else: workspace_source = 'registry_workspace' + # Resident process memory is already charged; only project extra pending work. + if budget is not None: + allocation = budget['allocations'].get(key) + if not isinstance(allocation,dict) or any(not valid(allocation.get(k)) for k in ('observed_bytes','pending_bytes','resident_bytes')): + raise ValueError(role + ': shared allocation is unavailable.') + credit, pending, source = allocation['observed_bytes'], allocation['pending_bytes'], 'observed_allocation' + else: credit, pending, source = row['resident_bytes'], row['reserved_bytes'], 'registry_resident' + growth = row['growth_bytes'] + # Task jobs reserve fresh workspace; JIT growth may already be materialized. + if plan.get('runtime') == 'tasks': + charged = allocation['resident_bytes'] if budget is not None else row['resident_bytes'] + required_cap = max(estimate['size'], row['resident_bytes']+workspace+growth, + credit+workspace+growth, charged+workspace+growth) + if cap_bytes is not None and cap_bytes < required_cap: + cap_failure = role + ': route cap is below the working estimate.' + future = max(workspace+growth, max(0,envelope-credit)) + else: + future = max(pending, max(0,envelope-credit)) + delta = max(0,future-pending) + result['members'][role] = {'credit_bytes':credit,'current_pending_bytes':pending,'workspace_bytes':workspace, + 'growth_bytes':growth,'workspace_source':workspace_source,'credit_source':source} + if plan.get('runtime') == 'tasks' and cap_bytes is not None and cap_bytes < estimate['size']: cap_failure = role + ': route cap is below the working estimate.' + result['members'].setdefault(role, {'credit_bytes':0,'current_pending_bytes':0,'credit_source':source}) + result['members'][role].update(envelope_bytes=envelope, incremental_bytes=delta, + configured_limit_bytes=cap_bytes, required_limit_bytes=required_cap if plan.get('runtime') == 'tasks' else None, + allowance_source='route_cap' if plan.get('runtime') == 'tasks' else 'model_allowance') + total += delta + floor = max(floors,default=0); required = baseline+total+floor + projected = None if budget is None else budget['accounted_bytes']+total + if not all(valid(v) for v in (baseline, total, floor, required)) or (projected is not None and not valid(projected)): + raise ValueError('Joint allocation total is invalid.') + result['estimates'].update(incremental_bytes=total, baseline_pending_bytes=baseline, + headroom_bytes=floor, required_available_bytes=required, projected_accounted_bytes=projected) + if cap_failure: result.update(status='does_not_fit',reason=cap_failure) + elif budget is not None and projected > budget['admission_bytes']: result.update(status='does_not_fit',reason='Estimated shared budget is insufficient.') + elif not valid(available): raise ValueError('OS available memory is unavailable.') + elif available < required: result.update(status='does_not_fit',reason='Estimated OS headroom is insufficient.') + else: result.update(status='fits_estimate',reason='Conservative concurrent allocation estimate.') + except (OSError,ValueError,TypeError,KeyError,OverflowError,SubprocessError) as error: + result['reason'] = str(error) + return result + +def preview_workflow(definition, *, receipts_dir=None): + definition = validate_workflow(definition) + members, binding, forecasts = {}, {}, {} + root = receipts_root(receipts_dir) + for role, member in sorted(definition['members'].items()): + try: + plan = _member_plan(member, receipts_dir) + estimate = reservation(plan.get('memory_policy'), plan) + receipt = root / (str(member['port']) + '.json') + candidate = None + if os.path.lexists(receipt): + candidate = _reuse_candidate(root, plan) + action = 'reuse' if candidate else 'start' + member_hash = plan['preview_hash'] + members[role] = {'member_plan_hash': member_hash, 'action': action, + 'runtime': plan['runtime'], 'task_kinds': plan.get('task_kinds', []), + 'endpoint_state': 'unknown' if candidate else 'not_started', + 'model_state': 'unknown' if candidate else 'unloaded', + 'reason': None, 'candidate': candidate, 'estimate': estimate} + binding[role] = {'member_plan_hash': member_hash, 'action': action, 'candidate': candidate} + forecasts[role] = {'plan':plan, 'estimate':estimate, 'action':action, 'candidate':candidate} + except (OSError, ValueError, TypeError, KeyError, RuntimeError) as error: + members[role] = {'member_plan_hash': None, 'action': 'blocked', 'endpoint_state': 'unknown', + 'model_state': 'unknown', 'reason': str(error), 'estimate': None} + binding[role] = {'member_plan_hash': None, 'action': 'blocked', 'reason': str(error)} + forecasts[role] = {'plan':None,'estimate':None,'action':'blocked'} + inspection = MemoryRegistry().inspect() + forecast = _resource_forecast(forecasts, inspection, available_memory_bytes(), root) + definition_hash = _hash(definition) + return {'schema': 'serving-workflow-preview/1', 'definition_hash': definition_hash, + 'preview_hash': _hash({'definition_hash': definition_hash, 'members': binding}), + 'members': members, 'resource_forecast': forecast} diff --git a/providers/agy/catalog.json b/providers/agy/catalog.json index 43c7efa..e34fde8 100644 --- a/providers/agy/catalog.json +++ b/providers/agy/catalog.json @@ -8,7 +8,7 @@ "repository": "cavi-ai/mlx-agent", "package": "providers/agy", "install": { - "command": "git clone --branch v0.12.0 --depth 1 https://github.com/cavi-ai/mlx-agent.git && agy plugin install ./mlx-agent/providers/agy" + "command": "git clone --branch v0.13.0 --depth 1 https://github.com/cavi-ai/mlx-agent.git && agy plugin install ./mlx-agent/providers/agy" } } ] diff --git a/providers/hermes/catalog.json b/providers/hermes/catalog.json index 5cef548..bc5c204 100644 --- a/providers/hermes/catalog.json +++ b/providers/hermes/catalog.json @@ -8,7 +8,7 @@ "repository": "cavi-ai/mlx-agent", "package": "providers/agentskills", "install": { - "command": "git clone --branch v0.12.0 --depth 1 https://github.com/cavi-ai/mlx-agent.git && python3 mlx-agent/scripts/mlx-agent install hermes --scope user --dry-run --json" + "command": "git clone --branch v0.13.0 --depth 1 https://github.com/cavi-ai/mlx-agent.git && python3 mlx-agent/scripts/mlx-agent install hermes --scope user --dry-run --json" } } ] diff --git a/providers/openclaw/catalog.json b/providers/openclaw/catalog.json index 1d93a1b..e5894c9 100644 --- a/providers/openclaw/catalog.json +++ b/providers/openclaw/catalog.json @@ -8,7 +8,7 @@ "repository": "cavi-ai/mlx-agent", "package": "providers/agentskills", "install": { - "command": "git clone --branch v0.12.0 --depth 1 https://github.com/cavi-ai/mlx-agent.git && python3 mlx-agent/scripts/mlx-agent install openclaw --scope user --dry-run --json" + "command": "git clone --branch v0.13.0 --depth 1 https://github.com/cavi-ai/mlx-agent.git && python3 mlx-agent/scripts/mlx-agent install openclaw --scope user --dry-run --json" } } ] diff --git a/providers/opencode/catalog.json b/providers/opencode/catalog.json index 169fc08..ca785f0 100644 --- a/providers/opencode/catalog.json +++ b/providers/opencode/catalog.json @@ -8,7 +8,7 @@ "repository": "cavi-ai/mlx-agent", "package": "providers/opencode", "install": { - "command": "git clone --branch v0.12.0 --depth 1 https://github.com/cavi-ai/mlx-agent.git && python3 mlx-agent/scripts/mlx-agent install opencode --scope user --dry-run --json" + "command": "git clone --branch v0.13.0 --depth 1 https://github.com/cavi-ai/mlx-agent.git && python3 mlx-agent/scripts/mlx-agent install opencode --scope user --dry-run --json" } }, { diff --git a/releases.json b/releases.json index 47c9e86..46c5416 100644 --- a/releases.json +++ b/releases.json @@ -1,7 +1,7 @@ { "mlx-agent": { - "tag": "v0.12.0", - "commit": "fc585f36abdd9d47614327afec4719fa9049d729" + "tag": "v0.13.0", + "commit": "96995d85ba0ae369dbf1d6c1c570ab012a1bbbec" }, "obsidian-agent": { "tag": "v0.1.0",