diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index f5df3f2..05c11df 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.16.0", - "sha": "854341a6ce44a0b09dea2dbf012b411919de9847" + "ref": "v0.17.0", + "sha": "26e35745620679c60ae70b017213717f63e03252" }, "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 81193e6..3b2302c 100644 --- a/packages/codex/expected-integrity.json +++ b/packages/codex/expected-integrity.json @@ -1,9 +1,9 @@ { "mlx-agent": { "repository": "cavi-ai/mlx-agent", - "source_commit": "854341a6ce44a0b09dea2dbf012b411919de9847", + "source_commit": "26e35745620679c60ae70b017213717f63e03252", "source_path": "providers/codex", - "tree": "689f380ba8541a447db47bedad40894b66d4603c216a66fab78744b622773db9", + "tree": "864d5628d2cc8d58dc369951eac14ef343af8d4d0d1cbf6c313e7beb3985f608", "skills": [ "mlx-adopt", "mlx-bench", diff --git a/packages/codex/mlx-agent/.codex-plugin/plugin.json b/packages/codex/mlx-agent/.codex-plugin/plugin.json index 4e99926..c550809 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.16.0", + "version": "0.17.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 1121a49..31cc92c 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": "854341a6ce44a0b09dea2dbf012b411919de9847", + "source_commit": "26e35745620679c60ae70b017213717f63e03252", "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": "689f380ba8541a447db47bedad40894b66d4603c216a66fab78744b622773db9" + "tree": "864d5628d2cc8d58dc369951eac14ef343af8d4d0d1cbf6c313e7beb3985f608" } } diff --git a/packages/codex/mlx-agent/src/mlx_agent/__init__.py b/packages/codex/mlx-agent/src/mlx_agent/__init__.py index af25071..32580df 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.16.0" +__version__ = "0.17.0" diff --git a/packages/codex/mlx-agent/src/mlx_agent/acestep_compose_runner.py b/packages/codex/mlx-agent/src/mlx_agent/acestep_compose_runner.py new file mode 100644 index 0000000..5b44500 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/acestep_compose_runner.py @@ -0,0 +1,68 @@ +"""Run inside the isolated ACE-Step backend: format a caption and lyrics with the ACE-Step planner, print JSON. + +The planner loads from a private folder of links to its files; the network is closed. +""" + +import argparse +import json +import os +from pathlib import Path +import socket +import tempfile +import time + +if __package__: + from .acestep_runner import link_folder, offline, planned +else: + from acestep_runner import link_folder, offline, planned + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + for name in ("planner", "caption", "lyrics"): + parser.add_argument("--" + name, required=True) + parser.add_argument("--temperature", type=float, required=True) + parser.add_argument("--bpm", type=int) + parser.add_argument("--duration", type=int) + parser.add_argument("--key") + parser.add_argument("--time-signature", type=int) + parser.add_argument("--language") + args = parser.parse_args(argv) + planner_path = Path(args.planner) + socket.socket.connect = offline + socket.create_connection = offline + os.environ.update(HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", HF_HUB_DISABLE_IMPLICIT_TOKEN="1") + from acestep.inference import format_sample + from acestep.llm_inference import LLMHandler + + # The planner's decoding is bound to every value given; it chooses the rest. + bound = {"bpm": args.bpm, "duration": args.duration, "keyscale": args.key, + "timesignature": str(args.time_signature) if args.time_signature else None, "language": args.language} + with tempfile.TemporaryDirectory(prefix="mlx-agent-acestep-") as directory: + checkpoints = Path(directory) / "checkpoints" + checkpoints.mkdir() + link_folder(planner_path, checkpoints / planner_path.name) + os.environ.update(ACESTEP_CHECKPOINTS_DIR=str(checkpoints), ACESTEP_PROJECT_ROOT=directory) + started = time.perf_counter() + planner = LLMHandler() + status, ok = planner.initialize(checkpoint_dir=str(checkpoints), lm_model_path=planner_path.name, + 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 + started = time.perf_counter() + result = format_sample(planner, args.caption, args.lyrics, + user_metadata={name: value for name, value in bound.items() if value is not None} or None, + temperature=args.temperature) + seconds = time.perf_counter() - started + if not result.success: + raise RuntimeError("The ACE-Step planner returned no plan: {0}".format(result.error or result.status_message)) + metadata = {"bpm": result.bpm, "keyscale": result.keyscale, "duration": result.duration, + "timesignature": result.timesignature, "language": result.language} + print(json.dumps(dict(planned(metadata, result.caption, True), lyrics=result.lyrics, seconds=seconds, + load_seconds=load_seconds)), flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/codex/mlx-agent/src/mlx_agent/acestep_runner.py b/packages/codex/mlx-agent/src/mlx_agent/acestep_runner.py index 82f9502..897e9db 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/acestep_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/acestep_runner.py @@ -53,6 +53,29 @@ def adapt_quantizer(checkpoint): path.write_text(source.replace(original, replacement), encoding="utf-8") +# ACE-Step planner metadata names and the names a result reports them under. +PLANNED = {"bpm": "bpm", "keyscale": "key", "duration": "duration", "timesignature": "time_signature", + "language": "language", "vocal_language": "language"} + + +def planned(metadata, caption, keep_caption): + """The tempo, key, length, meter and language the planner chose, and the caption the DiT was given.""" + metadata = metadata if isinstance(metadata, dict) else {} + found = {} + for source, name in PLANNED.items(): + if name not in found and metadata.get(source) not in (None, "", "N/A"): + found[name] = metadata[source] + # The planner writes numbers as text at times, and a meter as "4" or "4/4". + for name, kind in (("bpm", int), ("duration", float), ("time_signature", int)): + if name in found: + try: + found[name] = kind(float(str(found[name]).split("/")[0])) + except ValueError: + del found[name] + found["caption"] = caption if keep_caption else str(metadata.get("caption") or caption) + return found + + def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) for name in ("model", "caption", "lyrics", "out"): @@ -65,6 +88,8 @@ def main(argv=None): parser.add_argument("--bpm", type=int) parser.add_argument("--time-signature", type=int) parser.add_argument("--reference") + parser.add_argument("--key") + parser.add_argument("--keep-caption", action="store_true") parser.add_argument("--planner") args = parser.parse_args(argv) model, out = Path(args.model), Path(args.out) @@ -91,6 +116,11 @@ 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) + class LocalPlanner(LLMHandler): + def has_all_metas(self, user_metadata): + # The caller can bind every musical setting while the caption or vocal language still needs planning. + return False + 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, \ @@ -107,7 +137,7 @@ def _sync_model_code_if_needed(self, config_path, checkpoint_path): raise RuntimeError("ACE-Step did not load: {0}".format(status)) planner = None if args.planner: - planner = LLMHandler() + planner = LocalPlanner() status, ok = planner.initialize(checkpoint_dir=str(checkpoints), lm_model_path=args.planner, backend="mlx", device="mps") if not ok: @@ -116,11 +146,12 @@ def _sync_model_code_if_needed(self, config_path, checkpoint_path): mx.reset_peak_memory() params = GenerationParams( task_type="text2music", caption=args.caption, lyrics="[Instrumental]" if instrumental else args.lyrics, - instrumental=instrumental, bpm=args.bpm, + instrumental=instrumental, bpm=args.bpm, keyscale=args.key or "", 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, + # A kept caption reaches the DiT as written; the planner still chooses what the take leaves open. + use_cot_caption=planner is not None and not args.keep_caption, 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() @@ -134,9 +165,12 @@ def _sync_model_code_if_needed(self, config_path, checkpoint_path): # 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) + report = {"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} + if planner is not None: + report["planned"] = planned((result.extra_outputs or {}).get("lm_metadata"), args.caption, args.keep_caption) + print(json.dumps(report), flush=True) return 0 diff --git a/packages/codex/mlx-agent/src/mlx_agent/backends.py b/packages/codex/mlx-agent/src/mlx_agent/backends.py index 46a6068..78c27fa 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/backends.py +++ b/packages/codex/mlx-agent/src/mlx_agent/backends.py @@ -20,7 +20,8 @@ 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", "embedding") + "video_generation", "music_generation", "mesh_generation", "image_segmentation", "source_separation", + "embedding") MAX_PROBE_FILES = 4000 MAX_PROBE_FILE_BYTES = 1024 * 1024 QUANTIZED_BITS = (2, 3, 4, 5, 6, 8) @@ -39,6 +40,8 @@ "image_generation": ("mflux",), "video_generation": ("mlx-video",), "mesh_generation": ("mlx-3d",), + "image_segmentation": ("sam2",), + "source_separation": ("mlx-audio",), } DEFAULT_PREFERENCE = ("mlx-lm", "mlx-vlm", "mlx-audio") _ID = re.compile(r"[a-z0-9][a-z0-9-]{0,31}") @@ -140,6 +143,16 @@ def _validate_manifest(value, path): isinstance(module, str) and _PORT.fullmatch(module) for module in converters.values() ): raise _invalid(path, "port_convert maps declared ports to a module inside the port") + inference_only = value.get("port_inference_only", []) + if not isinstance(inference_only, list) or not all( + isinstance(name, str) and name in ported and name not in converters for name in inference_only + ): + raise _invalid(path, "port_inference_only lists declared ports that cannot convert checkpoints") + prompted = value.get("port_prompted", []) + if not isinstance(prompted, list) or not all( + isinstance(name, str) and name in ports.get("source_separation", ()) for name in prompted + ): + raise _invalid(path, "port_prompted lists declared source-separation ports that separate a text prompt") pipelines = value.get("port_pipelines", {}) if not isinstance(pipelines, dict) or not all( isinstance(name, str) and _PIPELINE.fullmatch(name) and port in ported for name, port in pipelines.items() @@ -256,6 +269,17 @@ def port_converter(model_type, backend_id, manifests): return "{0}.{1}".format(_module_path(manifest, category, name), module) +def port_is_inference_only(model_type, backend_id, manifests): + manifest = manifests.get(backend_id) or {} + return normalize_type(model_type or "") in manifest.get("port_inference_only", ()) + + +def port_is_prompted(model_type, backend_id, manifests): + """Whether a separation port separates the sound a text prompt names instead of a fixed stem.""" + manifest = manifests.get(backend_id) or {} + return normalize_type(model_type or "") in manifest.get("port_prompted", ()) + + def port_bits(model_type, backend_id, manifests): """The bit widths a port converts to, or None for every supported width.""" manifest = manifests.get(backend_id) or {} diff --git a/packages/codex/mlx-agent/src/mlx_agent/cli.py b/packages/codex/mlx-agent/src/mlx_agent/cli.py index 81ed6c1..b3fe194 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/cli.py +++ b/packages/codex/mlx-agent/src/mlx_agent/cli.py @@ -124,6 +124,15 @@ def _add_discovery_arguments(parser): help="rank each role by this Hugging Face order (newest: reputable publishers only)") parser.add_argument("--search", help="match repository names on Hugging Face") parser.add_argument("--fast", action="store_true", help="skip per-model enrichment (name heuristics only)") + parser.add_argument("--local-status", action="store_true", + help="mark each candidate with its local copies (exact, variant or absent)") + parser.add_argument("--exclude-local", action="store_true", + help="leave out models present locally in any version before ranking (implies --local-status)") + parser.add_argument("--gguf-root", action="append", default=None, dest="gguf_roots", + help="local model folder read for local status (repeatable; well-known folders by default)") + parser.add_argument("--mlx-root", action="append", default=None, dest="mlx_roots", + help="MLX model folder read for local status (repeatable; defaults to the GGUF roots)") + parser.add_argument("--receipts-dir", default=None, help="conversion receipts read for local status") parser.add_argument("--json", action="store_true") parser.add_argument("--wire", metavar="REPO", help="emit setup + config for a model, instead of discovering") parser.add_argument("--target", choices=["ollama", "lmstudio", "mlx_lm", "mlx-vlm", "litellm", "openclaw"], default="mlx_lm") @@ -151,6 +160,18 @@ def _run_discovery(arguments, legacy): error = result.to_dict()["error"] print("discover failed [{0}]: {1}\nremediation: {2}".format(error["code"], error["message"], error["remediation"])) return 2 + local_models = None + if arguments.local_status or arguments.exclude_local: + from .convert import ConvertError + from .local_status import scan + try: + local_models = scan(_scan_roots(arguments, allow_empty=True), mlx_roots=arguments.mlx_roots or (), + receipts=_scan_receipts(arguments), signature=False)["local_models"] + except ConvertError as error: + result = ResultEnvelope.fail("discover", error.code, str(error), error.remediation) + print(json.dumps(result.to_dict(), indent=2) if arguments.json else "discover failed [{0}]: {1}\nremediation: {2}".format( + error.code, error, error.remediation)) + return 2 service, fixture_warning, fixture_error = _discovery_service_from_environment(arguments.state_dir) result = fixture_error or service.discover(DiscoveryRequest( role=arguments.role, @@ -168,6 +189,8 @@ def _run_discovery(arguments, legacy): context_tokens=arguments.context_tokens, sort=arguments.sort, search=arguments.search, + local_models=local_models, + exclude_local=arguments.exclude_local, )) if fixture_warning: result = ResultEnvelope.ok("discover", result.data, warnings=[fixture_warning]) @@ -1115,6 +1138,8 @@ def _add_splash_tuning_arguments(parser): help="thinking tokens of a request that sets no budget (0–1010000)") parser.add_argument("--splash-persistent-cache", action=argparse.BooleanOptionalAction, default=None, help="keep Splash's SSD prompt cache across restarts") + parser.add_argument("--splash-project-cache", help="named project SSD prompt cache") + parser.add_argument("--splash-max-cache-disk-writes-gb", type=float, help="project cache write cap in decimal GB") parser.add_argument("--splash-max-cache-disk-gb", type=float, help="SSD prompt cache quota in decimal GB (0 turns the cache off; default: Splash's own)") @@ -2163,8 +2188,21 @@ def _add_convert_arguments(parser): transcribe.add_argument("--path", required=True, help="converted speech model directory") transcribe.add_argument("--audio", required=True, help="audio file (WAV, FLAC, MP3)") transcribe.add_argument("--language", default=None, help="language code passed to models that take one") + transcribe.add_argument("--words", action="store_true", help="also return each word's start and end seconds (Whisper models)") transcribe.add_argument("--timeout", type=int, default=300, help="seconds before the backend run is stopped") transcribe.add_argument("--json", action="store_true") + separate = actions.add_parser( + "separate", + help="split one audio mix into a stem and the rest with a source-separation model", + ) + separate.add_argument("--path", required=True, help="source-separation model directory") + separate.add_argument("--audio", required=True, help="audio mix (WAV, FLAC, MP3)") + separate.add_argument("--out", required=True, help="new absolute .wav path for the stem") + separate.add_argument("--rest", default=None, help="new absolute .wav path for the mix minus the stem") + separate.add_argument("--prompt", default=None, + help="the sound to separate, such as drums (text-prompted models such as SAM-Audio)") + separate.add_argument("--timeout", type=int, default=1800, help="seconds before the backend run is stopped") + separate.add_argument("--json", action="store_true") decide = actions.add_parser( "decide", help="answer typed questions about a state with a converted classification model (read-only verification canary)", @@ -2184,6 +2222,8 @@ def _add_convert_arguments(parser): generate.add_argument("--height", type=int, default=1024) generate.add_argument("--steps", type=int, default=40) generate.add_argument("--seed", type=int, default=42) + generate.add_argument("--image", action="append", default=[], + help="absolute reference still the render keeps consistent with (repeatable, up to the model's limit)") generate.add_argument("--timeout", type=int, default=1800, help="seconds before the backend run is stopped") generate.add_argument("--json", action="store_true") music = actions.add_parser("music", help="generate music from an existing local music model") @@ -2197,8 +2237,24 @@ def _add_convert_arguments(parser): 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("--key", help='musical key for ACE-Step models, such as "F# minor"') + music.add_argument("--keep-caption", action="store_true", + help="send the caption to ACE-Step as written instead of the planner's rewrite") music.add_argument("--timeout", type=int, default=3600) music.add_argument("--json", action="store_true") + compose = actions.add_parser( + "compose", help="plan a song with the ACE-Step planner beside a music model: caption, lyrics, tempo and key (read-only)") + compose.add_argument("--path", required=True, help="ACE-Step checkpoint directory with the planner beside it") + compose.add_argument("--caption", required=True, help="style, instruments, mood and vocals (1..2000 characters)") + compose.add_argument("--lyrics", required=True, help="lyrics under [section] tags, or [instrumental]") + compose.add_argument("--bpm", type=int, help="tempo the plan keeps (30..300)") + compose.add_argument("--duration", type=float, help="whole seconds the plan keeps (1..360)") + compose.add_argument("--key", help='key the plan keeps, such as "F# minor"') + compose.add_argument("--time-signature", type=int, help="beats per bar the plan keeps: 2, 3, 4 or 6") + compose.add_argument("--language", help="vocal language code the plan keeps, such as en") + compose.add_argument("--temperature", type=float, default=0.85, help="planner sampling temperature (0..2)") + compose.add_argument("--timeout", type=int, default=900, help="seconds before the backend run is stopped") + compose.add_argument("--json", action="store_true") speak = actions.add_parser( "speak", help="synthesize one text with a converted text-to-speech model to a new WAV (read-only verification canary)", @@ -2213,10 +2269,10 @@ def _add_convert_arguments(parser): speak.add_argument("--json", action="store_true") describe = actions.add_parser( "describe", - help="answer one question about an image or a video with a converted vision-language model (read-only verification canary)", + help="answer one prompt, about an image, a video or neither, with a converted vision-language model (read-only)", ) describe.add_argument("--path", required=True, help="converted vision-language model directory") - describe.add_argument("--prompt", required=True, help="question about the media (1..4000 characters)") + describe.add_argument("--prompt", required=True, help="question about the media, or a text prompt (1..16000 characters)") describe.add_argument("--image", default=None, help="image file (png, jpg, jpeg, webp)") describe.add_argument("--video", default=None, help="video file (mp4, mov, m4v)") describe.add_argument("--max-tokens", type=int, default=256, help="answer length limit (1..4096)") @@ -2244,6 +2300,9 @@ def _add_convert_arguments(parser): 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("--bbox", type=float, nargs=3, default=None, metavar=("X", "Y", "Z"), + help="TRELLIS.2: sizes with z up; the sampled shape takes their proportions and the mesh " + "their size") mesh.add_argument("--timeout", type=int, default=3600) mesh.add_argument("--json", action="store_true") video = actions.add_parser( @@ -2280,6 +2339,8 @@ def _run_convert(arguments): from .gguf import GGUFError from .inference_runner import InferenceError from .music import plan_music, run_music + from .compose import plan_compose, run_compose + from .separate import plan_separate, run_separate from .serve import default_model_present from .speak import plan_speak, run_speak from .transcribe import plan_transcribe, run_transcribe @@ -2308,11 +2369,25 @@ def served_or_local(verb, runner, plan, out): if arguments.convert_command == "transcribe": if not 1 <= arguments.timeout <= 3600: raise ValueError("--timeout must be 1..3600 seconds") - plan = plan_transcribe(arguments.path, arguments.audio, language=arguments.language) + plan = plan_transcribe(arguments.path, arguments.audio, language=arguments.language, words=arguments.words) from .compute import guarded_start result = guarded_start("transcribe", run_transcribe, plan, timeout=arguments.timeout) + human = result["text"] + if arguments.words and not arguments.json: + lines = ["{start:.3f}s - {end:.3f}s {word}".format(**word) for word in result["words"]] + human = "\n".join(([human] if human else []) + lines) + return _emit_serve_result( + ResultEnvelope.ok(operation, result), arguments.json, human=human, + ) + if arguments.convert_command == "separate": + if not 1 <= arguments.timeout <= 7200: + raise ValueError("--timeout must be 1..7200 seconds") + plan = plan_separate(arguments.path, arguments.audio, arguments.out, rest=arguments.rest, + prompt=arguments.prompt) + from .compute import guarded_start + result = guarded_start("separate", run_separate, plan, timeout=arguments.timeout) return _emit_serve_result( - ResultEnvelope.ok(operation, result), arguments.json, human=result["text"], + ResultEnvelope.ok(operation, result), arguments.json, human=result["path"], ) if arguments.convert_command == "decide": if not 1 <= arguments.timeout <= 3600: @@ -2326,17 +2401,34 @@ def served_or_local(verb, runner, plan, out): if not 1 <= arguments.timeout <= 7200: 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) - result = served_or_local("generate", run_generate, plan, arguments.out) + height=arguments.height, steps=arguments.steps, seed=arguments.seed, + images=arguments.image) + if arguments.image: + # Served endpoints take no reference images, so a referenced render runs in its own process. + from .compute import guarded_start + result = guarded_start("generate", run_generate, plan, timeout=arguments.timeout) + else: + 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, - bpm=arguments.bpm, time_signature=arguments.time_signature, reference=arguments.reference) + bpm=arguments.bpm, time_signature=arguments.time_signature, reference=arguments.reference, + key=arguments.key, keep_caption=arguments.keep_caption) 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 == "compose": + if not 1 <= arguments.timeout <= 3600: + raise ValueError("--timeout must be 1..3600 seconds") + plan = plan_compose(arguments.path, arguments.caption, arguments.lyrics, bpm=arguments.bpm, + duration=arguments.duration, key=arguments.key, + time_signature=arguments.time_signature, language=arguments.language, + temperature=arguments.temperature) + from .compute import guarded_start + result = guarded_start("compose", run_compose, plan, timeout=arguments.timeout) + return _emit_serve_result(ResultEnvelope.ok(operation, result), arguments.json, human=result["caption"]) if arguments.convert_command == "speak": if not 1 <= arguments.timeout <= 7200: raise ValueError("--timeout must be 1..7200 seconds") @@ -2350,7 +2442,12 @@ def served_or_local(verb, runner, plan, out): 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) - result = served_or_local("describe", run_describe, plan, None) + if plan["input"]["kind"] == "text": + # Served endpoints take image and video tasks; a text prompt runs locally. + from .compute import guarded_start + result = guarded_start("describe", run_describe, plan, timeout=arguments.timeout) + else: + 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: @@ -2359,7 +2456,7 @@ def served_or_local(verb, runner, plan, out): seed=arguments.seed, resolution=arguments.resolution, guidance=arguments.guidance, max_faces=arguments.max_faces, denoiser_cache=arguments.denoiser_cache, cache_memory_mib=arguments.cache_memory_mib, views=arguments.view, - guide=arguments.guide) + guide=arguments.guide, bbox=arguments.bbox) result = served_or_local("mesh", run_mesh, plan, arguments.out) return _emit_serve_result(ResultEnvelope.ok(operation, result), arguments.json, human=result["path"]) if arguments.convert_command == "video": @@ -2453,21 +2550,12 @@ def served_or_local(verb, runner, plan, out): def _convert_scan(arguments): - from .convert import ConvertError, load_receipts - 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()) - if not roots and not arguments.mlx_roots: - raise ConvertError( - "no_scan_roots", - "No model roots were given and none of the well-known GGUF directories exist.", - "Pass --gguf-root PATH or --mlx-root PATH for each model directory.", - ) - report = inventory( - roots, + from .gguf import MAX_SCAN_FILES + from .local_status import scan + report = scan( + _scan_roots(arguments), mlx_roots=arguments.mlx_roots or (), - receipts=load_receipts(arguments.receipts_dir), + receipts=_scan_receipts(arguments), signature=not arguments.no_signature, limit=arguments.limit or MAX_SCAN_FILES, compare_assets=arguments.compare_assets, @@ -2478,14 +2566,29 @@ def _convert_scan(arguments): item for item in report["models"] if item["status"] == "pending" ]) 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 _scan_roots(arguments, *, allow_empty=False): + from .convert import ConvertError + from .gguf import default_gguf_roots + roots = arguments.gguf_roots if arguments.gguf_roots is not None else ( + [] if arguments.mlx_roots is not None else default_gguf_roots()) + if not allow_empty and not roots and not arguments.mlx_roots: + raise ConvertError( + "no_scan_roots", + "No model roots were given and none of the well-known GGUF directories exist.", + "Pass --gguf-root PATH or --mlx-root PATH for each model directory.", + ) + return roots + + +def _scan_receipts(arguments): + from .convert import load_receipts + return load_receipts(arguments.receipts_dir) + + def _human_bytes(count): value = float(count) for unit in ("B", "KB", "MB", "GB", "TB"): diff --git a/packages/codex/mlx-agent/src/mlx_agent/client.py b/packages/codex/mlx-agent/src/mlx_agent/client.py new file mode 100644 index 0000000..9cdb64f --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/client.py @@ -0,0 +1,137 @@ +"""Run one ``mlx-agent convert`` verb and return its JSON result data.""" + +import json +import os +import selectors +import shutil +import signal +import subprocess +import sys +import time +from contextlib import suppress +from pathlib import Path + +STDOUT_LIMIT = 16 * 1024 * 1024 +STDERR_LIMIT = 8 * 1024 +DIAGNOSTIC_LIMIT = 2000 +_BACKEND_TIMEOUT_VERBS = frozenset({ + "transcribe", "separate", "decide", "generate", "music", "speak", "describe", "mesh", "video", +}) +_CLI_REMEDIATION = "Pass the path to the mlx-agent executable or script, or put mlx-agent on PATH." + + +class ConvertError(RuntimeError): + """A failed convert call, carrying the envelope's error fields.""" + + def __init__(self, operation, code, message, remediation=None): + self.operation = operation + self.code = code + self.message = message + self.remediation = remediation + text = "mlx-agent {0}: {1}: {2}".format(operation, code, message) + if remediation: + text += " ({0})".format(remediation) + super().__init__(text) + + +def resolve_cli(cli=None): + """Return the CLI argv: an argv sequence, an executable, a script, or ``mlx-agent`` on PATH.""" + if cli is not None and not isinstance(cli, (str, os.PathLike)): + argv = [str(part) for part in cli] + if argv and argv[0]: + return argv + value = None + else: + value = str(cli) if cli is not None else shutil.which("mlx-agent") + if not value or not Path(value).is_file(): + raise ConvertError( + "convert", + "cli_not_found", + "mlx-agent CLI not found: {0}".format(value or "not on PATH"), + _CLI_REMEDIATION, + ) + executable = str(Path(value).absolute()) + return [executable] if os.access(executable, os.X_OK) else [sys.executable, executable] + + +def _run(verb, argv, timeout): + stdout, stderr = bytearray(), bytearray() + with selectors.DefaultSelector() as selector: + try: + process = subprocess.Popen( + argv, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + start_new_session=True, + ) + except (OSError, ValueError) as error: + code = "cli_not_found" if isinstance(error, FileNotFoundError) else "cli_launch_failed" + raise ConvertError(verb, code, str(error), _CLI_REMEDIATION) from error + + with process: + deadline = time.monotonic() + timeout + try: + selector.register(process.stdout, selectors.EVENT_READ) + selector.register(process.stderr, selectors.EVENT_READ) + while selector.get_map(): + remaining = deadline - time.monotonic() + if remaining <= 0: + return None, stderr + for key, _ in selector.select(remaining): + chunk = os.read(key.fd, 65536) + if not chunk: + selector.unregister(key.fileobj) + elif key.fileobj is process.stdout: + stdout.extend(chunk[:STDOUT_LIMIT - len(stdout)]) + else: + stderr.extend(chunk) + del stderr[:-STDERR_LIMIT] + returncode = process.wait(timeout=max(0, deadline - time.monotonic())) + return (returncode, stdout), stderr + except subprocess.TimeoutExpired: + return None, stderr + finally: + if process.returncode is None: + # The unreaped child still owns this process group ID. + with suppress(ProcessLookupError): + os.killpg(process.pid, signal.SIGKILL) + + +def convert(verb, arguments, timeout, cli=None, grace=60): + """Run a JSON convert command with a deadline and return its result or confirmation preview.""" + argv = [*resolve_cli(cli), "convert", verb, *map(str, arguments)] + if verb in _BACKEND_TIMEOUT_VERBS: + argv.extend(("--timeout", str(timeout))) + argv.append("--json") + finished, stderr = _run(verb, argv, timeout + grace) + diagnostics = stderr.decode("utf-8", "replace").strip()[-DIAGNOSTIC_LIMIT:] + if finished is None: + raise ConvertError( + verb, "timeout", "no result within {0}s. {1}".format(timeout + grace, diagnostics).strip(), + "Retry with a larger timeout.", + ) + returncode, stdout = finished + try: + envelope = json.loads(stdout) + if not isinstance(envelope, dict): + raise ValueError("not an object") + except ValueError: + raise ConvertError( + verb, "no_json", + "no JSON result (exit {0}): {1}".format(returncode, diagnostics), + "Check the mlx-agent installation and the convert arguments.", + ) from None + if envelope.get("status") == "ok": + if returncode == 0: + return envelope["data"] + data = envelope.get("data") + if (verb == "start" and returncode == 2 and isinstance(data, dict) + and data.get("requires_confirmation") is True): + return data + error = envelope.get("error") + if not isinstance(error, dict): + error = {} + raise ConvertError( + verb, + error.get("code") or "unknown", + error.get("message") or "exit {0}".format(returncode), + error.get("remediation"), + ) diff --git a/packages/codex/mlx-agent/src/mlx_agent/compose.py b/packages/codex/mlx-agent/src/mlx_agent/compose.py new file mode 100644 index 0000000..bc5e57d --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/compose.py @@ -0,0 +1,86 @@ +"""Plan a song with the ACE-Step planner beside a music model (read-only). + +The planner rewrites a caption into the detailed caption ACE-Step was trained on, structures the lyrics, and +chooses the tempo, key, length, meter and language a take leaves open. Nothing is rendered. +""" + +import json +import math +import subprocess +from pathlib import Path + +from .backends import backend_python, is_installed, load_manifests, load_registries, lookup +from .inference_runner import RunnerContract, invoke +from .music import MusicError, _acestep_planner, validate_parameters + +COMPOSE_SCHEMA = "compose/1" +COMPOSE_RUNNER = Path(__file__).with_name("acestep_compose_runner.py") +DEFAULT_TIMEOUT_SECONDS = 900 +MAX_TEMPERATURE = 2.0 +RESULT_KEYS = ("caption", "lyrics", "bpm", "duration", "key", "time_signature", "language", "seconds", "load_seconds") + + +def plan_compose(model_path, caption, lyrics, bpm=None, duration=None, key=None, time_signature=None, language=None, + temperature=0.85, manifests=None, registries=None, root=None): + """The planner run for an ACE-Step checkpoint; bpm, duration, key, time signature and language bind the plan.""" + model = Path(model_path).expanduser() + try: + config = json.loads((model / "config.json").read_text(encoding="utf-8")) + if not model.is_absolute() or not isinstance(config, dict): + raise ValueError("An absolute local model directory is required") + except (OSError, ValueError) as error: + raise MusicError("model_unreadable", str(error), "Pass an existing ACE-Step checkpoint directory.") from error + checked = validate_parameters(caption, lyrics, 15.0 if duration is None else duration, bpm=bpm, + time_signature=time_signature, key=key) + if duration is not None and duration != int(duration): + raise MusicError("invalid_arguments", "Compose duration must be specified in whole seconds.", "Use --duration 30.") + if language is not None and (not isinstance(language, str) or not language.isascii() or not language.isalpha() + or not 2 <= len(language) <= 8): + raise MusicError("invalid_arguments", "The language must be a language code such as en.", "Use --language en.") + if isinstance(temperature, bool) or not isinstance(temperature, (int, float)) or not math.isfinite(temperature) \ + or not 0 <= temperature <= MAX_TEMPERATURE: + raise MusicError("invalid_arguments", "Temperature must be 0..{0}.".format(MAX_TEMPERATURE), "Use --temperature 0.85.") + 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"] == "music_generation" and hit["backend"] == "ace-step"] + if not hits: + raise MusicError("not_music_model", "Only ACE-Step checkpoints have a song planner.", "Pass an ACE-Step 1.5 checkpoint.") + planner = _acestep_planner(model) + if planner is None: + raise MusicError("model_unreadable", "No ACE-Step planner (acestep-5Hz-lm-*) is beside {0}.".format(model), + "Keep acestep-5Hz-lm-1.7B in the ACE-Step checkpoints folder.") + manifest = manifests["ace-step"] + if not is_installed(manifest, root): + raise MusicError("backend_not_installed", "The ace-step backend is not installed.", + "Install it first: mlx-agent backend install ace-step.") + argv = [str(backend_python(manifest, root)), str(COMPOSE_RUNNER), "--planner", str(model.parent / planner), + "--caption=" + caption, "--lyrics=" + lyrics, "--temperature", repr(float(temperature))] + bound = {"bpm": bpm, "duration": int(duration) if duration is not None else None, "key": checked.get("key"), + "time_signature": time_signature, "language": language} + for name, value in bound.items(): + if value is not None: + argv += ["--" + name.replace("_", "-") + "=" + str(value)] + return {"backend": "ace-step", "model": str(model), "planner": planner, "temperature": float(temperature), + "bound": {name: value for name, value in bound.items() if value is not None}, "argv": argv} + + +CONTRACT = RunnerContract( + verb="compose", error=MusicError, action="plan the song", + accept=lambda value, plan: isinstance(value.get("caption"), str) and bool(value["caption"].strip()) + and isinstance(value.get("lyrics"), str), + remediation="Check that the ACE-Step planner beside the checkpoint is complete.", + activity="Song planning", timeout_remediation="Use a larger --timeout.", + environment={"HF_HUB_OFFLINE": "1", "TRANSFORMERS_OFFLINE": "1"}, +) + + +def run_compose(plan, manifests=None, root=None, timeout=DEFAULT_TIMEOUT_SECONDS, runner=subprocess.run): + result = invoke(plan, CONTRACT, manifests, root, timeout, runner) + bound = dict(plan["bound"]) + # ACE-Step skips emitting the language field when the caller supplies it. + if "language" in bound: + result["language"] = bound["language"] + return dict({"schema": COMPOSE_SCHEMA, "backend": plan["backend"], "model": plan["model"], "planner": plan["planner"], + "temperature": plan["temperature"], "bound": bound}, + **{key: result.get(key) for key in RESULT_KEYS}) diff --git a/packages/codex/mlx-agent/src/mlx_agent/convert.py b/packages/codex/mlx-agent/src/mlx_agent/convert.py index 93a1932..2da29bd 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/convert.py +++ b/packages/codex/mlx-agent/src/mlx_agent/convert.py @@ -27,6 +27,7 @@ port_converter, port_downloads, port_files, + port_is_inference_only, port_requirements, recipe_for, read_install_marker, @@ -202,6 +203,15 @@ def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backend "invalid_arguments", "ACE-Step checkpoints run as published; the ace-step backend converts nothing.", "Generate with mlx-agent convert music --path .", ) + config = _source_config(hf_path) if hf_path != repo and backend == "mlx-audio" else {} + for candidate in (model_type, config.get("model_type")): + if port_is_inference_only(candidate, backend, manifests): + raise ConvertError( + "conversion_unavailable", "{0} checkpoints use published MLX weights.".format(candidate), + "Use a published MLX checkpoint with mlx-agent convert separate --path .", + ) + requantize_music = (config.get("model_type") == "minimax_music3" + and isinstance(config.get("quantization"), dict) and bool(config["quantization"])) 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)) @@ -214,7 +224,7 @@ def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backend ) 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: + if requantize_music and q_bits not in MUSIC_REQUANTIZE_BITS: raise ConvertError( "invalid_arguments", "Exported music checkpoints requantize at {0} bits only.".format(_joined(MUSIC_REQUANTIZE_BITS)), @@ -246,7 +256,7 @@ def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backend 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): + if requantize_music: plan["argv"] = [str(python), str(MUSIC_REQUANTIZE_RUNNER)] + flags else: plan["argv"] = [str(python), "-m", converter or manifest["convert"]] + flags @@ -258,14 +268,12 @@ def plan_convert(repo, q_bits=4, out=None, backend=None, manifests=None, backend return _finish_source_plan(plan, primary, dependencies, require_completion) -def _is_quantized_music_source(path): - """Exported MLX music weights need the music loader, not the raw converter.""" +def _source_config(path): try: config = json.loads((Path(path) / "config.json").read_text(encoding="utf-8")) except (OSError, ValueError): - return False - return (isinstance(config, dict) and config.get("model_type") == "minimax_music3" - and isinstance(config.get("quantization"), dict) and bool(config["quantization"])) + return {} + return config if isinstance(config, dict) else {} def _required_sources(repo, model_type, manifests, hf_cache, dependencies=None): diff --git a/packages/codex/mlx-agent/src/mlx_agent/describe.py b/packages/codex/mlx-agent/src/mlx_agent/describe.py index ac8126d..f52d257 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/describe.py +++ b/packages/codex/mlx-agent/src/mlx_agent/describe.py @@ -1,4 +1,4 @@ -"""Answer one question about an image or a video with a converted vision-language model through its backend (read-only).""" +"""Answer one prompt, about an image, a video or neither, with a converted vision-language model through its backend (read-only).""" from __future__ import annotations @@ -20,7 +20,7 @@ DESCRIBE_SCHEMA = "describe/1" DESCRIBE_RUNNER = Path(__file__).resolve().with_name("describe_runner.py") DEFAULT_TIMEOUT_SECONDS = 900 -MAX_PROMPT_CHARS = 4000 +MAX_PROMPT_CHARS = 16000 MAX_TOKENS_RANGE = range(1, 4097) MAX_TEMPERATURE = 2.0 MIN_FPS, MAX_FPS = 0.1, 8.0 @@ -73,8 +73,8 @@ def plan_describe(model_path, prompt, image=None, video=None, max_tokens=256, te ord(character) < 32 and character not in "\n\t" for character in prompt ): raise _invalid("The prompt must be 1..{0} characters of plain text.".format(MAX_PROMPT_CHARS), "Pass --prompt with a question about the media.") - if (image is None) == (video is None): - raise _invalid("Pass exactly one of --image or --video.", "Pass --image FILE for a picture or --video FILE for a clip.") + if image is not None and video is not None: + raise _invalid("Pass at most one of --image or --video.", "Pass --image FILE for a picture, --video FILE for a clip, or neither for a text prompt.") if not isinstance(max_tokens, int) or isinstance(max_tokens, bool) or max_tokens not in MAX_TOKENS_RANGE: raise _invalid("--max-tokens must be 1..4096.", "Pass --max-tokens 256, for example.") if not _number(temperature) or not 0 <= temperature <= MAX_TEMPERATURE: @@ -85,8 +85,11 @@ def plan_describe(model_path, prompt, image=None, video=None, max_tokens=256, te raise _invalid("--fps must be {0}..{1}.".format(MIN_FPS, MAX_FPS), "Pass --fps 1.0, for example.") if max_pixels is not None and (not isinstance(max_pixels, int) or isinstance(max_pixels, bool) or not 1 <= max_pixels <= MAX_PIXELS_LIMIT): raise _invalid("--max-pixels must be 1..{0}.".format(MAX_PIXELS_LIMIT), "Pass --max-pixels 1000000, for example.") - kind = "image" if image is not None else "video" - media = _media(kind, image if image is not None else video, IMAGE_SUFFIXES if image is not None else VIDEO_SUFFIXES) + if max_pixels is not None and image is None and video is None: + raise _invalid("--max-pixels applies to --image or --video only.", "Drop --max-pixels for a text prompt.") + kind = "image" if image is not None else "video" if video is not None else "text" + media = None if kind == "text" else _media(kind, image if image is not None else video, + IMAGE_SUFFIXES if image is not None else VIDEO_SUFFIXES) 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 @@ -108,7 +111,8 @@ def plan_describe(model_path, prompt, image=None, video=None, max_tokens=256, te used_fps = (DEFAULT_FPS if fps is None else float(fps)) if kind == "video" else None argv = [ str(backend_python(manifest, root)), str(DESCRIBE_RUNNER), "--model", str(model), "--prompt=" + prompt, - "--{0}".format(kind), str(media), "--max-tokens", str(max_tokens), "--temperature", repr(float(temperature)), + *(() if media is None else ("--{0}".format(kind), str(media))), + "--max-tokens", str(max_tokens), "--temperature", repr(float(temperature)), ] if used_fps is not None: argv += ["--fps", repr(used_fps)] @@ -116,7 +120,7 @@ def plan_describe(model_path, prompt, image=None, video=None, max_tokens=256, te argv += ["--max-pixels", str(max_pixels)] return { "backend": manifest["id"], "model": str(model), "model_type": model_type, - "input": {"kind": kind, "path": str(media)}, "argv": argv, + "input": {"kind": kind} if media is None else {"kind": kind, "path": str(media)}, "argv": argv, } 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 e18c99c..5dd49f3 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/describe_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/describe_runner.py @@ -49,7 +49,7 @@ def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--model", required=True) parser.add_argument("--prompt", required=True) - source = parser.add_mutually_exclusive_group(required=True) + source = parser.add_mutually_exclusive_group() source.add_argument("--image") source.add_argument("--video") parser.add_argument("--max-tokens", type=int, required=True) @@ -68,15 +68,16 @@ def main(argv=None): config = model.config model_type = str(getattr(config, "model_type", None) or "") - kind = "image" if arguments.image else "video" + kind = "image" if arguments.image else "video" if arguments.video else "text" if model_type.lower() not in MODEL_CONFIG: - error = "not_vision_model" if kind == "image" else "video_unsupported" + error = "video_unsupported" if kind == "video" else "not_vision_model" return _refuse(error, model_type, "mlx_vlm has no chat format for images or frames of this model type") + # A prompt with no media is answered from the text alone. images, videos, template = [], None, {} if kind == "image": images = [arguments.image] - else: + elif kind == "video": from mlx_vlm.generate.video import processor_handles_video, resolve_video_inputs from mlx_vlm.utils import VideoSampling diff --git a/packages/codex/mlx-agent/src/mlx_agent/discovery.py b/packages/codex/mlx-agent/src/mlx_agent/discovery.py index dcf786e..182e437 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/discovery.py +++ b/packages/codex/mlx-agent/src/mlx_agent/discovery.py @@ -14,18 +14,22 @@ from .contracts import ResultEnvelope from .host import HostInventory from .huggingface import HuggingFaceClient +from .local_status import match as local_match from .models import ( DISCOVERY_ROLES, REPUTABLE, + TASK_ROLE_TYPES, base_name, classify, classify_roles, infer_quantization, + pipeline_task_type, quant_rank, resolve_ram, resolve_reasoning, wiring, ) +from .taxonomy import PIPELINE_TYPES CACHE_SCHEMA_VERSION = "2.0" @@ -41,6 +45,23 @@ } +def role_pipeline_tag(role): + """The Hugging Face pipeline tag a task role lists by: the first tag taxonomy maps to its task type.""" + task_type = TASK_ROLE_TYPES.get(role) + if task_type is None: + return None + # Music models carry text-to-audio, which taxonomy also reads as speech. + if task_type == "music_generation": + return "text-to-audio" + return next((tag for tag, mapped in PIPELINE_TYPES.items() if mapped == task_type), None) + + +def _local_digest(records): + """A stable fingerprint of the local models a response was built against.""" + rows = sorted(records, key=lambda record: record["path"]) + return hashlib.sha256(json.dumps(rows, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()[:20] + + @dataclass(frozen=True) class DiscoveryRequest: """Bounded, explicit discovery policy. Legacy ``new`` and ``fast`` remain supported.""" @@ -60,6 +81,9 @@ class DiscoveryRequest: context_tokens: object = None sort: object = None search: object = None + # Records from local_status.local_models; exclude_local drops present models before ranking. + local_models: object = None + exclude_local: bool = False def cache_request(self): """The reproducible request shape, excluding transport-only cache switches.""" @@ -81,6 +105,9 @@ def cache_request(self): shape["sort"] = self.sort if _normalise_search(self.search) is not None: shape["search"] = _normalise_search(self.search) + if self.local_models is not None: + shape["local"] = _local_digest(self.local_models) + shape["exclude_local"] = bool(self.exclude_local) return shape @@ -218,6 +245,9 @@ def discover(self, request): list_options = {"sort": list_sort} if search is not None: list_options["search"] = search + pipeline_tag = role_pipeline_tag(request.role) + if pipeline_tag is not None: + list_options["pipeline_tag"] = pipeline_tag list_url_builder = getattr(self._huggingface, "list_models_url", None) list_url = ( list_url_builder(limit_fetch=300, **list_options) @@ -259,24 +289,34 @@ def _build_response(self, request, raw, host_data, list_url=None): limit = max(0, int(request.limit)) ranking = self._ranking(request) listed = [] + primary = {} + excluded = [] for model in raw: repo = model.get("id") or model.get("modelId") if not repo or repo in seen_repo: continue seen_repo.add(repo) list_rank = len(seen_repo) - 1 - if ( - request.role - and request.role != "tool-use" - and classify(repo) != request.role - ): + tags = model.get("tags") or [] + role = classify(repo, model.get("pipeline_tag"), tags) + # A task type without a discovery role (classification, segmentation) is never listed. + if role is None: + continue + if request.role and request.role != "tool-use" and role != request.role: continue if request.sort == "newest" and repo.split("/", 1)[0].lower() not in REPUTABLE: continue - tags = model.get("tags") or [] # GGUF-only repositories carry no MLX weights, and their tree sums every quant file. if "gguf" in tags and "safetensors" not in tags: continue + # Models already local in any version leave before ranking, so they never take a slot. + if request.exclude_local and request.local_models is not None: + presence = local_match(request.local_models, repo) + if presence["status"] != "absent": + excluded.append({"repo": repo, "status": presence["status"], "basis": presence["basis"], + "copies": [copy["path"] for copy in presence["copies"]]}) + continue + primary[repo] = role listed.append((repo, model, list_rank)) # Walk in final rank order: a role list is settled once it holds `limit` # candidates, because every later candidate ranks below them. @@ -284,7 +324,7 @@ def _build_response(self, request, raw, host_data, list_url=None): wanted = (request.role,) if request.role else DISCOVERY_ROLES remaining = {role: 0 for role in DISCOVERY_ROLES} for repo, _model, _rank in listed: - remaining[classify(repo)] += 1 + remaining[primary[repo]] += 1 unprocessed = len(listed) def open_roles(): @@ -308,10 +348,10 @@ def open_roles(): while position < len(listed) and len(batch) < batch_size: entry = listed[position] position += 1 - remaining[classify(entry[0])] -= 1 + remaining[primary[entry[0]]] -= 1 unprocessed -= 1 # A repository whose role list is settled can still join tool-use. - if classify(entry[0]) in still_open or "tool-use" in still_open: + if primary[entry[0]] in still_open or "tool-use" in still_open: batch.append(entry) enrichments = {} if request.fast else self._inspect_all([repo for repo, _model, _rank in batch]) self._accept_batch( @@ -323,19 +363,26 @@ def open_roles(): buckets[role].sort(key=ranking, reverse=True) buckets[role] = buckets[role][:limit] - return { + response = { "host": host_data, "fast": request.fast, "roles": {role: items for role, items in buckets.items() if items}, "rejected": rejected, "request": request.cache_request(), } + if request.local_models is not None: + response["local"] = { + "models": len(request.local_models), + "exclude_local": bool(request.exclude_local), + "excluded": excluded, + } + return response def _accept_batch(self, batch, enrichments, request, host_data, list_url, buckets, rejected, seen_base, rejection_limit, ranking): for repo, model, list_rank in batch: enrichment = {} if request.fast else enrichments[repo] - roles, tool_use = classify_roles(repo, enrichment) + roles, tool_use = classify_roles(repo, enrichment, model.get("pipeline_tag"), model.get("tags") or ()) selected_roles = ( (request.role,) if request.role in roles else () ) if request.role else roles @@ -417,6 +464,11 @@ def _candidate( } if enrichment.get("tree_available") is True and enrichment.get("weight_bytes"): facts["weight_bytes"] = enrichment["weight_bytes"] + pipeline_tag = model.get("pipeline_tag") + if pipeline_tag: + facts["pipeline_tag"] = pipeline_tag + task_type = pipeline_task_type(repo, pipeline_tag, model.get("tags") or ()) + role_source = "pipeline_tag" if task_type not in (None, "text_llm", "vision_language") else "name" candidate = { # Legacy report keys. "repo": repo, @@ -456,6 +508,7 @@ def _candidate( ram_source, reason_source, list_url, + role_source, ), "rank_score": rank_score, # Position in the Hugging Face listing for the requested sort. @@ -465,6 +518,8 @@ def _candidate( } if community_bench is not None: candidate["community_bench"] = community_bench + if request.local_models is not None: + candidate["local"] = local_match(request.local_models, repo, facts.get("weight_bytes")) return candidate @staticmethod @@ -477,6 +532,7 @@ def _provenance( ram_source, reason_source, list_url=None, + role_source="name", ): encoded = repo.replace("/", "%2F") records = [{ @@ -501,7 +557,9 @@ def _provenance( "url": enrichment.get("tree_url") or "https://huggingface.co/api/models/{0}/tree/main?recursive=true".format(encoded), "fields": ["weight_bytes"], }) - if tool_use["source"] in ("chat_template", "tags", "checked"): + if role_source == "pipeline_tag": + role_basis = "primary role from Hugging Face pipeline tag" + elif tool_use["source"] in ("chat_template", "tags", "checked"): role_basis = ( "primary role from repository name; tool-use signal from " "Hugging Face metadata ({0})" @@ -637,6 +695,7 @@ def _legacy_compatible(request): and request.runtime is None and request.sort is None and _normalise_search(request.search) is None + and request.local_models is None and not request.refresh and not request.offline ) diff --git a/packages/codex/mlx-agent/src/mlx_agent/generate.py b/packages/codex/mlx-agent/src/mlx_agent/generate.py index 52d33f0..fdf9ec0 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/generate.py +++ b/packages/codex/mlx-agent/src/mlx_agent/generate.py @@ -20,6 +20,7 @@ DEFAULT_TIMEOUT_SECONDS = 1800 MAX_PROMPT_CHARS = 2000 SIDES = range(256, 2049) +IMAGE_SUFFIXES = (".png", ".jpg", ".jpeg", ".webp") class GenerateError(InferenceError): @@ -30,9 +31,9 @@ def _invalid(message, remediation): return GenerateError("invalid_arguments", message, remediation) -def plan_generate(model_path, prompt, out, width=1024, height=1024, steps=40, seed=42, +def plan_generate(model_path, prompt, out, width=1024, height=1024, steps=40, seed=42, images=(), manifests=None, registries=None, root=None): - """Pick the image backend for a converted model directory; pure apart from reading config.json.""" + """Pick the image backend for a converted model directory; ``images`` are reference stills the render keeps consistent with.""" model = Path(model_path).expanduser() try: config = json.loads((model / "config.json").read_text(encoding="utf-8")) @@ -51,11 +52,24 @@ def plan_generate(model_path, prompt, out, width=1024, height=1024, steps=40, se for name, value in (("width", width), ("height", height)): if not isinstance(value, int) or isinstance(value, bool) or value not in SIDES or value % 16: raise _invalid("--{0} must be a multiple of 16 from 256 to 2048.".format(name), "Pass --{0} 1024, for example.".format(name)) - if not isinstance(steps, int) or isinstance(steps, bool) or not 1 <= steps <= 100: - raise _invalid("--steps must be 1..100.", "Pass --steps 40, for example.") + model_type = config.get("model_type") if isinstance(config, dict) else None + limit = config.get("max_references", 0) if isinstance(config, dict) else 0 + min_steps = 2 if model_type == "qwen_image_21" and limit else 1 + if not isinstance(steps, int) or isinstance(steps, bool) or not min_steps <= steps <= 100: + raise _invalid("--steps must be {0}..100 for this checkpoint.".format(min_steps), "Pass --steps 40, for example.") if not isinstance(seed, int) or isinstance(seed, bool) or not 0 <= seed < 2 ** 32: raise _invalid("--seed must be 0..4294967295.", "Pass --seed 42, for example.") - model_type = config.get("model_type") if isinstance(config, dict) else None + references = [Path(path).expanduser() for path in images] + for reference in references: + if not reference.is_absolute() or reference.suffix.lower() not in IMAGE_SUFFIXES or not reference.is_file(): + raise _invalid("--image {0} is not an existing absolute PNG, JPEG or WebP file.".format(reference), + "Pass the reference still's absolute path.") + if references and not (isinstance(limit, int) and len(references) <= limit): + raise GenerateError( + "references_unsupported", + "{0} takes {1} reference images; {2} were passed.".format(model, limit if isinstance(limit, int) else 0, len(references)), + "Convert the model again with the current backend to keep its vision encoder, or pass fewer --image.", + ) manifests = load_manifests() if manifests is None else manifests registries = load_registries(manifests, root) if registries is None else registries hits = sorted( @@ -78,6 +92,8 @@ def plan_generate(model_path, prompt, out, width=1024, height=1024, steps=40, se "--prompt", prompt, "--out", str(target), "--width", str(width), "--height", str(height), "--steps", str(steps), "--seed", str(seed), ] + for reference in references: + argv += ["--image", str(reference)] return {"backend": manifest["id"], "model": str(model), "out": str(target), "argv": argv} @@ -85,11 +101,12 @@ def plan_generate(model_path, prompt, out, width=1024, height=1024, steps=40, se verb="generate", error=GenerateError, accept=lambda value, plan: isinstance(value.get("path"), str), action="render the prompt", remediation="Check that the directory is a complete converted image model.", activity="Image generation", timeout_remediation="Use fewer steps, a smaller size, or a larger --timeout.", + refusals={"invalid_arguments": lambda plan, detail: (detail, "Pass a readable PNG, JPEG or WebP reference file.")}, ) def run_generate(plan, manifests=None, root=None, timeout=DEFAULT_TIMEOUT_SECONDS, runner=subprocess.run): result = invoke(plan, CONTRACT, manifests, root, timeout, runner) - keys = ("path", "width", "height", "steps", "seed", "seconds", "load_seconds", "pixel_std") + keys = ("path", "width", "height", "steps", "seed", "seconds", "load_seconds", "pixel_std", "images") return dict({"schema": GENERATE_SCHEMA, "backend": plan["backend"], "model": plan["model"]}, **{key: result.get(key) for key in keys}) 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 04a32b8..e7be8ca 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/generate_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/generate_runner.py @@ -22,16 +22,26 @@ def main(argv=None): parser.add_argument("--height", type=int, required=True) parser.add_argument("--steps", type=int, required=True) parser.add_argument("--seed", type=int, required=True) + parser.add_argument("--image", action="append", default=[]) arguments = parser.parse_args(argv) port = importlib.import_module(arguments.module) + options = {} + if arguments.image: + try: + options["images"] = port.prepare_references(arguments.image) + except ValueError as error: + print(json.dumps({"error": "invalid_arguments", "detail": str(error)}), flush=True) + return 3 started = time.time() 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, - steps=arguments.steps, seed=arguments.seed, + steps=arguments.steps, seed=arguments.seed, **options, ) + if arguments.image: + result["images"] = arguments.image result["load_seconds"] = round(load_seconds, 3) print(json.dumps(result), flush=True) return 0 diff --git a/packages/codex/mlx-agent/src/mlx_agent/gguf.py b/packages/codex/mlx-agent/src/mlx_agent/gguf.py index 62da08f..11128f8 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/gguf.py +++ b/packages/codex/mlx-agent/src/mlx_agent/gguf.py @@ -131,12 +131,25 @@ ) +_LMSTUDIO_DEFAULT_ROOTS = ("~/.cache/lm-studio/models", "~/.lmstudio/models") +_LMSTUDIO_SETTINGS = "~/.lmstudio/settings.json" + + +def lmstudio_roots(): + """LM Studio model folders: its default locations and the downloads folder set in its settings.""" + candidates = list(_LMSTUDIO_DEFAULT_ROOTS) + settings = _read_json_object(Path(_LMSTUDIO_SETTINGS).expanduser(), MAX_CONFIG_BYTES) + if settings and isinstance(settings.get("downloadsFolder"), str) and settings["downloadsFolder"]: + candidates.append(settings["downloadsFolder"]) + return list(dict.fromkeys(str(Path(candidate).expanduser()) for candidate in candidates)) + + def default_gguf_roots(): - """Well-known local weight directories that exist on this host.""" + """Well-known local weight directories that exist on this host, LM Studio's downloads folder included.""" roots = [] - for candidate in _DEFAULT_ROOTS: + for candidate in list(_DEFAULT_ROOTS) + lmstudio_roots(): expanded = Path(candidate).expanduser() - if expanded.is_dir(): + if expanded.is_dir() and str(expanded) not in roots: roots.append(str(expanded)) return roots @@ -652,9 +665,28 @@ def _component_weights(directory): isinstance(name, str) and name and "/" not in name and name not in (".", "..") for name in names ): return False + if value.get("model_type") == "qwen_image_21" and value.get("max_references") and "processor" in names: + # Earlier reference-enabled conversions listed the weightless image processor here. + if not Path(directory, "processor", "preprocessor_config.json").is_file(): + return False + names = [name for name in names if name != "processor"] + if not names: + return False return all(any(Path(directory, name).glob("*.safetensors")) for name in names) +def _mlx_output_markers(directory, filenames): + # Cache weight symlinks must still point to files. + if not any(name.endswith(".safetensors") and (directory / name).is_file() for name in filenames) \ + and not _component_weights(directory): + return None + provenance = read_provenance(directory) + marker = _mlx_config(directory) + if provenance is None and marker is None and not _mlx_community_snapshot(directory): + return None + return provenance, marker + + def scan_mlx_outputs(roots, limit=MAX_SCAN_FILES, errors=None): """Inventory MLX model directories beneath the configured roots.""" outputs = [] @@ -692,14 +724,10 @@ def scan_mlx_outputs(roots, limit=MAX_SCAN_FILES, errors=None): if len(seen) >= limit: return sorted(outputs, key=lambda item: item["path"]) continue - # is_file follows cache symlinks: a snapshot whose weight blobs are missing is not a model. - if not any(name.endswith(".safetensors") and (directory / name).is_file() for name in filenames) \ - and not _component_weights(directory): - continue - provenance = read_provenance(directory) - marker = _mlx_config(directory) - if provenance is None and marker is None and not _mlx_community_snapshot(directory): + markers = _mlx_output_markers(directory, filenames) + if markers is None: continue + provenance, marker = markers try: resolved = directory.resolve() except OSError: @@ -745,15 +773,84 @@ def _output_matches(entry, output): return None +def _attached_projector(output): + provenance = output.get("provenance") or {} + projector = (provenance.get("source") or {}).get("projector") + return projector if isinstance(projector, dict) else provenance.get("projector") + + +def _projector_identity(projector): + signature = projector.get("signature") + if not isinstance(signature, str) or not signature: + signature = None + path = projector.get("path") + if isinstance(path, str) and path: + try: + return signature, Path(path).expanduser().resolve() + except (OSError, RuntimeError, ValueError): + pass + return signature, None + + +def _projector_matches(current, recorded): + signature, path = current + recorded_signature, recorded_path = recorded + if signature is not None and recorded_signature is not None: + return signature == recorded_signature + return path is not None and path == recorded_path + + +def _projector_receipt_output(receipt): + out = receipt.get("out") + if not isinstance(out, str) or not out or receipt.get("exit_status") == "failed": + return None + try: + directory = Path(out).expanduser() + if (directory / "config.json").is_file() and _mlx_output_markers(directory, os.listdir(directory)) is not None: + return out + except (OSError, RuntimeError, ValueError): + return None + return None + + +def _pair_companion(entry, projector_outputs, projector_receipts): + """A projector is converted once its base model's conversion attached it to an output.""" + identity = _projector_identity(entry) + matches = [out for projector, out in projector_outputs if _projector_matches(identity, projector)] + if matches: + evidence = "provenance" + else: + for projector, receipt in projector_receipts: + if _projector_matches(identity, projector): + out = _projector_receipt_output(receipt) + if out is not None: + matches.append(out) + evidence = "receipt" if matches else "companion" + return dict(entry, status="converted" if matches else "companion", outputs=sorted(set(matches)), evidence=evidence) + + def pair_conversions(entries, outputs, receipts=()): - """Mark each GGUF as converted or pending, by provenance then by name.""" + """Mark each GGUF as converted or pending, by provenance then by name. + + Projectors pair with the output their base model's conversion attached them to; drafters no + port converts stay companions of their target instead of pending conversions. + """ receipt_sources = {} + projector_receipts = [] for receipt in receipts: source = receipt.get("source") or {} + projector = source.get("projector") + if isinstance(projector, dict): + projector_receipts.append((_projector_identity(projector), receipt)) for key in ("signature", "path"): value = source.get(key) if isinstance(value, str) and value: receipt_sources.setdefault(value, receipt) + projector_outputs = [] + for output in outputs: + projector = _attached_projector(output) + if isinstance(projector, dict): + projector_outputs.append((_projector_identity(projector), output["path"])) paired = [] for entry in entries: shard = entry.get("shard") @@ -761,7 +858,7 @@ def pair_conversions(entries, outputs, receipts=()): paired.append(dict(entry, status="shard", outputs=[], evidence="shard")) continue if entry.get("companion"): - paired.append(dict(entry, status="companion", outputs=[], evidence="companion")) + paired.append(_pair_companion(entry, projector_outputs, projector_receipts)) continue matches = [] evidence = None @@ -777,9 +874,13 @@ def pair_conversions(entries, outputs, receipts=()): if isinstance(out, str) and Path(out).is_dir(): matches.append(out) evidence = "receipt" + status = "converted" if matches else "pending" + draft = entry.get("draft") + if not matches and draft is not None and draft.get("port") is None: + status, evidence = "companion", "drafter" paired.append(dict( entry, - status="converted" if matches else "pending", + status=status, outputs=sorted(set(matches)), evidence=evidence, )) @@ -879,6 +980,11 @@ def _mlx_model_key(directory): return _mlx_name_key(_mlx_name(directory)) +def name_key(repo): + """The model key a repository shares with its local copies: format and quantization labels removed.""" + return _mlx_name_key(str(repo).rsplit("/", 1)[-1]) + + def _read_json_object(location, limit): try: if Path(location).stat().st_size > limit: diff --git a/packages/codex/mlx-agent/src/mlx_agent/host.py b/packages/codex/mlx-agent/src/mlx_agent/host.py index a7ee4c7..ba5b41d 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/host.py +++ b/packages/codex/mlx-agent/src/mlx_agent/host.py @@ -14,6 +14,11 @@ class HostInventory: @staticmethod def runtime_supports(runtime, role): """Whether a runtime can serve the requested model class, independent of install state.""" + from .models import TASK_ROLE_TYPES + + # Speech, image, video, 3D and music models run on task backends, not chat servers. + if role in TASK_ROLE_TYPES: + return False if runtime == "mlx-vlm": return role == "vision" if role == "vision": diff --git a/packages/codex/mlx-agent/src/mlx_agent/huggingface.py b/packages/codex/mlx-agent/src/mlx_agent/huggingface.py index ffe0851..3f87a05 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/huggingface.py +++ b/packages/codex/mlx-agent/src/mlx_agent/huggingface.py @@ -533,10 +533,12 @@ def fetch_safetensors_header(self, repo, revision, filename, timeout=8): return self._header_get(url, timeout=timeout) @staticmethod - def list_models_url(sort="trendingScore", limit_fetch=300, search=""): + def list_models_url(sort="trendingScore", limit_fetch=300, search="", pipeline_tag=None): params = {"filter": "mlx", "sort": sort, "direction": "-1", "limit": limit_fetch} if search: params["search"] = search + if pipeline_tag: + params["pipeline_tag"] = pipeline_tag return "{0}?{1}".format(HF_API, urllib.parse.urlencode(params)) @staticmethod @@ -573,8 +575,9 @@ def list_datasets_url(search="", limit_fetch=20): params["search"] = search return "{0}?{1}".format(HF_DATASETS_API, urllib.parse.urlencode(params)) - def list_models(self, sort="trendingScore", limit_fetch=300, search=""): - return self._http_get(self.list_models_url(sort=sort, limit_fetch=limit_fetch, search=search)) + def list_models(self, sort="trendingScore", limit_fetch=300, search="", pipeline_tag=None): + return self._http_get(self.list_models_url(sort=sort, limit_fetch=limit_fetch, search=search, + pipeline_tag=pipeline_tag)) def list_adapters(self, search="", limit_fetch=20, timeout=10): """List PEFT/LoRA adapter model rows from the Hub (read-only).""" diff --git a/packages/codex/mlx-agent/src/mlx_agent/inference_telemetry.py b/packages/codex/mlx-agent/src/mlx_agent/inference_telemetry.py index 97573ad..03d552b 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/inference_telemetry.py +++ b/packages/codex/mlx-agent/src/mlx_agent/inference_telemetry.py @@ -13,6 +13,17 @@ def _timestamp(): return datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='milliseconds').replace('+00:00', 'Z') +def _span(start, end): + if start is None or end is None: + return None + seconds = end - start + return seconds if math.isfinite(seconds) and seconds >= 0 else None + + +def _rate(count, seconds): + return count / seconds if count is not None and seconds else None + + class InferenceTelemetry: def __init__(self, clock=time.monotonic): self.clock = clock @@ -43,9 +54,12 @@ def finish(self, request, success): if request.finished: return request.finished = True - elapsed = self.clock() - request.started - elapsed = elapsed if math.isfinite(elapsed) and elapsed >= 0 else None + ended = self.clock() + elapsed = _span(request.started, ended) measured = success and request.tokens is not None + prompt_seconds = _span(request.ready_at, request.first_token_at) + decode_seconds = _span(request.first_token_at, ended) + decoded = request.tokens[1] - 1 if measured and request.tokens[1] > 1 else None if success: self.completed += 1 else: @@ -58,7 +72,11 @@ def finish(self, request, success): '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} + 'output_tokens_per_second': request.tokens[1] / elapsed if measured and elapsed else None, + 'wait_seconds': _span(request.started, request.ready_at), + 'first_token_seconds': _span(request.started, request.first_token_at), + 'prompt_tokens_per_second': _rate(request.tokens[0] if measured else None, prompt_seconds), + 'decode_tokens_per_second': _rate(decoded, decode_seconds)} request.buffer.clear() @@ -66,11 +84,26 @@ class RequestMeasurement: def __init__(self, owner, started): self.owner, self.started = owner, started self.tokens = None + self.ready_at = self.first_token_at = None self.finished = False self.buffer = bytearray() self.discarding_line = False self.stream_done = False + def mark_ready(self): + """Record when a model worker accepts the request, after any load or queue wait.""" + if self.ready_at is None: + self.ready_at = self.owner.clock() + + def _first_token(self, value): + choices = value.get('choices') if isinstance(value, dict) else None + if self.first_token_at is not None or not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return + choice = choices[0] + delta = choice.get('delta') if isinstance(choice.get('delta'), dict) else {} + if choice.get('text') or delta.get('tool_calls') or any(delta.get(key) for key in ('content', 'reasoning', 'reasoning_content')): + self.first_token_at = self.owner.clock() + def observe(self, value): usage = value.get('usage') if isinstance(value, dict) else None if not isinstance(usage, dict): @@ -80,12 +113,15 @@ def observe(self, value): self.tokens = pair def observe_json(self, payload): - if b'"usage"' not in payload: + """Read a streamed chunk: its first generated text marks the end of prompt processing.""" + if self.first_token_at is not None and b'"usage"' not in payload: return try: - self.observe(json.loads(payload)) + value = json.loads(payload) except (ValueError, TypeError, UnicodeError): - pass + return + self._first_token(value) + self.observe(value) def feed(self, chunk): """Inspect SSE usage without retaining an unbounded line or changing the relay.""" diff --git a/packages/codex/mlx-agent/src/mlx_agent/intake.py b/packages/codex/mlx-agent/src/mlx_agent/intake.py index 1f88112..763ba2f 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/intake.py +++ b/packages/codex/mlx-agent/src/mlx_agent/intake.py @@ -10,7 +10,7 @@ from .backends import ( 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, + port_downloads, port_files, port_for_files, port_for_pipeline, port_is_inference_only, port_requirements, quantize_rule, recipe_for, snapshot_files, ) from .huggingface import HuggingFaceClient, HuggingFaceHTTPError @@ -263,6 +263,8 @@ def _verdict(payload, tags, files, config, manifests, registries): hits = lookup(payload["model_type"], manifests, registries) backend = choose_backend(hits, payload["task"]["type"], "vision_config" in config) if backend: + if port_is_inference_only(payload["model_type"], backend, manifests): + return "unsupported", ["conversion_unavailable"], None installed = registries.get(backend, {}).get("installed", False) return ("convertible" if installed else "convertible_after_install"), [], backend reasons = ["arch_not_in_registry"] 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 c3ab7c4..40d3a4a 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/jit_serve.py +++ b/packages/codex/mlx-agent/src/mlx_agent/jit_serve.py @@ -529,6 +529,12 @@ def _start(self): if self.strata_children: raise GatewayError(503, "model_unload_failed", "A previous Strata engine is still releasing memory.") self._match_serving_plan() + if self.config.get("splash_project_cache_dir"): + from mlx_agent.splash_runtime import prepare_project_cache + try: + prepare_project_cache(self.config["splash_project_cache_dir"]) + except (OSError, ValueError) as error: + raise GatewayError(503, "unsafe_splash_cache", str(error)) from error self._check_memory() self._launching_memory() private = self.config.get("private_worker") @@ -1315,6 +1321,7 @@ def do_POST(self): 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) + self._measurement.mark_ready() leased = True connection = self.server.controller.connection(timeout=120) connection.connect() diff --git a/packages/codex/mlx-agent/src/mlx_agent/local_status.py b/packages/codex/mlx-agent/src/mlx_agent/local_status.py new file mode 100644 index 0000000..faa06ab --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/local_status.py @@ -0,0 +1,145 @@ +"""Local model status: where each model lives, how it arrived, its task type and duplicate groups. + +Built from one read-only :func:`mlx_agent.gguf.inventory` pass annotated by +:mod:`mlx_agent.taxonomy`. Discovery matches Hugging Face repositories against it. +""" + +from __future__ import annotations + +from pathlib import Path + +from . import gguf +from .taxonomy import annotate_inventory + +# Storage item kinds that are whole models; standalone assets are files, not models. +MODEL_KINDS = ("gguf", "folder", "ollama") +# Model parts that share a base model's name but are not a copy of it. +_PART_TYPES = ("vision_projector", "speculative_draft") +_WEIGHT_SUFFIXES = (".safetensors", ".gguf") + + +def scan(gguf_roots, mlx_roots=(), receipts=(), signature=True, limit=gguf.MAX_SCAN_FILES, + compare_assets=False, asset_exclude_roots=()): + """The inventory report with task types, ``families`` and ``local_models``.""" + report = annotate_inventory(gguf.inventory( + gguf_roots, mlx_roots=mlx_roots, receipts=receipts, signature=signature, limit=limit, + compare_assets=compare_assets, asset_exclude_roots=asset_exclude_roots, + )) + task_types = {item["path"]: item["task"].get("type") for item in report["models"] + report["outputs"] + report["ollama"] + if isinstance(item.get("task"), dict)} + report["families"] = gguf.families(report["storage"]["items"], task_types) + report["local_models"] = local_models(report) + return report + + +def _hf_cache_repo(parts): + for index in range(1, len(parts) - 1): + if parts[index] == "snapshots" and parts[index - 1].startswith("models--"): + return parts[index - 1][len("models--"):].replace("--", "/", 1) + return None + + +def _lmstudio_repo(location, kind, roots): + """LM Studio keeps ``//``: a folder at that depth, or a GGUF file inside one.""" + for root in roots: + if location.is_relative_to(root): + parts = location.relative_to(root).parts + if (kind == "folder" and len(parts) == 2) or (kind == "gguf" and len(parts) == 3): + return "/".join(parts[:2]), True + return None, True + return None, False + + +def local_models(report): + """One record per local model in an annotated inventory report.""" + lmstudio = gguf.lmstudio_roots() + sources = {**{item["path"]: item for item in report.get("models", [])}, + **{item["path"]: item for item in report.get("outputs", [])}, + **{item["path"]: item for item in report.get("ollama", [])}} + converted = {path for item in report.get("models", []) for path in item.get("outputs") or []} + groups = {} + for group in report.get("duplicates", []): + for path in [group.get("keep")] + list(group.get("redundant") or []) + list(group.get("members") or []): + if path and group["group_id"] not in groups.get(path, []): + groups.setdefault(path, []).append(group["group_id"]) + family = {path: entry["family_id"] for entry in report.get("families", []) for path in entry["members"]} + records = [] + for item in report["storage"]["items"]: + if item["kind"] not in MODEL_KINDS: + continue + source = sources.get(item["path"], {}) + location = Path(item["path"]) + repo = _hf_cache_repo(location.parts) + store = item["store"] + if store == "folder": + lmstudio_repo, in_lmstudio = _lmstudio_repo(location, item["kind"], lmstudio) + store = "lmstudio" if in_lmstudio else store + repo = repo or lmstudio_repo + provenance = source.get("provenance") or {} + origin = provenance.get("source") or {} + if provenance or item["path"] in converted: + acquired = "converted" + elif store == "huggingface": + acquired = "cached" + else: + acquired = "downloaded" + if item["kind"] == "folder": + quantization = gguf._mlx_quantization(source) if source else None + else: + quantization = source.get("quantization") + weights = [stored["bytes"] for stored in item["files"] if stored["path"].endswith(_WEIGHT_SUFFIXES)] + records.append({ + "path": item["path"], + "name": item["name"], + "repo": repo, + "store": store, + "format": item["format"], + "acquired": acquired, + "converted_from": origin.get("repo") or origin.get("path"), + "model_key": item["model_key"], + "quantization": quantization, + "task": source.get("task"), + "duplicate_groups": groups.get(item["path"], []), + "family_id": family.get(item["path"]), + "bytes": item["bytes"], + "weight_bytes": sum(weights) if weights and item["kind"] != "ollama" else None, + }) + return records + + +def match(records, repo, weight_bytes=None): + """How a Hugging Face repository is present locally. + + ``exact``: a copy of the same repository, or a same-named model whose weight + files total the same bytes. ``variant``: another quantization or format of the + same model name. ``absent``: neither. + """ + key = gguf.name_key(repo) + wanted = repo.lower() + same_repo, same_key = [], [] + for record in records: + if ((record.get("task") or {}).get("type")) in _PART_TYPES: + continue + if record["repo"] and record["repo"].lower() == wanted: + same_repo.append(record) + elif len(key) >= gguf._MIN_NAME_MATCH and record["model_key"] == key: + same_key.append(record) + same_weights = [record for record in same_key + if weight_bytes and record["weight_bytes"] == weight_bytes] + if same_repo: + status, basis = "exact", "repository" + elif same_weights: + status, basis = "exact", "weight_bytes" + elif same_key: + status, basis = "variant", "model_key" + else: + status, basis = "absent", None + return { + "status": status, + "basis": basis, + "model_key": key, + "copies": [ + {field: record[field] for field in ("path", "repo", "store", "format", "quantization", "acquired")} + for record in same_repo + same_key + ], + } diff --git a/packages/codex/mlx-agent/src/mlx_agent/mesh.py b/packages/codex/mlx-agent/src/mlx_agent/mesh.py index 166f08a..34b8711 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/mesh.py +++ b/packages/codex/mlx-agent/src/mlx_agent/mesh.py @@ -23,6 +23,21 @@ class MeshError(InferenceError): DEFAULTS = {"steps": 50, "resolution": 512, "guidance": 7.0} MAX_FACES_RANGE = (1000, 10_000_000) RESOLUTION_RANGE = (16, 4096) +# The smallest bbox side keeps at least two voxels of the 32³ sparse structure. +MAX_BOX_RATIO = 16 +# A centered GLB stores half of each extent as a float32 coordinate. +MIN_BOX_SIZE = 2**-148 +MAX_BOX_SIZE = 2 * float.fromhex("0x1.fffffep127") + + +def validate_bbox(bbox, guide=None): + """Check bounding-box constraints that do not depend on the selected model.""" + if (guide is not None or not isinstance(bbox, (list, tuple)) or len(bbox) != 3 + or any(type(size) not in (int, float) or not size > 0 for size in bbox) + or max(bbox) > MAX_BOX_RATIO * min(bbox)): + raise ValueError("--bbox takes three positive sizes, at most {0} times apart, without --guide.".format(MAX_BOX_RATIO)) + if not MIN_BOX_SIZE <= min(bbox) <= max(bbox) <= MAX_BOX_SIZE: + raise ValueError("--bbox sizes must fit centered float32 GLB coordinates.") def _settings(config): @@ -33,6 +48,11 @@ def _settings(config): type(value) is int and RESOLUTION_RANGE[0] <= value <= RESOLUTION_RANGE[1] for value in resolutions ): raise MeshError("model_unreadable", "The model config lists invalid mesh resolutions.", "Convert the model again.") + # Optional cascade settings: the token cap of the high-resolution flow and the lowest level it drops to. + for key, low, high in (("max_tokens", 1, 2**31 - 1), ("cascade_floor", *RESOLUTION_RANGE)): + if key in mesh and (type(mesh[key]) is not int or not low <= mesh[key] <= high): + raise MeshError("model_unreadable", "The model config mesh {0} must be an integer {1}..{2}.".format( + key, low, high), "Set mesh.{0} in the model's config.json.".format(key)) return tuple(resolutions), {key: mesh.get(key, value) for key, value in DEFAULTS.items()} @@ -43,9 +63,9 @@ 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, 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.""" + guide=None, bbox=None): + """The backend run for one image, plus TRELLIS.2's extra ``views``, ``guide`` mesh and ``bbox`` sizes; 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() @@ -61,8 +81,14 @@ 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 (views or guide is not None or bbox is not None) and config.get("model_type") != "trellis2": + raise MeshError("invalid_arguments", "--view, --guide and --bbox require a TRELLIS.2 model.", + "Drop them for this model.") + if bbox is not None: + try: + validate_bbox(bbox, guide) + except ValueError as error: + raise MeshError("invalid_arguments", str(error), "Use --bbox 0.6 0.6 1.2.") from error 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"): @@ -105,6 +131,8 @@ def plan_mesh(model_path, image, out, steps=None, seed=42, resolution=None, guid argv += ["--view", str(view)] if guide is not None: argv += ["--guide", str(guide)] + if bbox is not None: + argv += ["--bbox", *(str(float(size)) for size in bbox)] return {"backend": manifest["id"], "model": str(model), "out": str(target), "argv": argv} diff --git a/packages/codex/mlx-agent/src/mlx_agent/mesh_runner.py b/packages/codex/mlx-agent/src/mlx_agent/mesh_runner.py index 27b2fab..b565c71 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/mesh_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/mesh_runner.py @@ -22,6 +22,7 @@ def main(argv=None): parser.add_argument('--cache-memory-mib', type=int, default=256) parser.add_argument("--view", action="append", default=[]) parser.add_argument("--guide") + parser.add_argument("--bbox", type=float, nargs=3) args = parser.parse_args(argv) port = importlib.import_module(args.module) started = time.monotonic() @@ -35,6 +36,7 @@ def main(argv=None): max_faces=args.max_faces, **({"views": args.view} if args.view else {}), **({"guide": args.guide} if args.guide else {}), + **({"bbox": args.bbox} if args.bbox else {}), **({'denoiser_cache':args.denoiser_cache,'cache_memory_mib':args.cache_memory_mib} if args.denoiser_cache != 'off' else {})) result["load_seconds"] = round(load_seconds, 3) diff --git a/packages/codex/mlx-agent/src/mlx_agent/models.py b/packages/codex/mlx-agent/src/mlx_agent/models.py index 54604a9..27631e5 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/models.py +++ b/packages/codex/mlx-agent/src/mlx_agent/models.py @@ -33,7 +33,17 @@ "function_calling", "tools", } -DISCOVERY_ROLES = tuple(role for role, _keywords, _label in ROLES) + ("tool-use",) +# Discovery roles for taxonomy task types beyond text chat: (role, task type, label). +TASK_ROLES = ( + ("speech-to-text", "speech_to_text", "Speech to text"), + ("text-to-speech", "text_to_speech", "Text to speech"), + ("image-generation", "image_generation", "Image generation"), + ("video-generation", "video_generation", "Video generation"), + ("mesh-generation", "mesh_generation", "3D mesh generation"), + ("music-generation", "music_generation", "Music generation"), +) +TASK_ROLE_TYPES = {role: task_type for role, task_type, _label in TASK_ROLES} +DISCOVERY_ROLES = tuple(role for role, _keywords, _label in ROLES) + ("tool-use",) + tuple(TASK_ROLE_TYPES) REPUTABLE = {"mlx-community", "lmstudio-community", "unsloth", "mlx-omni", "mlxvlm", "qwen", "google", "mistralai", "meta-llama", "nvidia"} QUANT_TOK = re.compile(r"[-_.]?(mlx|mxfp4|nvfp4|dwq|optiq|turboquant|rotorquant|oq4e?|mtp|q\d(_k(_[ms])?)?|int[48]|fp16|fp8|bf16|\d+\.?\d*bpw|\d+bit|e[24]b|4bit|8bit)$", re.I) PARAM_RE = re.compile(r"(\d+(?:\.\d+)?)\s*b(?![a-z])", re.I) @@ -74,7 +84,28 @@ def name_ram_gb(repo): return round(float(match.group(1)) * 0.55, 1) -def classify(repo): +def pipeline_task_type(repo, pipeline_tag, tags=()): + """The taxonomy task type a Hugging Face pipeline tag names, or None for an unknown tag.""" + from .modality import detect_facets + from .taxonomy import PIPELINE_TYPES + + task_type = PIPELINE_TYPES.get(pipeline_tag) if pipeline_tag else None + # text-to-audio labels speech and music alike; the name or tags tell music apart. + if pipeline_tag == "text-to-audio" and "music" in detect_facets("audio", " ".join([repo, *map(str, tags or ())])): + return "music_generation" + return task_type + + +def classify(repo, pipeline_tag=None, tags=()): + """The primary discovery role; None for a task type no discovery role covers.""" + task_type = pipeline_task_type(repo, pipeline_tag, tags) + for role, role_type in TASK_ROLE_TYPES.items(): + if task_type == role_type: + return role + if task_type == "embedding": + return "embedding" + if task_type not in (None, "text_llm", "vision_language"): + return None low = repo.lower() for role, keywords, _label in ROLES: if any(keyword in low for keyword in keywords): @@ -82,9 +113,9 @@ def classify(repo): return "general" -def classify_roles(repo, enrichment): +def classify_roles(repo, enrichment, pipeline_tag=None, tags=()): """Return ordered role memberships and the canonical tool-use signal.""" - primary = classify(repo) + primary = classify(repo, pipeline_tag, tags) explicit = enrichment.get("tool_use") if explicit is not None: source = enrichment.get("tool_use_src") or "checked" @@ -145,6 +176,8 @@ def resolve_reasoning(repo, enrichment): def wiring(repo, role, host): + if role in TASK_ROLE_TYPES: + return "`mlx-agent task capabilities` → `{0}` backends".format(TASK_ROLE_TYPES[role]) preference = prefer_runtime_for_role(role, host or {}) return wiring_for_preference(repo, role, preference) @@ -156,14 +189,23 @@ def render_md(report): host.get("chip") or "?", host.get("ram_gb") or "?", "✓" if host["ollama"] else "✗", "✓" if host["lmstudio"] else "✗") + (" _(fast mode: name heuristics)_" if report.get("fast") else "")) if report.get("error"): return "\n".join(out + ["\n> ⚠ {0}".format(report["error"])]) - labels = {role: label for role, _keywords, label in ROLES} + labels = {role: label for role, _keywords, label in ROLES + list(TASK_ROLES)} + show_local = "local" in report + columns = ["model", "RAM", "reasoning", "fits", "license", "wiring"] + if show_local: + columns.append("local") + header = "| " + " | ".join(columns) + " |" + separator = "|" + "---|" * len(columns) for role, items in report["roles"].items(): - out.extend(["\n## {0}".format(labels.get(role, role)), "| model | RAM | reasoning | fits | license | wiring |", "|---|---|---|---|---|---|"]) + out.extend(["\n## {0}".format(labels.get(role, role)), header, separator]) for item in items: ram = "{0}GB".format(item["est_ram_gb"]) if item.get("est_ram_gb") is not None else "?" reason = "⚠ {0}".format(item.get("reason_src") or "") if item.get("reasoning") else "no" license_name = (item.get("license") or "?") + (" 🔒" if item.get("gated") else "") - out.append("| `{0}`{1} | {2} | {3} | {4} | {5} | {6} |".format(item["repo"], " ⭐" if item.get("trusted") else "", ram, reason, "✓" if item["fits"] else "✗", license_name, item["wiring"])) + row = "| `{0}`{1} | {2} | {3} | {4} | {5} | {6} |".format(item["repo"], " ⭐" if item.get("trusted") else "", ram, reason, "✓" if item["fits"] else "✗", license_name, item["wiring"]) + if show_local: + row += " {0} |".format(item["local"]["status"]) + out.append(row) out.append("\n_RAM is always an estimate; measured model-file bytes, when available, are retained separately as evidence. Add KV-cache headroom (~1–4GB) beyond weights._") out.append("_`reasoning ⚠` sources: chat_template > tags > name (weakest). Verify with a test-generate._") return "\n".join(out) diff --git a/packages/codex/mlx-agent/src/mlx_agent/music.py b/packages/codex/mlx-agent/src/mlx_agent/music.py index 2f37dd6..eda2c20 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/music.py +++ b/packages/codex/mlx-agent/src/mlx_agent/music.py @@ -20,13 +20,28 @@ ACESTEP_TURBO_STEPS = 20 TIME_SIGNATURES = (2, 3, 4, 6) REFERENCE_FORMATS = (".wav", ".flac", ".mp3", ".m4a", ".aif", ".aiff", ".ogg") +# ACE-Step's planner decodes a key as a note, an optional accidental and a mode, such as "F# minor". +KEY_NOTES = "ABCDEFG" +KEY_ACCIDENTALS = ("", "#", "b", "♯", "♭") +KEY_MODES = ("major", "minor") class MusicError(InferenceError): """Classified music-generation failure safe to surface in a result envelope.""" -def validate_parameters(caption, lyrics, duration=15.0, steps=30, seed=42, bpm=None, time_signature=None, reference=None): +def normalize_key(key): + """The ACE-Step spelling of a musical key, such as "F# minor"; MusicError for anything else.""" + parts = key.split() if isinstance(key, str) else [] + if (len(parts) != 2 or parts[0][0].upper() not in KEY_NOTES or parts[0][1:] not in KEY_ACCIDENTALS + or parts[1].lower() not in KEY_MODES): + raise MusicError("invalid_arguments", "The key must be a note A-G, an optional #, b, ♯ or ♭, and major or minor.", + 'Use --key "F# minor" or --key "C major".') + return "{0}{1} {2}".format(parts[0][0].upper(), parts[0][1:], parts[1].lower()) + + +def validate_parameters(caption, lyrics, duration=15.0, steps=30, seed=42, bpm=None, time_signature=None, reference=None, + key=None, keep_caption=False): """Validate generation settings without accessing weights or a backend.""" for name, text, limit in (("caption", caption, 2000), ("lyrics", lyrics, 10000)): if not isinstance(text, str) or not text.strip() or len(text) > limit or any(ord(c) < 32 and c not in "\n\t" for c in text): @@ -44,7 +59,12 @@ def validate_parameters(caption, lyrics, duration=15.0, steps=30, seed=42, bpm=N 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} + if key is not None: + key = normalize_key(key) + if type(keep_caption) is not bool: + raise MusicError("invalid_arguments", "keep_caption must be true or false.", "Pass --keep-caption or leave it out.") + settings = {"bpm": bpm, "time_signature": time_signature, "reference": reference, "key": key, + "keep_caption": keep_caption or None} 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}) @@ -64,7 +84,7 @@ def _acestep_planner(model): 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): + reference=None, key=None, keep_caption=False, manifests=None, registries=None, root=None): model = Path(model_path).expanduser() try: config = json.loads((model / "config.json").read_text(encoding="utf-8")) @@ -72,7 +92,8 @@ 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, bpm, time_signature, reference) + key = validate_parameters(caption, lyrics, duration, steps, seed, bpm, time_signature, reference, key, + keep_caption).get("key") 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.") @@ -88,9 +109,9 @@ def plan_music(model_path, caption, lyrics, out, duration=15.0, steps=30, seed=4 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.") + if not acestep and ((bpm, time_signature, reference, key) != (None, None, None, None) or keep_caption): + raise MusicError("invalid_arguments", "BPM, time signature, reference, key and keep-caption apply to ACE-Step models only.", + "Drop --bpm, --time-signature, --reference, --key and --keep-caption 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: @@ -107,12 +128,15 @@ def plan_music(model_path, caption, lyrics, out, duration=15.0, steps=30, seed=4 "--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.update(bpm=bpm, time_signature=time_signature, reference=reference, key=key, keep_caption=keep_caption, + 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)): + for flag, value in (("--bpm", bpm), ("--time-signature", time_signature), ("--reference", reference), + ("--key", key), ("--planner", planner)): if value is not None: plan["argv"] += [flag, str(value)] + if keep_caption: + plan["argv"].append("--keep-caption") return plan @@ -139,7 +163,10 @@ def _unknown_checkpoint(plan, detail): 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} + settings = {key: plan[key] for key in ("bpm", "time_signature", "reference", "key", "keep_caption", "planner", "shift", + "guidance") if key in plan} + # What the ACE-Step planner conditioned the take on: its caption, tempo, key, length, meter and language. + planned = {"planned": result["planned"]} if isinstance(result.get("planned"), dict) else {} return dict({"schema": "music/1", "backend": plan["backend"], "model": plan["model"], "duration": plan["duration"], "steps": plan["steps"], "seed": plan["seed"]}, - **settings, **{key: result.get(key) for key in keys}) + **settings, **{key: result.get(key) for key in keys}, **planned) diff --git a/packages/codex/mlx-agent/src/mlx_agent/residency.py b/packages/codex/mlx-agent/src/mlx_agent/residency.py index 5f14910..b5eaf07 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/residency.py +++ b/packages/codex/mlx-agent/src/mlx_agent/residency.py @@ -298,10 +298,12 @@ def configure_budget(self, limit_bytes, reserve_bytes=0, external_pids=None): _atomic_in_directory(self.root, 'budget.json', json.dumps(policy).encode(), 0o600) return summary - def reserve_execution(self, key, limit_bytes=None, probe=None): + def reserve_execution(self, key, limit_bytes=None, probe=None, diagnostics=None, overhead_bytes=0): """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.') + if not _bytes(overhead_bytes): + raise MemoryAdmissionError('memory_unknown', 'Invalid controller overhead.') with self._locked() as rows: row = self._own(rows, key) try: @@ -325,6 +327,7 @@ def reserve_execution(self, key, limit_bytes=None, probe=None): capacity = resident + current['pending_bytes'] + free else: capacity = limit_bytes + agent_capacity = capacity 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'], @@ -343,22 +346,37 @@ def reserve_execution(self, key, limit_bytes=None, probe=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])) + details['available_bytes'] = available if not _bytes(available): raise MemoryAdmissionError('memory_unknown', 'OS memory headroom is unavailable.', details) + other_reserved = sum(r['reserved_bytes'] for r in others) + headroom = max([row['headroom_bytes']] + [r['headroom_bytes'] for r in others]) + physical = (resident if row['phase'] == 'resident' else 0) + max(0, available - other_reserved - headroom) + details.update(agent_capacity_bytes=agent_capacity, physical_ceiling_bytes=physical) + if limit_bytes is None and physical < capacity: + capacity = physical + if max(0, capacity - overhead_bytes) < minimum: + raise MemoryAdmissionError('insufficient_headroom', + 'The minimum job memory does not fit available system headroom.', details) + # A fitting shared budget can leave a partial controller margin. + grant = max(minimum, capacity - overhead_bytes) if limit_bytes is None else capacity + amount = grant - resident if row['phase'] == 'resident' else grant + if probe is not None: + required = amount + other_reserved + headroom + details.update(required_available_bytes=required, headroom_bytes=headroom) if available < required: raise MemoryAdmissionError('insufficient_headroom', 'The job memory ceiling does not fit available system headroom.', details) - row['execution_bytes'] = capacity + details['controller_headroom_bytes'] = capacity - grant + details['effective_grant_bytes'] = grant + if diagnostics is not None: + diagnostics.update(details) + row['execution_bytes'] = grant row['reserved_bytes'] = amount - return capacity + return grant def shared_execution_enabled(self): """Sharing is opt-in through the existing host memory budget.""" diff --git a/packages/codex/mlx-agent/src/mlx_agent/resident_worker.py b/packages/codex/mlx-agent/src/mlx_agent/resident_worker.py index 09b9f2a..05d4dc2 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resident_worker.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resident_worker.py @@ -17,10 +17,26 @@ 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")) + "generate_runner", "describe_runner", "video_runner", "mesh_runner", "embed_runner", "segment_runner")) MAX_MESSAGE = 16 * 1024 * 1024 +def apply_memory_limit(runner, limit): + if type(limit) is not int or not 0 < limit <= 2**60: + raise ValueError('Invalid worker memory limit.') + if runner == 'segment_runner': + torch = importlib.import_module('torch') + if not torch.backends.mps.is_available(): + raise ValueError('The MPS device is unavailable.') + recommended = torch.mps.recommended_max_memory() + fraction = limit / recommended + if not 0 < fraction <= 2: + raise ValueError('Worker memory limit is outside the supported MPS range.') + torch.mps.set_per_process_memory_fraction(fraction) + else: + importlib.import_module('mlx.core').set_memory_limit(limit) + + class BoundedText(io.StringIO): def write(self, text): if self.tell() + len(text) > MAX_MESSAGE // 4: @@ -45,6 +61,7 @@ def watch_parent(): runner_model_cache._enabled = True cache = AllocatorCache() runner_model_cache._allocator_cache = cache + framework = 'mlx' with os.fdopen(args.response_fd, "wb", buffering=0) as response: response.write(json.dumps({"ready": os.getpid()}).encode() + b"\n") while True: @@ -73,11 +90,9 @@ def watch_parent(): or request['runner'] not in RUNNERS): raise ValueError("Unknown inference runner.") limit = request.get('memory_limit_bytes') + framework = 'torch' if request['runner'] == 'segment_runner' else 'mlx' 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) + apply_memory_limit(request['runner'], limit) cache.configure(request.get('cache_policy', {})) with redirect_stdout(output), redirect_stderr(errors): module = importlib.import_module("mlx_agent." + request["runner"]) @@ -94,7 +109,7 @@ def watch_parent(): 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" + "memory": worker_telemetry.capture(runner_model_cache.statistics(), framework), "cache": cache.snapshot()}, allow_nan=False).encode() + b"\n" if len(message) > MAX_MESSAGE: return 2 response.write(message) diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mflux.json b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mflux.json index 9d0d998..f222df0 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mflux.json +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mflux.json @@ -1,7 +1,7 @@ { "schema": "backend/1", "id": "mflux", - "version": "0.20.0", + "version": "0.24.0", "builtin": false, "package": "mflux", "convert": "mflux.models.common.cli.save", diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mflux.lock b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mflux.lock index 5b9a5fd..cd09c20 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mflux.lock +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mflux.lock @@ -5,7 +5,9 @@ annotated-doc==0.0.5 \ anyio==4.15.1 \ --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101 \ --hash=sha256:9f28306018cbd6d329e64a36d58256edff76dd996fe423bc957326e578b82a94 - # via httpx + # via + # httpx + # mflux certifi==2026.10.19 \ --hash=sha256:42d35340cc5b9ba78e818ddbff0c5b1c2b779de448a340fd1b989f5fa8670e1b \ --hash=sha256:035c1e85572b141bf1c3a3eff0e33a8eb74917522f2559075ff8d2fea780a1ae @@ -341,6 +343,7 @@ fsspec==2026.9.0 \ --hash=sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f # via # huggingface-hub + # mflux # torch h11==0.16.0 \ --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \ @@ -777,10 +780,10 @@ mdurl==0.1.2 \ --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \ --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba # via markdown-it-py -mflux==0.20.0 \ - --hash=sha256:5d60a278d67289be0da2e4ba0e8dcf938dd3c676a01c9064f64e3fb10e30767d \ - --hash=sha256:8fec3407bbc821cfba9cebd8ae55e35450b9429ec9b5445c9557aaeb78087de0 - # via -r req.in +mflux==0.24.0 \ + --hash=sha256:682368f04a1b2b0871144a8d57b7f7866e84dd0fd2bc3a765d1d57918e21237e \ + --hash=sha256:febb16b91a7f0aa2eb5f0d715d320ebed4d0c12f2a7eba9ad724d5180aede671 + # via -r .tmp/mflux-requirements.in mlx==0.32.3 \ --hash=sha256:0512049c81fded99aa6af2d039ae1fccf113ff1a5f2df937a596578aabd46869 \ --hash=sha256:097856504e6cf5944b9aaa7c2e1d5be0693428abd9175429cae3893e7ec2f681 \ 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 8d6d6d1..185b702 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 @@ -1,7 +1,7 @@ { "schema": "backend/1", "id": "mlx-3d", - "version": "0.31.1", + "version": "0.32.5", "builtin": false, "package": "mlx", "convert": "mlx.mlx_agent_ports.triposg.convert", diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-3d.lock b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-3d.lock index b161545..8cabd86 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-3d.lock +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-3d.lock @@ -31,36 +31,83 @@ imageio==2.38.1 \ lazy-loader==0.6 \ --hash=sha256:2f4b7824d6401958639008a0cae20c776b61dff619accd6890693e2de8260167 \ --hash=sha256:77253be3391b06124a0e16105bd663b6c54470af1a9ca8e1cf026f38d58ed056 -mlx==0.31.1 \ - --hash=sha256:0de504c1f1fe73b32fc3cf457b8eac30d1f7ce22440ef075c1970f96712e6fff \ - --hash=sha256:10715b895e1f3e984c2c54257b7db956ff8af1fa93255412794a3724fe2dd3b1 \ - --hash=sha256:195c5cb27328380287c0ffe9ef48f860ab75ec5d3dfce153d475dc2c99369708 \ - --hash=sha256:1ed1991c8e39f841d5756c0c543beb819763a2f80fba3f4b150bc6cad4d973de \ - --hash=sha256:20bd7ba19882603ac22711092d0e799f1ff7b5183c2c641d417dab4d2423d99e \ - --hash=sha256:3987282a1e63252bdd7c636138812c67316c3f7c7a7acad08e76c8843648a056 \ - --hash=sha256:4c4565d6f4f8ce295613ee342d313ee5ab0b0eab9a6272954450f8343f7876bc \ - --hash=sha256:69bc88b41ddd61b44cd6a4d417790f9971ba3fdf58d824934cea95a95b9b4031 \ - --hash=sha256:6cdb797ea31787d1ce9e5be77991c4bd5cbf129ab15f7253b78e09737f535fce \ - --hash=sha256:78f51ab929278366006ee7793dbb5c942b121542c793c33eb9b894a2ce8e27e1 \ - --hash=sha256:877ff2f98debd035b922825a0d7e7e1be0959fc5ca1d24cb5020a23e510ff16d \ - --hash=sha256:8863835fb36c7c4f65008b1426ddb9ff7931a13c975e0ef58a40002ae8048922 \ - --hash=sha256:8a63b31a398c9519f2bb0c81cf3865d9baca4ff573ffc31ead465d18286184e8 \ - --hash=sha256:931c9316ec47b45ec0e737519f4f4c90eb69cbbdaaecadd6dd2ccdf1a85d4e61 \ - --hash=sha256:9a6d3410fc951bd28508fed9c1ab5d9903f6f6bb101c3a5d63d4191d49a384a1 \ - --hash=sha256:9dc564a8b38b9aec279a1c7d34551068b1cc1f8e43b5ac044b56b2a9a4205195 \ - --hash=sha256:a7a9347df4dcc41f0d16ff70b65650820af4879f686534b233b16826a22afa00 \ - --hash=sha256:b2cf8502d9d64dc6851034fcd4a656cbb26be20c36f190f2971f4ac0caed89cb \ - --hash=sha256:b973506fd49ba39df6dc4ff655b77bd35ea193cee878e71d6ee3d1a951d2b3a6 \ - --hash=sha256:bba9d471ba20e050676292b1089a355c8042d3fc9462e4c1738a9735d7d40cfa \ - --hash=sha256:bc46c911cc060d2eaf21b9e24a1712dc56763b660b53631b9057a32ab1c0271a \ - --hash=sha256:d065625ab3101adcd7f5824297243fe40a0615099a06f5597ab67284483aa2f8 \ - --hash=sha256:d90b0529b22553eb1353b113b7233aa391ca55e24b1ba69024c732fcc21c5c49 \ - --hash=sha256:dec00ce7b094d6bc2876996291fd76c9e28326bc1a9853440903f2a06946ce1f \ - --hash=sha256:fa132def5b3d959362077521c80f1fc80f64c45060d2940dc1d66a1aa19ce5f6 -mlx-metal==0.31.1 \ - --hash=sha256:6c56bd8cd27743e635f5a90a22535af7c31bd22b4b126d46b6da2da52d72e413 \ - --hash=sha256:70741174131dbf7fdd479cb730e06e08c358eac3bf7905d9e884e7960cfdd5b8 \ - --hash=sha256:e7324b7c56b519ae67c025d3ced07e5d35bc3a9f19d4c45fe4927f385148c59e +mlx==0.32.5 \ + --hash=sha256:039a7eae14aeaccfcb0c321dcd928832dedb5a3c61c330b032b024502ae14b6c \ + --hash=sha256:060757235bc4272712ac3a81286ec32267547b25a3dcaeda1c4fe3102cd23b3d \ + --hash=sha256:0704ac1b83e9ff0cdcaf519416cde8bfa421819e84c66b8585abcb2fbd0648b0 \ + --hash=sha256:098dd442a2a60b5709cbbcce041d879af7cabcc6c1332dffbfb39685c4f787a4 \ + --hash=sha256:09b08919f439e442965ec15025758f6ead9ad2a32210abd6f83f19f43be9d582 \ + --hash=sha256:0ac1367d6f512080aa007ec4b0a8649c129576bf182b8247dc05840f096d6832 \ + --hash=sha256:0b07316aaf4e47e11a45eb455aaf2ccd20ca798921932e7373dac7790ccf1688 \ + --hash=sha256:0e14be0ec7b6fb45fcf5f497f09dae7f7dce8536bf1b70f6ad68effd3b3ea724 \ + --hash=sha256:150de7eb65396cadfc7acaa7f2761e0e51ec1d813c7a3879eb344c1cc9c8dbb9 \ + --hash=sha256:1c17b94187714f936f14e2cd45b16e43c9d33e9ecafd62d4788863e47448f24f \ + --hash=sha256:20601b7d5803c7211a58e1f83f7d32b1fd1cebc7b0151b42cf289aabb11a2751 \ + --hash=sha256:253ad3977533b512805f10fcfc310672c181a38cbe54e1aa0af09e11c676e7f9 \ + --hash=sha256:26a797f698860f7a21099650526168456bc1f812f79cd72e7f794e9444f57159 \ + --hash=sha256:29fa9d55be644ab3316b8b62515bbaa4aa92bdc2e5d7badcc455091aaae84f1b \ + --hash=sha256:2b73883fb95a190a232dfa365969ee8ba445858ac1ae8598b1ec84ff3a941f7f \ + --hash=sha256:2d6eb9f9253459670177caada380e6ff7bada9fadd86344ed02465d1d0fc6cef \ + --hash=sha256:2e5ea651dbea067f6fa880569fcc0248d85a7a282cebaade6e93c5d3e11cc4aa \ + --hash=sha256:35145f09dcecd752bdd9b8227d2c9941c0a4b2cea043496926d602194e4dd6c3 \ + --hash=sha256:35b862f3335eed0d5080c6b2b3fd3d97507a8666ee22a0aa327f04c755b9495e \ + --hash=sha256:371a832614e7cea843504b14e3d2fb67b52ceaf34751d689252cfd75c5f8e190 \ + --hash=sha256:37475d3789db7d1221cc5061d39f425e17c577cdd81c6f661cb7e1034d41808d \ + --hash=sha256:3796189c8f94b1bc4380ded80ea4edafb595ee76d54ee72710037fa0888c83ca \ + --hash=sha256:40656dd3d1ec7ddc88f2ba0d4572f64ab6577940feb71d8aa57abc396478661d \ + --hash=sha256:41923569acb1c42959738c3dbe1fab988a9d52897b2d428341549e7676b667e0 \ + --hash=sha256:4419ac13d3633b207fd1a7e3c7edf8d4cc6f1375c17d2138a2b2946890a8c317 \ + --hash=sha256:4a22f3548b4e1b9efb963317db0d35841bc0c306d001b3cd079db6a7ced0bb0e \ + --hash=sha256:4e073e8a5668bb957dbee82a571e7c8379bcd75f0a24a986228d661ab90bcd05 \ + --hash=sha256:4fbef7eda29f5688e7df12378ebf5c1428d40289d8348f93abf49bbeeadfcbd9 \ + --hash=sha256:4fe958073f2297fabce0657d0b232ca9133cc0cff33a01047f613797c5275427 \ + --hash=sha256:50bcc1738623f74adea32fe944dbf110f771571daccd440eef17b2e14e7978bc \ + --hash=sha256:50c966985b4125c3ee50ec35abd4b16d5415674c3b2538d82371d7426a4c24bd \ + --hash=sha256:541983fb54fcfb5e40ab253ade69c1966dba68e8ab1e00c7653f365686ca6a93 \ + --hash=sha256:56dd4e3768ad89947067f88068f077fd76fe6703d87336044bacb1ca76f3298b \ + --hash=sha256:5999037de85f29cf71c3fe76867c3bee60089886c0aa4242721226c4868b724d \ + --hash=sha256:5d7269c4472c5c784a979e0a9cbf7fa15727c959cf5dde279aa9cb999e80134b \ + --hash=sha256:60a68127fe8aabca3b2b3b470b4364bcf09aca7c665ea058d9175337a28e11e9 \ + --hash=sha256:63318a27bd104036ea21ab4c460e102f2e90778f61fde7df1b0ca93fad87fbe4 \ + --hash=sha256:690faae2b07aaed4971a2297a82e4af99615d33e98c9ba27eff5553d8c904f79 \ + --hash=sha256:6f0173bd5e58f71f8067d9784a9e9f0fcff797bc7820d698afc07482fd4674e1 \ + --hash=sha256:718a9bbc005bb0ef4c8f136c0d48dd8b5d5af1beff162354632217367ae7c02b \ + --hash=sha256:727ba0ea1ea3c7c564f9d92e867f7c65b5902130e9b0ece6a0e6835fbf266404 \ + --hash=sha256:7337663af055f7977b4f26f4d8914371e75b13dab9a06d618703c5c9f542992a \ + --hash=sha256:78b9c819d0acd486500fabba1a3db4aa87acfb92746b0b8c29ff9b31d792c75b \ + --hash=sha256:9025bdb69eddb265e681d5b242e0a482a108c6e7471276e9d60c8f68a1d526a1 \ + --hash=sha256:90acbc59515cbd12d3d5be8d992b0963b3985ced03ffabe00cfe8d502961691d \ + --hash=sha256:92a21a8009aa317f78c8a89dda8c0576b71c76a64b01c0be95a05492b024b0bc \ + --hash=sha256:93c80d4538914844905f2075025fe59b60c22ff74910d623ad3574246ee3bcca \ + --hash=sha256:95797593515f653db4f0af652cd1c430f7fdd7c5fd36bf7b285e0602f4271940 \ + --hash=sha256:964d9705ae5f2586cd1d75e92837d099d58fa107b5ef7e574d7c5e4db981db71 \ + --hash=sha256:9c2236c44ccc0e4cba97e82eba9744ef3d614800cae15687e7f3c8f9466139c9 \ + --hash=sha256:9fc6ef9db295a67aa23965577f758aa05ecbb69c653e9b549b9a3685c0cb8814 \ + --hash=sha256:a0756062c7b5a8be776be73e6c0c159a98125c020c920e2b246a01a3183163c0 \ + --hash=sha256:a52d79c62f56de5db34f56b0aa7e025fe53ca10254df669e5bf3e0997733d003 \ + --hash=sha256:a8762db42866be1195706caf50ca054371c72bd54ebdd12c2566a280c3085011 \ + --hash=sha256:aff082cff248b7e255f4d1579f834fc2803b3fb6bb7ea24a34044f96e30a3056 \ + --hash=sha256:b02704f5fcb2773f1c8f43e0741b5376811d4ec1d33e0956c7ccd7f4ebce2a4c \ + --hash=sha256:b7e459563ee0b76593e359656978115a78a871d33e0fae28398652a34ec2c336 \ + --hash=sha256:bc08ec8367cbf16f445608a65b488048ac742ff075743a2d587baa9a551ff116 \ + --hash=sha256:be51074f75764069460834c8c59802dd0167a082c2051389f6a5d4598ba25e7c \ + --hash=sha256:ca04f7777c7d25a627e7f3535766f722b4edff1e7fe5dc6dd929997f96467d36 \ + --hash=sha256:cd454f9abe21ede70b92a55a9eee178204bd7cdc6dcbf3cbe7732b5626d8cec4 \ + --hash=sha256:d3564cd8286642ce93d74f7a303899c15a45705278766a09c34fa155da4489c4 \ + --hash=sha256:da5d138c6f12a5573a2efb2c50acdecdf3fe4962d8a931de937df4e61b5640a2 \ + --hash=sha256:e36d69a23634d9a9be2ca73cee394481768fa79c0616f106bf8304869fb1bc93 \ + --hash=sha256:e6091f3132138f31305cffe08dd9ebcb9454646de966d2de0993b186590bd821 \ + --hash=sha256:e6cae3447cf0b144da19061261180f8bded958187aa58ead54722e2c16d2001a \ + --hash=sha256:e9992d0d82cb345b51b897b9dcbf413f63f579afd6687dd5beb20fa1bb641fe9 \ + --hash=sha256:ea93c8ee0bb945cfb0461138fc7736706576e7d321c209f34eb8e178fef240d2 \ + --hash=sha256:f0c3931d49b3e296206b5f4f3be415464f701528b27b10dc60e4ece977437b9b \ + --hash=sha256:f0c903e27f1e17662d973bae27f8dd751a6dbe873ac1b6a49e80f2c3fb6c851f \ + --hash=sha256:fdaf3bd9fc19ce9ed057613d514077623ae3c9a2d1a12bd3eaa101ebf180871c +mlx-metal==0.32.5 \ + --hash=sha256:4d1803083d1d04092ebb0fdbc1e204bbc6c4c1ddce3732a2409b33ff3b04e26c \ + --hash=sha256:4dc95a2960b5431ceb8f6a1bd7621449c09b71c43a4b864c92dbbf7ec8e01570 \ + --hash=sha256:b63657c86bcdce634536717b2415464da7b944ef09134cb96e90b3dc8ad043eb \ + --hash=sha256:c662c3543b9c5da2cbe121269cdf099d14447a48dac2d4d3e96965df3629c787 networkx==3.7 \ --hash=sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0 \ --hash=sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-audio.json b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-audio.json index 4cddbf3..742c478 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-audio.json +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/mlx-audio.json @@ -7,10 +7,16 @@ "convert": "mlx_audio.convert", "lock": "mlx-audio.lock", "ports": { + "source_separation": [ + "mel_band_roformer", + "sam_audio" + ], "speech_to_text": [ "audio8_asr_infinite" ] }, + "port_inference_only": ["mel_band_roformer", "sam_audio"], + "port_prompted": ["sam_audio"], "port_quantize": { "audio8_asr_infinite": { "include": [ @@ -27,7 +33,8 @@ "categories": { "speech_to_text": "stt/models", "text_to_speech": "tts/models", - "music_generation": "music/models" + "music_generation": "music/models", + "source_separation": "mlx_agent_ports" }, "remap_files": { "music_generation": ["music/utils.py"], diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/sam2.json b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/sam2.json new file mode 100644 index 0000000..fdd1cad --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/sam2.json @@ -0,0 +1,27 @@ +{ + "schema": "backend/1", + "id": "sam2", + "version": "5.18.0", + "builtin": false, + "package": "transformers", + "lock": "sam2.lock", + "ports": { + "image_segmentation": [ + "segment" + ] + }, + "categories": { + "image_segmentation": "mlx_agent_ports" + }, + "remap_files": {}, + "registry": { + "image_segmentation": { + "model_types": [], + "remapping": { + "sam2": "segment", + "sam2_video": "segment" + } + } + }, + "convert": "" +} diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/backends/sam2.lock b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/sam2.lock new file mode 100644 index 0000000..3b191df --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/backends/sam2.lock @@ -0,0 +1,890 @@ +annotated-doc==0.0.6 \ + --hash=sha256:361ca0950cc7082f53fa69e9328409f40a62c61e57e0a47e1825a08078a58a53 \ + --hash=sha256:7969bb69912085b2285849c0dcac0b4b374fd180c13cf10a87f284ffcf347bbf + # via typer +annotated-types==0.8.0 \ + --hash=sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7 \ + --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0 + # via pydantic +anyio==4.16.0 \ + --hash=sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb \ + --hash=sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026 + # via httpx2 +click==8.5.1 \ + --hash=sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37 \ + --hash=sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4 + # via huggingface-hub +filelock==4.2.10 \ + --hash=sha256:9479aaeb4db20b5a53e3da28493edd24720b66b8a0b84030aa56ccdf243d6857 \ + --hash=sha256:fcc3c0cb8bfe7f4b3bb0e231c04b15dbad068cb3c2515f343d8fde4dce93bd5d + # via + # huggingface-hub + # torch +fsspec==2026.9.0 \ + --hash=sha256:0f08147951c8cb31d844c3547d631053b127863b60be04cf06e121333ee0e2fe \ + --hash=sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5f + # via + # huggingface-hub + # torch +h11==0.16.0 \ + --hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \ + --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86 + # via httpcore2 +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 + # via huggingface-hub +httpcore2==2.16.2 \ + --hash=sha256:16051ae2a42f776007543f32de9349a317b23d2cbb4e1456b4bac0e88b87419a \ + --hash=sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2 + # via httpx2 +httpx2==2.16.2 \ + --hash=sha256:748b615678f07d8e3b183efe81ad13b655ca88bfc56ce4589219b2d442860574 \ + --hash=sha256:f05c13aade4c45dbf1c9060647a1058f0acad62398fad96e741269edb33d46f5 + # via huggingface-hub +huggingface-hub==2.4.0 \ + --hash=sha256:13a6158b9e3393d9d3f248ce99074d50c2a0a1449fb9d8e2f710751e2084c188 \ + --hash=sha256:42ecfd93ede47bdd333daebbf66a32d7bfe2e18752754fe4d2d4f98a0179d801 + # via + # tokenizers + # transformers +idna==3.20 \ + --hash=sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44 \ + --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c + # via + # anyio + # httpx2 +jinja2==3.1.6 \ + --hash=sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d \ + --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67 + # via torch +markdown-it-py==4.3.0 \ + --hash=sha256:7aa1511a46c39138de78d9eba92ce47e63124d8003fc98b3a351909e04239efa \ + --hash=sha256:91a58fa5b72c71a40cf7177250fd767480d7a2bb3ac426ccfb76fb90305fdaaa + # via rich +markupsafe==3.0.4 \ + --hash=sha256:007e1ffd9bf65bb6ee96df7b258fc632a4868dd5566037986c64781f35a36e98 \ + --hash=sha256:02fa4acbc6a3fc5c693c34d4dd8c1130b7fe99cc915181b0ddd6f72aeb296002 \ + --hash=sha256:03470d1a8268e692ecf79ecd565593e59d44219377a7ead61f1f1b94c1f7ff6b \ + --hash=sha256:04e7902ba80ee4bac1d50a549606527a1dcf0476cd81403db41099d3b60ec653 \ + --hash=sha256:051417f74bcaaefa316276e0ff723f541616ca51043d070da00249d9bddd3e3c \ + --hash=sha256:05295589e619b9bed252a86b532b8e27350abc372d18ba89b59375325e91ec1e \ + --hash=sha256:06de8ef6331f6e822c28d577dc8bf43fe398800477c49498f38fc38b67ff33fc \ + --hash=sha256:0764a13d34cae40db7bbf3a09b7e9b491bf4603e20b263a7a9d6b8e324975d0a \ + --hash=sha256:077293e425f28ec737dbcad442a71752e28f8ae27cde3d68acd1fb212091cd92 \ + --hash=sha256:0930db9bdc62d22944e10b066448bb65dc9abe9112880c7cab8da54db4284d5f \ + --hash=sha256:0cee7cb0f9a1b6892ea482237d9403b3d1b4603aee057d0ff01f0fac2d019a97 \ + --hash=sha256:0d9c47709875fdb321452056622e930c52afbc07a7d780762fbb8b4d91ce6fa4 \ + --hash=sha256:11935df9bf455ed0c04eb87bcd720f02b1fe5e02128a9430f23aed6f93336fc7 \ + --hash=sha256:12a606a492de952afcb43b59a14aaaaad120e708d3663dd0fdf2d738d427a691 \ + --hash=sha256:14bd2d845d62ab678eaf81da89d7b621b51756c72346745c1a594c09d49207a2 \ + --hash=sha256:15ba9e28640feef770374b116a6f019c21f52404aeabe516aa7f800587b98cfc \ + --hash=sha256:18a801868a884f216e784d7d14db2a4077143ce7610440aee2ce8f734e7cfcde \ + --hash=sha256:1c0df495a977d10460a94941799c72d5b5ab03d3858d949b55b5a66c8f371c99 \ + --hash=sha256:1caa2fa5a6184fb233153b35f654e6687bd555476f6170f29d8ee9be1a8b0af9 \ + --hash=sha256:1e1451fab512d1bcc3dc26988ec1edb0b82c2db909132872cd9356070a6b63df \ + --hash=sha256:1f1f9477e174582b0a1b583d60b66e1f2cf5d3fe12cee985e4aedf44766600e5 \ + --hash=sha256:2628d3a8cb648ecebb3c5d6b0a1052d400e4d8b7ac0fb786be8d285b50040d17 \ + --hash=sha256:26e9867520db70d37f7fb421a7f0d8adb40171011fb84ce869afa1a83370dfa8 \ + --hash=sha256:2a6ef68ae94aed8721934072b27a3b654ea2100b97e4ab864cf1489c90926fbc \ + --hash=sha256:2b2b1e18af909b448bb3cf9e3433366f7a8726271fc214e8b10e0f62a78c724b \ + --hash=sha256:2cb3dd71fc6be918ad4264346a8ed69485f9b7ed7bf35495d8e22807cd6b8bea \ + --hash=sha256:2d1b7d9308288661f56672b1b157d75fc536714d3638487bbea17b6318a78248 \ + --hash=sha256:2dad610540cb2e6272855c178f08ae9a1c7ac258a7fb71660553a5f104b42741 \ + --hash=sha256:2e5a7cd7fdd14fcb1ae5d7d8bf23d24fbd1daefd1fbca2580132e1ea75f098b5 \ + --hash=sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6 \ + --hash=sha256:340cbb1957ba99929cbf19a75626d36ba1ae21d1730b287d1cf7f824a20c4fc7 \ + --hash=sha256:34bdde374c5932765d7dc685c4a1d191a3207852d67e8e0a9eb6ea85156181f1 \ + --hash=sha256:353bd63081912ab8cfa6a0c7d185934cdf8426f04c618bba6bc4b394f2069b67 \ + --hash=sha256:387d8cd30e69b3f0a72877b9ae717033396404e19095b17fe89753a981fda44f \ + --hash=sha256:3882fb412298575bae3b9c46868251f15cc69307359f87bb1b382e53d6e5a2c9 \ + --hash=sha256:38fc55594dab834470b6733dead2ee9e3f657fb0608c769dcafa0ba5ab52f45c \ + --hash=sha256:396ec4e65cc889f69786b3b89478b471cee5a3bcf468b9d9bb03e1a30fb291fc \ + --hash=sha256:39dbacefc411633db5b4378b066a9aca70a3d7e2922c9e578d825f844026eeba \ + --hash=sha256:3a93d9616ddecfb393727a0041a562cf0b15a244e20f2bd25efc7949be4c4f17 \ + --hash=sha256:3d23795802fc8bd72534836d64489bbf0f67c088959091bdb22e10735a5107bf \ + --hash=sha256:434139499bb20b502ed3baa1f169e618f924a97e7a777fea1a49446d80106cf6 \ + --hash=sha256:436e3ffc6310d3c41878c601db29098102fe5d8a467c49da4a4125254e0980f2 \ + --hash=sha256:489505b03f692c3f376394e49194fa7a7f9e8558d6e293a7056a0032b0c38163 \ + --hash=sha256:4a540e2d3192792fc84eced57bef37851ccb2b41f73291bb17408eea77bcd278 \ + --hash=sha256:4a7cdc2a420ca01058182da4253329764d4bfa055564d1eced90e6ba1e8b1d3d \ + --hash=sha256:4bced6e2a6dba6a28f7dd3c6ce14df1b2dd495923f16ea484cad03decd463b2b \ + --hash=sha256:4cf3468d5ec187ffffcaca8e61929a37448f215dafc1386a12c750a72fe53634 \ + --hash=sha256:4e2c4809c14559aa7ef426f27fb35afbb38104c349a903bf8f3600456764bb38 \ + --hash=sha256:4ed644d75aa94a2baf7ec3a96eaa160ea58c742eb9d27c6506053c5c40fc84ed \ + --hash=sha256:4f6e0852a0283b1b1fd776eeb7b766a5f440b3e2bd31ab51af3b400585f3965c \ + --hash=sha256:5066b244f576f91afc8ee3ba029a89f99d39c79b1853fe9d39bea9f0afbec148 \ + --hash=sha256:5086f9975abb1ab531ee6afca1761e4b59a19b446f3f6522ed776963228cfe5a \ + --hash=sha256:50b5bedc9ed8a94fc8857a42ef4f84a81ea88f8d4f05dc8705fb23ee6d8dcca7 \ + --hash=sha256:52704c5d36eb6dda8866493decd61111fff86244c9b1ad225ca01b9e91e5970f \ + --hash=sha256:55ffd6ce583d97dc71dc92e930324c8c0d25aea7e3ade6ae54ef77cedb096811 \ + --hash=sha256:569d65055d367e3dcdf30c3f41119467b73d9ee9faf332bdf40402644f5ac08e \ + --hash=sha256:57f9947a7e57a081c1e3e0a2dd0d2dcf290a4531450e6f611e30084c222a7295 \ + --hash=sha256:5989cb26b2e1efc6a42216a9f6b5ee495ce5ace2e5b352a9af489976b32d1ee2 \ + --hash=sha256:5c22873ad1f0532ba40fa1727f3c0fc1bbbaab6d373d4cbe3f0dc74b2e2521c7 \ + --hash=sha256:5e8b3d0b18fd623afa12ecb2ce8d8becef69f9b5440c6330c7972200e0bb84b0 \ + --hash=sha256:61631e08084be9e21a8967ec3139c7616ed7c5e9368e05c86d1b39562c8a57b6 \ + --hash=sha256:64511c54db4e4987aef4c41923235927428729e8174c5dba488429be70a998ed \ + --hash=sha256:6669c1bf34080161ce49c589cc512ef24d4c704ac9d2b2d3667f519c60418378 \ + --hash=sha256:672d207103e6b16ca098611b0f9efad6bc00afd47c03d6ef62186495ca677dc0 \ + --hash=sha256:6768d67d1bce64270e0fdc2e69309d68b9b18ae56ddf6c711d168e9d051c2cac \ + --hash=sha256:6a45c3d514f2436064db00d7fc8778d888f0236ebfed649b53d13a59e69ad51b \ + --hash=sha256:6bd9e1788e15bfcf6a9082de42e30387e7b85d211ab21e57a939bb8cfaaf8d96 \ + --hash=sha256:6d2a9efe686f9de00d0d1ea32a4a5a86d558a2277501bd78d964214eab625e59 \ + --hash=sha256:6da83a088f8ef93b2d483a8232a4dbf4d69d3d8496b568a03c56becac43e1808 \ + --hash=sha256:7018d4af1cd272e847aa5917983ab5e83e4f6579f9dbfecd4a79c0ca80b144c2 \ + --hash=sha256:71f88e749ea29f67f21f3b36433c1dc54c7729ed2a6d9e2da2e0d9e0d7b224eb \ + --hash=sha256:737c9c3981998eba27f11786f84fddcbabc74068b72a4a1f454ea02094b57b65 \ + --hash=sha256:73e77980c7207854f00fc4e71fb1626868d5740ab4012623d55c7a99ad122a72 \ + --hash=sha256:799c39bdf5e2f1292fedd3009f7b3c9e760f10b2420cb9638d56920840ff6db8 \ + --hash=sha256:7a83aa6e4805df46fed18e989d3d16f86ef60cb50bbc8d9ce3a6be89165fbf6e \ + --hash=sha256:7d3391b2188d18737cb2fa147028b1096236eaa7e156446c650a489fa2cadc91 \ + --hash=sha256:7e1636da3d8dfc220b6dd10264db5f2b165e4888c4518594898fbe381049af8a \ + --hash=sha256:805c8b84534fa10891890f0e4be39f3a99e94615d93e8836bf9fa1fdca2feeb2 \ + --hash=sha256:811d02d5122171c1941357efd8f9bf4ffe907b7f0a1a4e729a880e4be3f46e3e \ + --hash=sha256:8138eb83940ec7299024d92d4dee45f601b9e6c5ffde9d25f4e35e326203c707 \ + --hash=sha256:83b3944fea42a8400edf92fd1770fb8d0d4f7de651353bd2d8525a92dba69a21 \ + --hash=sha256:849dd2bb0e5e4ab2b71c7191726a4a8d5aa8a610daa584728cbee0b710ddc4ef \ + --hash=sha256:8698d70a8081ee8c090dbb394768b5789a1da8b131b5499f89d071dd3cfaf6be \ + --hash=sha256:8781a792a070cf2bd1b86d3aa943894115faaba6e88122a7bf32d62072742453 \ + --hash=sha256:88d59b473bfb03259722600839af9bbd7fa13a2eb514beefeedb95997882f69a \ + --hash=sha256:8909c2f1c6dd65e054ac4b573a91c8384d1492281e55d82d159d653f7a13adf6 \ + --hash=sha256:8965520ac587c94a4ac48b729be3d8b8de00af39699b17585dfb599babe77977 \ + --hash=sha256:8b5d563170ff8ba3181caa967c99a3c804d1dedb702c7cb93a6a7c32247da978 \ + --hash=sha256:8e124f974786f831d6043728e38296969d3579db8896fe004682f5758e613581 \ + --hash=sha256:8f0fac8b13d14bb06c68195f849371924ae53dd7b1c00fed24650f704383b692 \ + --hash=sha256:9240187afb63d2f9ddc3e032c670356fe941f6e20662ea168a5dc3f1f317e1b3 \ + --hash=sha256:925f929d6b59a8b3f8b8c6ac363cd0af7eecc81efb3071770b3c6717c450a369 \ + --hash=sha256:9348cbb300d224fe3b89793262cb093504d4ae927004468463f745188a193e4a \ + --hash=sha256:9388003072b95f2f1e3fd908604194d653ba21330d811961a78b7da1a77e9e36 \ + --hash=sha256:9438a2648b2195980cb2dd8e53ed7b8df91319e2d0b70ae61a9e1d1bc8d3bec9 \ + --hash=sha256:94e4c421742086aeee4c32a506eec8859d7634aad943f7e6aacf70f813478768 \ + --hash=sha256:94f5407f7bc64fa6463906b896f9904beeeb7dd8dc116ee8e9056c8714ff9916 \ + --hash=sha256:971a3bbb75d97ae4e2e8f7d4834236f86f85f0c85e04ab2e191db1123b04f80b \ + --hash=sha256:9e227f3dbe6bde7491cf0a9965d00b88c6b1a4a95d11480ddf88bb96d397c19f \ + --hash=sha256:9e25feb9e330b63edb0278a0acdf85e50d0cb0fbf49c3084abbe4e24ae195346 \ + --hash=sha256:9f098115c247e11d138ab83a28fa0323c77015007ea2df73ba5fd714dfefd67c \ + --hash=sha256:a18f38cafc329bac5e3c2b96c765b4c96d3d103421ed22ab7988c1e3fce27464 \ + --hash=sha256:a4bbd2d87dd233b9fc5812160c3d0ffbe42edc22a26ce0469f58479ede633fe9 \ + --hash=sha256:a5fcffb37e602b0b3c1638a97746b9b96125caa9bcf6fa41d337a9261de231ee \ + --hash=sha256:a8e9f292fcda89b324f2f5c91d13f1424a153e40fc2756f38ee23b15835ff300 \ + --hash=sha256:a9f54054101545a9a9cccefddf54316aa6e4491611fcbef9e91b3b6bebec04f6 \ + --hash=sha256:aa2c838cc024642cc04c6854232f32b43e5e22833dd11119c1766c7873b8370d \ + --hash=sha256:ac0c7c9f1609b0c4c114feb1d7a3409564c7fb77e360bed9e97e5d25dfeaf868 \ + --hash=sha256:add96447a86d205ab616665d53b2950ee81083757f56e6ea833c8b2917646b46 \ + --hash=sha256:ae9dcb8fbe244cb82f8a6458b455b927a03685e383d9bacf1ea5ce180b96dc97 \ + --hash=sha256:b4a635a0487774f841cb1fb62e907e7195cc95bc761e053184b8acc3ceb20733 \ + --hash=sha256:b4d12837e0203bbace818ff4a7461afdcd78bcd782351cea148139180d7bcffe \ + --hash=sha256:b61687d0828e72bf5cda24a2690188f37170bd31c9359ac97e4e66569f120a16 \ + --hash=sha256:b807e598953730f82e4eae3bd30f6a122cf6b31c398c6b504c0e04c13c170429 \ + --hash=sha256:b8cd1f918b26fd7b1832ece557cc18f2d8747309ff8b3f0ef9d4250c5ad67a39 \ + --hash=sha256:b91cc9d336957239ff200f30097e6fea2dc6d6fb3c81e853eaa09eac904fd894 \ + --hash=sha256:bd3ce56ae2cbae3ba82b683bc425cd7e48d2ed8b10f3e818186b6f5646d9271c \ + --hash=sha256:be6cb0c799abb0e2ba3e618e6d28ddddf7e485f6c2ce938dfa237daf3905072c \ + --hash=sha256:befb4158af32106b9a93db8d6d1d1cbbd418c0d5aca0cabb7b1780abf0c89169 \ + --hash=sha256:bf053da3c97a4bc5ecfbb218cdd2983febd91c617be8367d139882aa11e490aa \ + --hash=sha256:c02e8f18bdedba082cef725942ac823b9b60656db07f7e265cb31618dfd00d77 \ + --hash=sha256:c1bc67752d5f21013cfe430df4062441714eab79f65a6a05e01505957e9c35fe \ + --hash=sha256:c61750fadcd119d0825bcb7d7d675dd264dcc89cc05292aab5be68ebdbb374ad \ + --hash=sha256:c90d5b3d4e944e065a301d741b3c1d784f6bd1f503aa68b4967e32b2ba313d85 \ + --hash=sha256:c9a7f43c0b202b334cc9184af09bb8f21d3a209e038efaf106936fb69e6b026e \ + --hash=sha256:cb96e6e088d6cf71c1ea977510948320234824cf226e32f6f6e044f7a9c82b34 \ + --hash=sha256:cf63c214fe879a65e69a386f915e36104fc84254ab141240f8854602d8e0be2a \ + --hash=sha256:d1aca03ede943eb80ab3d63bb082c84b7aab85ea83bd0fd0c200260945fb49d9 \ + --hash=sha256:d2e56fd3b00222722abfb3f5f0759ddbae4b90811b5ad4343c64030ad1bde70c \ + --hash=sha256:d5f93ebbeb8032d47e349328ec8662d973d9b05a70b3c35df1f91fe419b84749 \ + --hash=sha256:d882a373d8093c2941e01291b7ced96e9cbe4781da9a7751ca7e6c70385e5214 \ + --hash=sha256:d920abdfa61279ba1a2ef9484aab07bf03331f8c08a10120fa332353d06e6932 \ + --hash=sha256:da2af0d7aebfc2074080d72efa6ab8317c62481ef1f896f65d9999c1c01f4494 \ + --hash=sha256:dd8ea6ebee7aedbf7c749fa80521d9ccf1ba473e0d1e14805caafbaad281c889 \ + --hash=sha256:de8b364c423ef0a4bad9069657d617f9a5d2b2062457a89b1fa16ee199c399c1 \ + --hash=sha256:df1ae86ff54725a01fa1a0510b914ca53a161b7050be74f6204e24aded5971d0 \ + --hash=sha256:dff05cb7016dff1e9fd68f4122c127b65dfc59de5306cfb7ad92f956f230bee2 \ + --hash=sha256:e1a622f13970d81f95d0c72f9dc090dce9085fccfa4c9f2174377ee32bd15786 \ + --hash=sha256:e49fb0d1ce92cfa0cb198cc5b1b11cdf9d0638658e2a2db2687e39db7c87fc78 \ + --hash=sha256:e5c802729725bd07e2bc3ab7b76dc7e0bbfc53129d8f1eb1c002c24cf774717e \ + --hash=sha256:e841068dc0be4cb6dfb5c890eb88cbdcff2f4a332393c7ec94e8e618bd32c1a8 \ + --hash=sha256:e916035e3e9930cbdfdd10abf48861340221857f45509565898e012263f7b289 \ + --hash=sha256:eba154571c16e032112afac0dc2dfe9e63c2ceb7aedd07bb7eecf2ce26d4dd4c \ + --hash=sha256:f03460ff076f70ab595bb45a0205ccea1971443575b6920c52e755dec2b3fbfe \ + --hash=sha256:f0ec3b750b59375eab5b0fb2b9254810c00a3375be6d789899f1055a1d556237 \ + --hash=sha256:f291bcf42ae98eb5107edb162c3c998b4a89648fd8e99ed4cbd12705292788cd \ + --hash=sha256:f61efe1d2fe0de16158a5fe1d1cf3c14bdb6aecd54d8938fd26512c525c1f624 \ + --hash=sha256:f68edfc67aabac33708941f26f22a7b8e9f81429bc0cf249fcf7d66b23af8d19 \ + --hash=sha256:fa95848c929b6a75f6848d3c9793e59db365ee436776e57db835cdbfa79ba977 \ + --hash=sha256:fd9f8797427910198f95bced71ddfed61130d7e349213bfb8466c9c99e2c46a8 \ + --hash=sha256:fdb4ca07ab75ffadab4a8b135ad59cdbb3156b99310f3d565370da74a15d6bd3 + # via jinja2 +mdurl==0.1.2 \ + --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \ + --hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba + # via markdown-it-py +mpmath==1.3.0 \ + --hash=sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f \ + --hash=sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c + # via sympy +networkx==3.7 \ + --hash=sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0 \ + --hash=sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a + # via torch +numpy==2.5.5 \ + --hash=sha256:08f1b9abf1707fa89c125aaa17e78389c063fb20ce37a141b47821e996f4a1db \ + --hash=sha256:095113ee2ceab6a9501b184eff5ea806973d3a63d74a8cbc15e4911e754da9c1 \ + --hash=sha256:10396f7c5ebc37d8f3cbdec44e3313912ccc2dc5841cc905de5de54ebbe8e2d3 \ + --hash=sha256:178cb1eaed819b2cb4e398c554b0776d1499f307e30cb58b9bae1921de35dae6 \ + --hash=sha256:1c24be6a82f5f257afc4dbefde4c3b56dee02146dfed2be2811940e79576b237 \ + --hash=sha256:20145b11776d2f7570cd61351b156a51d3a341822282095baa819d87272bc710 \ + --hash=sha256:228e3d90e967495d61ddc79dd64e95267aae3bcf1b1c516a6186429106a0b444 \ + --hash=sha256:229743571f901a082f031f511dc4f926b4b4a714075d98b1ff2af62d836365ac \ + --hash=sha256:263b2aa236d752b18f90c5107137d24b2e3856d7db37725609f0ab5bcdb58881 \ + --hash=sha256:2a9c502cdb9a3050ac1686774624cc278658b11f72e11b971a3a8542d6ded357 \ + --hash=sha256:2abd39cfbb3d2af11e9bc8cc92b08cd089b0975fe9b1a30c8b7c740c67d397ce \ + --hash=sha256:2efb2ae4e0414b6bd636dde7235c158cd65dd52891ff64a320a4847a8ce7400f \ + --hash=sha256:31e5be6cd4b896004cb9e416741612ade530fc9a04bceca5219cf66a675113b4 \ + --hash=sha256:32dce94d74bb4d5bb058d65b0d9dad7fa61d07ff9375fd7695d8aa7ea82ee73d \ + --hash=sha256:3cedc2980b45794a6a2cfee9c8c3a80f04517082cc1d387e4cc895506c481696 \ + --hash=sha256:3d59ab8f6bfc4ffd29b0f558450e17922c1bc88459882e37726fbcd5834afbfd \ + --hash=sha256:410eab02c6718cb42d06ccbb8604659f3522d2ce06ae70cacd5042092659f5af \ + --hash=sha256:4302902ebf82d37f446664757be59db53587822c8b35f16368ca69fe66ec4315 \ + --hash=sha256:479e43c183049ec1a820eeb36549e493924f56b3e893a1d5865d0fff12abad47 \ + --hash=sha256:567994389edd2963b643d63d826138402a63401176f1daf84dbb3204eb838b39 \ + --hash=sha256:5cddc243c75114ba845f01b1f87aca1572dbf7b6c2d88636ed3e1d2bccd7f1bf \ + --hash=sha256:5e202d5facc9c0681834018062466d0b3eabd48c540c3570f72905c97f641a90 \ + --hash=sha256:704d819265e5d1064d932968e9ee85fff2103ccc78c05b878c06943ba27b8507 \ + --hash=sha256:7ca51125c76817de53473dae31ddc17213776472761bea9cca68a1a0037a4827 \ + --hash=sha256:7da9a248f149cfbb220c6da964a59c8d051d516704f7758acfb81eb382a05d97 \ + --hash=sha256:7e71ac4284c700afa654e2d15b1b174166710dca932f24045e5dc92001b5bda0 \ + --hash=sha256:7fb87c4bcc73850ef433a0c42f096b010d3d3d284e9d00028bb030b43df3d078 \ + --hash=sha256:824025655df929268bfe6b47ed91a00d14209a6f760847cf150be446829e1ce4 \ + --hash=sha256:84dfb1611993a3525b250c955b1e2ebab6ce0ed36e4ab4dd5746432dd362fb5d \ + --hash=sha256:86868185bf4b6c4e5a8628ac42cfa165cd9530266c731f7dd1d11b4ad7e7cd1c \ + --hash=sha256:919eb420662b0b4ba34889df503f3d5329775b0c1d5f7e5f5af4fba8315b1e30 \ + --hash=sha256:9c3e1ac3cd5d3329f4d38709ff4c21f0621bbe8779c094d6de8ec8347246fcdc \ + --hash=sha256:9f44875964889bd9088cf838d191b58c04088d10b4dc9b140e9da2431ecfbb60 \ + --hash=sha256:a0750f2156d53446caca85663d0b65d67214e1664b9050454a731ea1418d176a \ + --hash=sha256:a207eb88a18e30add597c366c1db7e79f48fc94084b8e7dbd0eefb95a645db12 \ + --hash=sha256:a3856a97e48ed8371c680fb04120b99fbcc29f2076ebe6dc3deb34f77947c5ca \ + --hash=sha256:ab3ff087826c49d07953d0219eb00663ce5b1a0ef0a6b757e1ac041b09387428 \ + --hash=sha256:ac910558645a4b006f70596b450712b8564730c1b2ac10291fcedd656d321ec0 \ + --hash=sha256:ad0c8b963f9281f2eb118e283eb61964c716c8e344ed8e8c309b49c586d41ed1 \ + --hash=sha256:ae2b8285d0b4eed24739c3ca9ec0fa424a0247489c01e1d5fe2815a599e11d33 \ + --hash=sha256:ae9cfe4e985139c5f2db69d4310de7348bd0abc02cfdc06991c4419065f6fdca \ + --hash=sha256:b3d328eebe0056c634878c251131d73d74e0c4af317a3aea718816d6fa0bb963 \ + --hash=sha256:b5d08742de581c9eb61102768ccca125a2982913de399611b56981a07278de74 \ + --hash=sha256:b6e30929e3443f46aa7be2749fb003fefbbad6b6a1e2168bf8850a55b657914a \ + --hash=sha256:b6ecbc1ff292c6799067d8064a4dd35cd25ba9d1a24aa41dd635d701691a49b5 \ + --hash=sha256:b7dd0287b6cdd35a27d5678a56b1bc508ff206c2b78b30b4821dd5c3197b393a \ + --hash=sha256:b96e9ee49ccbdb5676359f852a4497f7a9c5df6c377d8877f5330d6fd3ff42e4 \ + --hash=sha256:bea7de36bb304a850710c1dfbb35e7cdb9a005928106a3adfc6dc3a753469dec \ + --hash=sha256:bf6fa5a4d73b3a9699a57b8824d4863acde7241808a5305882222843537f02a2 \ + --hash=sha256:c48960d420e90cf305cb1fde0d4e6082cc90512cda87a9acf0b6e04e91cf4abe \ + --hash=sha256:cc6eb7502facce90349b4097a26821af224aaa0ab36e78304711cdb544352882 \ + --hash=sha256:d0c7c0dfabdcb7cde080b7c9ef301c7533e90110198b39965141a903c7dddcf8 \ + --hash=sha256:d64daa409e9b1ac818b0c59e47b005f802e130c8281e40c6a2f7e70c43f75e0f \ + --hash=sha256:d7d9be35d50366fe5ac28188364154c9e1e22ad1b977a06c9465c0680c8eeefe \ + --hash=sha256:dec156cda7322bcb1479ca992794705fe226a911b0ffebe13bff97fa1f3be63c \ + --hash=sha256:e0608d1585557b68dcb6a70a41654f7536567960afad79d91752d2863b242b68 \ + --hash=sha256:e0b87886bb45621d9279dad4ab9f2d154b5db0b019d378c107b8f71527b06a4a \ + --hash=sha256:e0cf407a83118faf0463ade48a4533982f1737c7c58aac29e08855f7d9ad2977 \ + --hash=sha256:e10e81d1db6c8fa507f61bebfd1ea383971dbc40c2005ed4db88fac5538b1ef6 \ + --hash=sha256:e99bf8a3d54693f2063fa6c7d13955d460a9f543d9dbc80e69a92da288259b28 \ + --hash=sha256:ef2a874cc70e2132c1c499268bdc34e211a715e481bc33c97b8a0190f2559295 \ + --hash=sha256:f5e8603f0892d1b848e12124863b5b29af72383ee9b25ddc6fe4967d4c1ee6ef \ + --hash=sha256:f6622e32cb46c60bee3b2c7dd7f5c22bdc86fcb8630336b4822ec81c3986111a \ + --hash=sha256:f82a7567c590ff266f8c18fd527a0662edde074de11be256541a656e274f2b05 \ + --hash=sha256:fd47c92e0d1e53f9498b1a30305072434fbae6b5a305cbcab514f959e9ce0fab \ + --hash=sha256:ff5c1ab54a637c0adcdbb69ad10e5c4f1c4dedba69c0d1de383249b70c36908f + # via transformers +packaging==26.3 \ + --hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \ + --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c + # via + # huggingface-hub + # transformers +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 +pydantic==2.14.3 \ + --hash=sha256:1054f237f4d4733e5a30e1e2333bd33a2004ab9ab1510bd053a9a31bb48e232d \ + --hash=sha256:3f7b347782ab7e4cf4c798496ae3a82787d9f21ec12676a9c564355eeef8daa8 + # via typer +pydantic-core==2.50.4 \ + --hash=sha256:0001d6920e3a5d92758cda460d6dc9f918a78ad6d5d092f1c8b5395e6b775356 \ + --hash=sha256:0574866e05f6adeecc520d87e87dd06210c0a51706341f6ef8421572f5a64444 \ + --hash=sha256:09450778e3ab58d3f565899fcfbf6c82926e31af29e28e799d1d50941316e0cb \ + --hash=sha256:0af56dbf8822ba9f4efcbbfdc15478f8b6fb08f1609860cb50aa2cc8476b3c34 \ + --hash=sha256:0b059a7968b1911be5a2d9a8234827ab0bef9d1e465d4b42da525894143550e8 \ + --hash=sha256:0ec20aca2b067369913716847f7dfe5f4dddf16a46965b7a70bbad5defaaba86 \ + --hash=sha256:0f87ae9db5ba8d8de40dcb93982cf8dd544e6552a80d3345af51941cc2146b80 \ + --hash=sha256:1239daaf063e62213ca1f34d96663900bd7510c42a786e843fd328af70e46445 \ + --hash=sha256:13b6dd62b5279f5b9d72f3bf918a35443ee8bd549241d9dc52d79a2c3b6d7016 \ + --hash=sha256:15bece43a02ad543c621c8305e67dedb5f27d378c5ba741e5a2c36523f8ef37f \ + --hash=sha256:16902a147b3da4840612164a5e67947104d63e978f7a57c395877a5e26690b9c \ + --hash=sha256:1afefe44ec042fbabfb4483ea258c04cf75ff4ff328d754f09b321fdaa232aca \ + --hash=sha256:1de7be9a66fc8536770481ab64a05aae5067c725f2b29a09543af00e6a417b97 \ + --hash=sha256:1e20cbde2b6deb33a51d08cd168454dd9044ec7d4474056f4d98d63f51578783 \ + --hash=sha256:2039e323acee9abfec1fb5f661776e8965fe5928f3b7f8431900a774cba5c317 \ + --hash=sha256:219114f8dcdcbe4720d82ef016b1287ce5a0a67d7c69ca61524eb72e82aac344 \ + --hash=sha256:22e874666bdbd96d6bf629d32cd8ab376fedf1fd62585b52a42b9fa9fa6c20b6 \ + --hash=sha256:23a9ba564b2db709ff16eca990992ba95a19069972b34bff87c81d4b473cd755 \ + --hash=sha256:25e7e1080f9f7ce7cd9d114b31470ce912771bd02f38c824721d3c35d312abff \ + --hash=sha256:26cb012c4b8ca9f847bd0ac15978bd3d0f55b050bfbe6c47355edfc7e945029b \ + --hash=sha256:29358a8ca74e7d81158d14e2b10c904bd18773293ae3788716c0626fe0342347 \ + --hash=sha256:2980a701be88f9128a7470189fa3bcda5387f76c298a6f8e000fc29eb2a6f4e7 \ + --hash=sha256:2a60ec2a57ac3ef3767e526e9bf706ec75aa3d79c4ea134d9d4fcf7c62a297a7 \ + --hash=sha256:2f42584e5785385f681163a42506cab0d51295e17599a648396c52a7046c1372 \ + --hash=sha256:2f5cc5bcb94063fbbdfd285a2b302da34af07491337c10bb35de1d5220fa1583 \ + --hash=sha256:2f6767122b37c780bb756a720a4eef2bc6a050a0a1143428834b3cbc89448bd2 \ + --hash=sha256:300753f71c73302e218124baf995f00058e085cd01869bd9610bcbd0bd4500c1 \ + --hash=sha256:30d4dc35bc0eea52202a90b3820445ee0072c820241bfa710a623a078c9b267b \ + --hash=sha256:32a991aebd165f227b7c7c60bb9d66c2c7de9c24308552da264c9938fde0f8d6 \ + --hash=sha256:32d6dda86383645ec428ea64dfc277036f5cbc60a72238eab28b91a3fdb9a113 \ + --hash=sha256:33b21f69540a12c2053cd1d95766d8bd9667a3897f7c712a642de8aa37eb0865 \ + --hash=sha256:39f489ce31272073e6e146f6781690f9c1ee8c126836e6403361ef91154d89fe \ + --hash=sha256:3a48a5254d15a0ad050318bfc7a9566d4ec740118187e8f303e47a6840287eb7 \ + --hash=sha256:3b8ee2589a082739c522c1fe4be227412fcf108b903abb6672ae2f5570558882 \ + --hash=sha256:3de6c2a4df2af0ac9ab4dc1488746fe8b1a90e27955d870d9edda3187d20092b \ + --hash=sha256:3e0b395648c6cb871bceb2906907f255dc876ec425f2d5b024e129985cea8519 \ + --hash=sha256:3e547ceec1da7382f01f9e13963023e53367a71802c88778b21b9645a077cbdf \ + --hash=sha256:41b2cd8b29dbb5a4c9828a70f50d1abfc92011115c813213d3a91205c6f731b3 \ + --hash=sha256:41f4f8ae714e4fea1d635880f8a1af715ecf080eed4d13c5b04a0f3210f9c61a \ + --hash=sha256:474f7e598c7902165662a5d5160d3fce31037890a2975a9871ebf7c05862300b \ + --hash=sha256:477af785d1846e4e96bf56983b92ea7553aaeccdeb8acdaa55c7cee9eda0ae32 \ + --hash=sha256:49eb1241a969a5994db6880c18c012b6cbe2340343d8f529721571806583e500 \ + --hash=sha256:4c29b8f2d6417069bb1f257e6b9113f5d64dc2f554cc200ea90b4fe2c5cdb733 \ + --hash=sha256:4eb15be588407148ef5937dc8d9256a71f6b115e6cddadb7aa20b6ee384680dc \ + --hash=sha256:4eda7e3fdef382b7d4492745988a5baaf6953923a337f8b9dde5f76fa8afde20 \ + --hash=sha256:523466eba8ee10f7480f3c2057563145978011c583130d2cc01fb1e7af808e25 \ + --hash=sha256:57fa0a9490785139f1a4e4f43891830d55dfe4408845c0c9cb5eff4aeaf75f69 \ + --hash=sha256:5b26e5f1793b96cdc60242bf38da86ff24a27a708aa396214cac9b534bf571c7 \ + --hash=sha256:5bc1811ef2b4d4ba63e8e452f6e332b6374bd1d2cbbfdf66826c8cb1f71dd10d \ + --hash=sha256:5c074454dc6d4f6f4ba6561a56bf33a14db7651d882a5a5321ba3ae8868e082d \ + --hash=sha256:5c1013647be741647895c102831dcf79c34209662dbb683df9efb864417ed7d5 \ + --hash=sha256:601fce6cea9ddeaa85329e12e7f351def38d233075f42a3012b9c48071b02941 \ + --hash=sha256:6118e5a5550e36582e19bac1a403711a748f9f18251b054c326d3db02aaa7a18 \ + --hash=sha256:629eae995185540406e3635df5d5cf1d44f19ea240840b835d3f44541ff694d8 \ + --hash=sha256:6348ad12fa741bcc9c2f173e99fbf27cbc038826d8c31a4a7d836eca27878ba2 \ + --hash=sha256:65376dbe1ab4dbc768ca2b72b7c13993562c035f5925fd3bc7ff9c8c585c515d \ + --hash=sha256:6619d49a89a15cd04334f76fec530c155923bfc60da74ff5d815a52629e1aa6c \ + --hash=sha256:664e74848c2f5fc27db8505fe24e1ecd3ac669412913bf73d176916f86cc08e2 \ + --hash=sha256:67f7cc397e1d5556a801d1cba74de0d27d827eb242e6c036c0ca273c745414f1 \ + --hash=sha256:696613a0c0e7b2b35356e389ba4195ce20cfe7a2fc2e992c87d974d973eabec7 \ + --hash=sha256:6c5687b59b6ba0f663c4f2f15470f68507d6b45ccd3a19ee6d224f95cbee70d8 \ + --hash=sha256:6c7d7b0b596319e9ce79ef96ce57a14054a2eac629c0588a0539187a218be799 \ + --hash=sha256:70dbc9f83c41f37a4faa62dae5203853847223a891da446f48ef2efcfd5df806 \ + --hash=sha256:71395a43da5584bb70556f380387e15f845c0dcf76373c1afbfa0025737576ac \ + --hash=sha256:71ade6d2e445839350d589ff99bbddfde16f3f32db28da5c894a09f99c8b2a03 \ + --hash=sha256:71e03d2ea1a221d020cfc5b6cc8bbbedef23a06704c70fcf4d0afb42965b22d1 \ + --hash=sha256:7210398a1607ad607dc73196e575b3148b00a333cbb602ddbe1b60ba54554f43 \ + --hash=sha256:7472c39480ccc11dda69a196d1b7c7a6b48eb6594b77f05d945599d3e47f731c \ + --hash=sha256:7646353a5a7c553c04167aca628e2550b538f492765b03ccf34321a560acc43c \ + --hash=sha256:76e0065998159244ff4c097a6c05ff08019c6fbb6e597a85846e73044f0215b3 \ + --hash=sha256:789a6453e5ffd18a7ab6b8c3a0dd8403053829197ec258ecb90c604c21ffcc99 \ + --hash=sha256:789f88dea57841cdebef392b5d6e90444d767117e9ff2e0d9172df5c9de6690c \ + --hash=sha256:7ac2769a7ddd661e07e26c12220adc31b17014c48234b2a5a88993b8d4109e09 \ + --hash=sha256:817953730e4a73a09008b010c4a42396cefe799616a22df2ac21d3927b3080cf \ + --hash=sha256:83d2beac85b757bfc404c5c0612df51c4ef33bbb7be65cf4a96b4da7cbc4ff4f \ + --hash=sha256:86c7c4615634b5c57a79770f5b738354e45ae219a89949aeae84f19169a05283 \ + --hash=sha256:8923fcd49f875e8a0448d7223d1fdf1a9973ae2d1f20d4158753ceb8909facd2 \ + --hash=sha256:8cceae48ae7f94990c2f4e36291e9ec9868735e8b0f19e4489a17b0422338466 \ + --hash=sha256:92f8f63df729061bb14558ed740e7a222f6e2aa6c2e6a5bcfb4e706676562049 \ + --hash=sha256:930ad463d3fb7a340d323bcc496ec32dae469ec9974c29ff569f19806b6b03b4 \ + --hash=sha256:94733cb447c37b0ce6f71b39ca1288d5f966a084023a5617b4cc35a852586859 \ + --hash=sha256:9be1cfe715ecaa060ffd5d599ef410b94ef2697a0eed4cee562f788a2aa2175b \ + --hash=sha256:a0c5210d038418a115e7cf8706bfa611bd14add2f5787274dba45aadca3155e0 \ + --hash=sha256:a2f8716344bbbd10443391be0b1f2003b34949e3c4e6883005c2bc498ab6b64b \ + --hash=sha256:a4bb174bd65f795c39ad6642d9d5bdc43351b306b7d0a654ab0d0abb38be245f \ + --hash=sha256:a70d5effebd81ebd8e15a8aabdc7980832367b2b00c36543bac378977004cc80 \ + --hash=sha256:a9ee990bf2cfbd81574c5d4f9f6c9d480a14b5b43d2c4f2ca13f4c6f48089394 \ + --hash=sha256:ab2822bcdcefb54d1e8ca29f5e3ec3afe160fb794bb3a3a73b09d11ed2671104 \ + --hash=sha256:ad92d255a165cde5f9882ff69699eaf5495e0a1f32e97566bbbb80f11e46781f \ + --hash=sha256:aead3b74b68396bf0feab5d57e050b730ded7df55853c1e048a87e00aaf033c6 \ + --hash=sha256:aeb2e123cbf978a905e9f55155c1b8316fbbfa7cf64d04521fe174bab302d100 \ + --hash=sha256:aec3c2d741a8e3ee993de7f95f37afb51e31b169c95dbd29da4cf6688f340914 \ + --hash=sha256:b0cdb655fbd1562c2dfc9986f9103a106f7058cd0915afc6e656d4b1d73f3387 \ + --hash=sha256:b26f39a5be3cd91a2035818be3d0ffdf5282c3e1f5f53d3b80b7024021acee52 \ + --hash=sha256:b2f2d13239487cecaae98c9f4d5904ad0737643cdf8873c88ec6a78b12214f20 \ + --hash=sha256:b300a30304c4c6aeab03ed06809819d9eceacdd58441d3c7dffe41edfd006091 \ + --hash=sha256:b42f64825f5d750228f08318a9bf4d723b7ecb4c472aedcb3013c3ec2dc1f949 \ + --hash=sha256:b67d38e8bb0ade7e6e84575e4bb153fab35b122458077273aeb08fdf12be9d2c \ + --hash=sha256:b867f9fd183d76977f810c626d539265183c25b2284762893a31e8d6cacc81c0 \ + --hash=sha256:b99bed995ed7c41515c11fe2beb86f8a6cc298e5537cae2f736de2f982f74ef0 \ + --hash=sha256:bd46bcc28ed85d3cf71581b42d90b4ebd1f2062f81879519fed209f8a4d1cfc6 \ + --hash=sha256:bee28aab5a580eec673f7b68dfa8dece3dd37bd207ef8d22fafe23a8e9837296 \ + --hash=sha256:c04e9d920e2674f54651fd260a15c5d2843526c73d5242ee4311325ddc9573b3 \ + --hash=sha256:c4c5a1770ecfe8bdb6c6f09f8d81ea4de04f7efb012fac1efa4ad315dccc1fd1 \ + --hash=sha256:c733087ecf7dde06b1d071679bfd5f3ba03266ba77814c1c7253bc48c9adedd9 \ + --hash=sha256:c813ada7a651193acda85b6bc1cf12abd4b37cd25c7c6a75d7183512cc374969 \ + --hash=sha256:c81d98e27d9d9261909dcccab1ba5d6ea1c98b0bb9470e368604614fd1d36ddd \ + --hash=sha256:c81e35862aced259177a537ce1a6264c3a97bae1ced184ca9dc10ea754563688 \ + --hash=sha256:c856e439a9d54d514e81a7131229ba151cdf81df7c408e0f6c89340e5003dfe2 \ + --hash=sha256:c9e70012926e97069cdd09221861aff412aa94e4cac2e019055cdb79485b150c \ + --hash=sha256:ca83a32b2b41653d89f09a3d22b770bca96da72273bef8f7a68136bdd1e8b823 \ + --hash=sha256:cbf0777d54672990b10cb8ca9b0523499e182d7e2ea39f86b138519a902aa601 \ + --hash=sha256:d49127f137f871cde3c5650af33bbbdcee02679dae76e020902fa106f522b8ae \ + --hash=sha256:d690121e80ab16e623415351ab24713534d4e500b3cadff216409cb6826063d4 \ + --hash=sha256:d6a166978f22f10cb91413f70519861605219346decf65bc79008f9257c94afe \ + --hash=sha256:d6e3485a5e5c01fb5339c1ee3d4b9e21e2135a2a9d44caafb71acd994487ee7c \ + --hash=sha256:d7d406709ae924cf0b08b8282ca2f0e1c90526911d93bc040557cbc83b74c55f \ + --hash=sha256:d8201c9f9035520cdcc7dcad383b039ec8123969b87e01cf27c3dd883c02313b \ + --hash=sha256:da779ae50b46f3f7d1e1b5f362fdc0ad376a49fd55f6f3122dc2b6149936cdf7 \ + --hash=sha256:dcf2c7eaaa4cafe8e49b017e5bb49e76e084ab6f0cd712ee4019c812b5cf68b8 \ + --hash=sha256:dd8bed00731a21e3106e5dd6bbffb6c775a2c0bbc7c0c9face534d830057bdc9 \ + --hash=sha256:df1c174796cd63eb6b139f7daf783affe1f3ed659605850e843b24764c21bfc5 \ + --hash=sha256:dfcf6e51000b34f7026322cd9ea9bc340d745637e27e0bbc22f504b4f6b967ee \ + --hash=sha256:e498900bfbf7ddddd862f810440c09e9b81674739e8a11d619b40906dccd4a9a \ + --hash=sha256:e512c75ec5cf4475c1aa50ad975ecdf253f4963b06e152e1a11edd6de4010753 \ + --hash=sha256:e5bd109d095aaae989a0463d5ef0fcc43e9ddd5de125e656d3c119a79e466380 \ + --hash=sha256:e6b4b08d09054310a4dc389fa61ee22a7a5a292cb23ab8a985136ca8828bf924 \ + --hash=sha256:e6da138a1ecc1341c8b788a5ee822670b03788e1f5decf7af9d461de6e508b8e \ + --hash=sha256:ea2f61b0bc12f3592288503961b764579dea0658852d96a0b3d823614d808821 \ + --hash=sha256:ed9c0b6f236648dbf30d57e9f57e1f74878caafa04833a19f529b5ba5164b7a8 \ + --hash=sha256:edbca8789fd10f0de534b660a6b4c71f1fd18039679c918dad392ab044bb37e4 \ + --hash=sha256:edc17549ab592e33cfcaf285f047bb75fcd98f608aa9309af1187fd736ce9641 \ + --hash=sha256:ef8a9ddb2e2a4eae4abb72dc0710eca6c2726779b0664bd10c3ce9fcfaed8c4e \ + --hash=sha256:f08ee8248aad2d054e5bc4c73554d4505464698f6d754f16198dbc5764e9821d \ + --hash=sha256:f1d62fb172db35c6478c9323da34ff37d1f3d37d7d44337a9d94ba8c583e5730 \ + --hash=sha256:f8fd23653a252cefabea11cd041efd7b80bdf403e43a36dea53f9cb0aaa21f0f \ + --hash=sha256:faa4e96385c820ce9d7f7a623486e23d4134ae3c9ba2071e44e0ab5a5a5002c4 \ + --hash=sha256:fb2bb5b557080da398b866408117d98fe9731a12334afd0cdff221b458cdc5dc \ + --hash=sha256:fc04affef30be98c1f36f0c422a4061ef618fdc1dde79f5ad5458dd496fecffa \ + --hash=sha256:ffb616d8d55965839670301dc3bae3abacff560a7e137a89056058a8a9da4d96 + # via pydantic +pygments==2.21.0 \ + --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \ + --hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c + # via rich +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 + # via + # huggingface-hub + # transformers +regex==2026.11.15 \ + --hash=sha256:03e3e31271f40e17f038e2810014a15b3e9b0950c8dac5ca910a3375ffc7b112 \ + --hash=sha256:058e6aa045d02985490d6622b986cb7db25929890384faf642233539439b804c \ + --hash=sha256:0a24a03358c429457365e600ad639ca6111b61a6275dd2756b4e02a792ec8477 \ + --hash=sha256:0e1cd15586d8afa75a925f1837ad347e61e3d32d9bbe0b0e63edb194b4d718c5 \ + --hash=sha256:0fa62f316890f582ec536aa4e993b8e3679d493b45d87de77b59e9df2325ad28 \ + --hash=sha256:119909bbaae76605210572042196de125e261037f915dec273af3b13fae65c06 \ + --hash=sha256:14feb390805c099e16bf7d37e5f574068eeac59c55336a76d0c1c6f7388b2510 \ + --hash=sha256:150f52dbcaf759d94c73a61dc31ccc60eb8a552acafa43e99e3ed76405173170 \ + --hash=sha256:19989877c737d3f648a6addd2cba45b2698b895cd15ac37388eb4af48b6af819 \ + --hash=sha256:1b34d1f63493a14845e70b72a53eb6b1542f63c44cb615ecf2fd68ec470ed489 \ + --hash=sha256:1bdcc15a5e10be63a05f6660ac28679f7ab50cd48d8a53c9328b030d2bc36060 \ + --hash=sha256:1c3c89fbbb08d2f75e36179d27154e867836656a9ab57616aaf8042c089c0d20 \ + --hash=sha256:1f05e0ea23b59b4a69e08498c6d2b58eb94719dd1966e97b73e4c1df1604db38 \ + --hash=sha256:20a86cd29d0323feab48ddb630cd7a48e66355504e6f4661329f11a931ed58f2 \ + --hash=sha256:20fb02e33c0e3c0a265d1b767c359c92d0df9292292c280ff67ace49e3e05467 \ + --hash=sha256:2388100a73abc2205b22b37f292661bfd1b221be0fde996e5e4f1ad272335471 \ + --hash=sha256:259abe2f6d24a87928715f758f55ad8bad58f02c950447cad42f46752cd96c66 \ + --hash=sha256:2ade9b8a36259183539c2eb82cc163ebaac1c38d14b4a30da9433295a4610dc0 \ + --hash=sha256:3232156a2b62a063f21aa155154e9cc943ca05eeae1d1a00dca7910c7cc1976c \ + --hash=sha256:34fd5add8dedc9b1de724049951e3835afddc21cc43e2741cdce6e1c92b88b81 \ + --hash=sha256:37f839f3a65368314d232376c754eee726ce4a34030c18247c76d238ef0ff249 \ + --hash=sha256:3a16f20dcfb68ad67bcc326757facad9b3e922693409c1c8c0deea3869e70669 \ + --hash=sha256:3b896ba13443de0048e7adc18632ea04a163641a77e977a010cc178f45b2352c \ + --hash=sha256:415ae840ea09b36e40fe602d65a84c2fec12a5bff845d932a6cc863c94a60b96 \ + --hash=sha256:42f9f6d0f3698f8b32cfe45b03cbd1830a7c203c9930fe15a1516ab9dda19c36 \ + --hash=sha256:481626b285706374a83f7ce569f2d1a0c640700a569d5ca54dba1d2668e03a04 \ + --hash=sha256:49ca893a13a1fb68fcec24ddf19e8c8dfb13fef697c1ed9d65711b5881d03180 \ + --hash=sha256:55db42bd5d8de089e2ab3e5ef48a83c013fa6eb81cc69e3e124556762b61cff3 \ + --hash=sha256:5607a1d49b4ef9d4a61de1a84902a09e4bd6619be71712d7c32381292ece5063 \ + --hash=sha256:5de7aeead82b6f40ec8524555bcbfdf21824ac97fd8e219598008befba56fc91 \ + --hash=sha256:66a49a7a63c0d77d0abe20edcc2d9466c8bb7b6a78d77c61871c768d6894f72f \ + --hash=sha256:681e92c0de78a5124e5a2e53788538c7acba4c8086d90623fc8101840583d40b \ + --hash=sha256:6dace895669eb1a4e4c02ffa6595fc4f02873de53f88fc21e70d41c4451220a7 \ + --hash=sha256:7011045ea36d3d642ae5207f2f80f0486f3495f6107326bc1d9a9c68b2ba9f72 \ + --hash=sha256:702089e41de56efc2cf4a690dcdc6c16e80833bb336eeee70b61c147bbb608f4 \ + --hash=sha256:7288fae326a15b1ea57c6b07225a1b6e0b68def5dbe7670651a35e4af61f785b \ + --hash=sha256:74e0b34c79b7c27e47d5929e565ab703a2149e89c5d50d99e06e33410ff29394 \ + --hash=sha256:76d4a6f241bd25e915ee292722cd06610d417689d11f9b1080fcb3693952fe6c \ + --hash=sha256:7848463f856954ca7991c076cad16734329596417e8ed266b1753ac09dc51097 \ + --hash=sha256:7912578bc32a25cde9648f35ef00e064464792980f43fa0a690501277e33042e \ + --hash=sha256:7ad141cdbb94ee48a9128b7118bf82b4df2b80f3b3caa22c36045da49e765481 \ + --hash=sha256:7ddabafb036132a20a8868637bfade62a98e5edefc574a52a91ce73961bc4e47 \ + --hash=sha256:7e0562f26fbe338b614691a3ab7040392b17c5ed1cb26e04032c9c1a874b0040 \ + --hash=sha256:808be73b8fcb4bc9f1996ce0dead2e49aaeee0cd11db0691f7b63eea7c0f8448 \ + --hash=sha256:81130194b54191230abe0bc57f15f70f18147d1c1c7c237f85e6a2425c1c0445 \ + --hash=sha256:81a0a8a2cecab76abc0fbb4d50f849d004a6128accb32d77109b92e8324d4272 \ + --hash=sha256:82abe7618741745c83a8cf3f0decc4605c3bb5a2b6e1bc5e7412be01ed10eabb \ + --hash=sha256:8721e5331ed77ddc52e86e2f3111840e58e3182bb049195fb632c441e8ed853b \ + --hash=sha256:88da86058c8ee083aa4ecb8c73bcbb46e388a34a4d548b73c834e77409a445a1 \ + --hash=sha256:8965eafcd408db9f44d7ae9debf052dfbad3748972510bc1c7e2d6241645a3bf \ + --hash=sha256:8a194defd67c120d7dfbd8459b9d98057bdcd03a8466b977d4d237a526c053a7 \ + --hash=sha256:8a3cb0651bc61270f3db6f733a277a9c1bea006ab9e0bf17d5a1ae36ea55def6 \ + --hash=sha256:8ba7541b08666615b6a5348fb9b2553dcdb7b6543089f318b77135667c3a7d43 \ + --hash=sha256:8f1c6871464b8da493f1f6828f1073725a0e9cbaacb1181a3334e65422c062ef \ + --hash=sha256:930c3244a9128d9546c50f9b03c01c22b3674bf006fd8830f2581e74bb5f1105 \ + --hash=sha256:958661f35e8f260fea889a9a4b42db0e2756f85971c8f7371d9059cfd1997f70 \ + --hash=sha256:95cf02fb529fdda5f9414303e3a9c0e1807bc4a00ae5b0ac214e66812fa175aa \ + --hash=sha256:99e61a4f575b3439de59de524bed94d144b22a11877407c81c702ce98fb4e1d3 \ + --hash=sha256:9a7d15f046e1ea4be447749462ad588effe5fe4c6e26271649385d89767d6e9b \ + --hash=sha256:9d304418a1de575974d85c1d3b4ca04b8371d18cbe55c9f953fbaebcb61741c6 \ + --hash=sha256:9dee9001be6426e1ca58411e5b77dbf297d89cfe4f1d3abe78595ecd912adba7 \ + --hash=sha256:9f94950edcaee1925e1e9ab11d1b458029d525f42b32eb8014c93ead19a22fdb \ + --hash=sha256:9fc28a3e2f8a1d6930dcdbefb31a80a82caa86619980f147d5bfeca30eae76b3 \ + --hash=sha256:a489fde13c1f49325ff8b3f4ac2138631edd093c02dfbfa31921cd8a478e8aff \ + --hash=sha256:a99aa9a355ebe33cc7a68e6651c20712f338fa57a8e8cebd782e4208543c3b46 \ + --hash=sha256:aafeb64c8569d69edfbf772feba49d2a001d3dca0f43e6a71e3735587ecb8222 \ + --hash=sha256:ac637b5ad26f868091fd939426dc5aa4b75237c2cc72196cab756a861abd107e \ + --hash=sha256:b22436339fe2fbf5e932f4b187dd1244663f05fe96d255c11c0cb1adaaa13576 \ + --hash=sha256:b2bc7e596c7fd46f303a42ce40b4e9c08fdd37f431695052acbee2e7ac7db6ae \ + --hash=sha256:b55f41770984827e083808892b25022b618a74e228887bdfc51574621dcf96e9 \ + --hash=sha256:b569ef5adf7dc957c24602b243cc3af6f4e8fc80d688d528ec478b4164f3f1b8 \ + --hash=sha256:b90e34261f0cc8ab174602a86bfc0b9b89825ba7fa05b996a1c97a1426730267 \ + --hash=sha256:b9aff8d89f72818646f192632c8249f3848a23d2c9527360de356d6025c5bcee \ + --hash=sha256:bbe5efba8a008a2a684173286be44b85b2cfc3427107662440903ccce6ec00d5 \ + --hash=sha256:befb860301d5c4736e0cdfabbbe2ea5887a7a643594f5e32c59d9a28f94a5f75 \ + --hash=sha256:c2873cc9abe12d0ad55e4ff5b616856c2e1b764f39d58e931038c06b37e5a7f4 \ + --hash=sha256:c487f7832327bbaf68d66b47e8848586e2d07ceb0028ba71a42cd5ec10585bd3 \ + --hash=sha256:c56b4d165feb65211571007f4b016d142b52fffb91b30bb4b38175cf3acd3917 \ + --hash=sha256:c58f6a5c1f080384010dfa8b33378fdc554b4ad96299d3dcbe362a7aaa50857d \ + --hash=sha256:c5d722af534ac05fea28db7876d45aaae1f8b6c504cf82a5ab27cd80e543e9fe \ + --hash=sha256:c6c868a2b8a2ca126930d2699b1a9ea7bd2134fe32107f8b5608d352783adce3 \ + --hash=sha256:c91d5a2a0b8fbf1e9deddbc2c59df93eb0de5c2314d9384969866cfaff6096c2 \ + --hash=sha256:c9d594f5785a4b0b7ad6a949ce8c799c67ee8105a6ffc8b4d5f4fd39f53bb9cb \ + --hash=sha256:ca38887219a8b77e56a8ded792a4ca6b0e78138c0ea0817de44022b0f73da3a7 \ + --hash=sha256:caeba590c348e1960ef9ce99589af4ab53b481f68b35ebd7f536abec2b072d54 \ + --hash=sha256:cb35195054f5eb044a9022a9d1c1799e0524adaa3f9ba936d2f134f3c7fa1d01 \ + --hash=sha256:cde33ba347b399d6b4f4c4ad03679a2570f945222596a56f9ca335e8ceea9340 \ + --hash=sha256:ce6afc332face9c5978dccf74c9bbee095d43b9794bc256f5acec1565c3e3fde \ + --hash=sha256:cfaf14e2080f5ced2699ebfbd5fd6cede980d331e14b2dc25235480bbd3de61d \ + --hash=sha256:d55cb1bb1f4309e7462324d70491d99b8cfe7af62c41a0e5bf42835f164fa2bc \ + --hash=sha256:d6ec7e29e62ebf93ab2a593d1137022b6025497d8610e5cb666d52f9ee5bb0ce \ + --hash=sha256:d7882799ee96f80e07cc0cc049e609ed3ccacf08fec81e47fdbbb06c0b8ea2c1 \ + --hash=sha256:d8d8f0dcd2583c0095e1764d591f35d9b974b6d98afec20b33512cc7778f389a \ + --hash=sha256:d96b2621622b040e5fec358cd9f45341845ab8517fd4d06d28088ea4a2fb2d5b \ + --hash=sha256:d9ab084d9c09cb95cce2e93bb59e19d55b98347e01649beeadf595d129111475 \ + --hash=sha256:da8dcbb501d6b3bc2c47db82fd1f3c78b7e980941db820e98562955e59c4a562 \ + --hash=sha256:dcb2f4ce63699ba4606d928ccf1e9f81557ba8b2ff263c52610253324856e199 \ + --hash=sha256:e3b0bac7b125515fee40b4df7069b2c3a89b4f722e159ccaaf78d44fe4fec261 \ + --hash=sha256:e4e69107963c47c35ca2d5f3c400e4dfe7eab5b107ab02830f712058e34e9846 \ + --hash=sha256:e53de052944732050022a81ea14f6dea25fbcfddc1c0c38def00e2ea3da1257a \ + --hash=sha256:e64ed603efac109f0ca26bb7e69ddcb5735aac463ca7dd15f7ca1eb7cf212f02 \ + --hash=sha256:e6cd01d3cefde448faacee38fcb1372e8e8687dd05a23d767e684b5081bcd0b4 \ + --hash=sha256:e7d10c6ac4e4a7cc65cc12ad61daa188c7fd16b32ba1919913b5da054ec6fd35 \ + --hash=sha256:e809decf3539660a2080b806d48a9b716b58b011a43f62f4272d256ec9cdf0c6 \ + --hash=sha256:e933aa169c3ec81518ce52b4db533eb3c7bfe5e55426a3e7f57742300263c4c0 \ + --hash=sha256:ece2f6ae38a8cd3eae07c8ca723af420351385294f989a76235a2b5bd465045a \ + --hash=sha256:f07145c751729bc78aa1a231018e4c98316c1e516514c09e926fbcb0d3b14ec8 \ + --hash=sha256:f11f0d4110a071aa6d8da35c199fdcc607271cb8c23babbf00aadc2d02b85b00 \ + --hash=sha256:f3758c3b1689ab778f3e1ae0f9aa4d22b8e4efc362e2e4cfdbbc5a208fed0bc1 \ + --hash=sha256:f48429378adb4a3e2c93ef4b551265350d712cb7cc5071538b7841a66da17014 \ + --hash=sha256:f5749d2d16ebd65e60ae1e1a2661c80ac1717e5cb2db50fb47cbeb0073108b5e \ + --hash=sha256:f8b2e49c18439db0a77533429d3ed7330671a262b8e82bdb6e9cf03b4ea91adc \ + --hash=sha256:fd90d5f29b349833fd692860ecdea1a9e6fd24127582b96234bfae15c1ae18ae \ + --hash=sha256:ff36007d31a0ba241f7bb09fd179febe221f52b3bf11798ab1b48e8b20a43220 + # via transformers +rich==15.0.0 \ + --hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \ + --hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36 + # via typer +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 + # via transformers +setuptools==84.1.0 \ + --hash=sha256:23657205b63d4d31395ab917815247f694aafad28cd21316bf5fd45a51048ea0 \ + --hash=sha256:5231689c6ac8156cd155cfb98c3fd6fb252c3e7e9bd3d78b64d3c55f132624c9 + # via torch +shellingham==1.5.4 \ + --hash=sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686 \ + --hash=sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de + # via typer +sympy==1.14.0 \ + --hash=sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517 \ + --hash=sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5 + # via torch +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 + # via transformers +torch==2.13.0 \ + --hash=sha256:024c6cc0c1b085f2f91f20a3dc27b0471d021c31ce84b81be3afdc39f791fd9d \ + --hash=sha256:092790c696a760c729fd5722835f50b9d81fd7c8f141571f3f3cf4081a8f664c \ + --hash=sha256:0ab4b69f3ee03a62a002cfbf77b1ca5e88aceb4ea64cb4388bb28f638ddbb045 \ + --hash=sha256:1e09d6a722504957c694faceca843acde562786df1144ebcc5a74075ec7f6005 \ + --hash=sha256:2bd30b6b730d987fa386ce3898933762c5cb8cc82eb0535211d787cc3ce2dfeb \ + --hash=sha256:2fe228aba290d14b9f31b049be550dbd469c3fd3013d7a19705b30454da97027 \ + --hash=sha256:31061ff56ed8fbf26c749806905aeb749ebeb819810fd5d52508aa5afd90dddc \ + --hash=sha256:33449899ce5496c1b84b4853179d94fd102028ae1407314d9fb956bb79e70d09 \ + --hash=sha256:49b58f1e2c52440abb6f17c28f0335fe6c6d01ad1a7f55b0183b81e4b34d64e6 \ + --hash=sha256:49f1ea385c754e54919408a9bb3b5a72b0b755bbe2c916c1d6f70afbec4908a2 \ + --hash=sha256:4f8573e3ce9ebcd53fe922f01077a6085ccdfbe5f12fd215883a9d87d7a744fd \ + --hash=sha256:572df8be8ffb4599c88cbd6a0726f1f854f4da65d2e3c09f0e2c2283333cd6d4 \ + --hash=sha256:60fcdcb2f3876e21146cb4524ef06397d727ca9ad5f020818547e25075fe3cb7 \ + --hash=sha256:796633c4cdf0fe2cdced72d8f88f22e73dbcfce83132763162f6d4bff13b820b \ + --hash=sha256:94f0de129916f77b8dc2c7a8eff644cfeddfe59e39c9f55e9f6e17543410281d \ + --hash=sha256:a0d8b11f16a48d60e2015d8213aa0390744cbebb98e58b62b3514dddc656e330 \ + --hash=sha256:a3893dc2da0a972a8ca5d698c85a9f967559ac5f8ee1797b77408aa8734d073c \ + --hash=sha256:a3a9a21312872af8a26950b2c15680335a386a1f56ed03e780653d78b9607e9e \ + --hash=sha256:a7de8a313090dc5c7d7ba4bfe5c3be222528f9a4dba1acc83bddb1157360c4b8 \ + --hash=sha256:c28def70706c2f9ecc752574766e8ae4da9b810ab6676b611166761a78a9f1e1 \ + --hash=sha256:c78b7b4d04461855a764cf01bae9a462bb88bc93defcfa11235cbc8fdf3e12c4 \ + --hash=sha256:cc26eead4cf51d0b544e31e364dcf000846549c273bd148936fe9d24d29acb92 \ + --hash=sha256:d849b390e07d8d333ce8ecaf91b273c656c598379a19c9acf1318a883f6b391c \ + --hash=sha256:e76f9bcecc52b8ff711239a2f7547d5353df95878ab232f0773c1d95928b92f8 +tqdm==4.70.1 \ + --hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73 \ + --hash=sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4 + # via + # huggingface-hub + # transformers +torchvision==0.28.0 \ + --hash=sha256:028a3d481b37d785605620d7cdad897064c5a55bae2aa1f2658766333e291940 \ + --hash=sha256:09ce8f56e81f19b9c378ae7bb109f83f6659fd8bc3cd14241a48e4af46e9ed49 \ + --hash=sha256:2a1ef4b6f4bf5828b48cfad97372c8982db906830884b2868ba5c3df937a7d81 \ + --hash=sha256:3557cc7b539f46dabcda2b6f2b14017ccbeef024de466d4fc5835fc3f287f769 \ + --hash=sha256:36beb0782976906069ca03d4c9aacaf4b6b838b06ed6c20960ea9c51cce7acdd \ + --hash=sha256:3bd9dba55224a9db4a2d77f6feaa5651770d8c8e86d3d0ddb0fa6bec54c8712b \ + --hash=sha256:46f581979c010ad6da6bd85ee602aa707e1ff44312670223b7a0ee517ad06d47 \ + --hash=sha256:546fd85345cf8652f6cd099d4f9884b0ca5c2f3fae78689a21dd2f35ea6b622f \ + --hash=sha256:5a38bc6da3d72621be003400b66f66a2b4c6d644fde05f680c2cb7ca8cf8dd6c \ + --hash=sha256:5cf78ebc401ce64ae19b8c55de866bb836797d559a4de9c25ccbe74cfa642d3a \ + --hash=sha256:62c7d110f86a039245b587e4fae60278c649f3bd42ff79cfbc1178eca4e72542 \ + --hash=sha256:6dfb0f45e2b4ceb4e76f158c3fbb5f44387099f3c466e3423a09ab665a194aba \ + --hash=sha256:7e80f543b22503d9415e126db5f0ff3917036925e38560ee6b9ae38c571a4002 \ + --hash=sha256:7e9dd6f60d6e15f8dc27d4f877fdb6002fc70d70272412135f1c2ff9cfa08d3b \ + --hash=sha256:7fad44dc9582570c7d92c4487d36ac46998f40cc39b438e8b8f5111a935ce4e8 \ + --hash=sha256:83fe6c020866a85acd7d97deccc45ff11d66daf42916d04396a4309c66c0ccb8 \ + --hash=sha256:87dc16b2df427c1318ad335f1e2be2b3b15b2cf20f7934c83b0505a48425ee5d \ + --hash=sha256:89f90e29b0966352811b12589f3a3c61943bf2bb9487b9d7bbec10efb1096bb5 \ + --hash=sha256:904cf89af220f8c6b2ed0296bb5065b474ce43b77558e48b2bf9de8b0ba17204 \ + --hash=sha256:9a45ea67235d965ef52187130d20002a4de20c54ea3d927a24286961d268dc37 \ + --hash=sha256:ad7b3a439265cc3739a4ab5b4c998c0e38ea99c0ee7ca4dea35c5d0b099ec237 \ + --hash=sha256:bb6dd6918460ed89cc7644adcc2402991474d6933cf1ce92b390641cb233fddf \ + --hash=sha256:d483b4aa3f5237569053f749cd1a2b5bb548ca456e40461a5dd087f21149d123 \ + --hash=sha256:e9f54c30cd52e3ef7fd034cc69b7bb7e0964e1c8f8743e018ab92e95b40f9eee +transformers==5.18.0 \ + --hash=sha256:d79e5a515a572ee3deb33eb0d578be47d91e70c75d54cf21bf6eede6edef14a9 \ + --hash=sha256:d89c206e42e841af7cd314b3d2b21c03e977d819cdb4aef65ada048769a644df +truststore==0.10.5 \ + --hash=sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd \ + --hash=sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c + # via + # httpcore2 + # httpx2 +typer==0.29.1 \ + --hash=sha256:00dbc549c13428bec1be55fe1f4d0fb8c6637a310e4f178ef14abe9534ee7b58 \ + --hash=sha256:ab6eb3880bf67ce96147734717f9ec333c06f66e361f3ea947d0be43da39f242 + # via transformers +typing-extensions==4.16.0 \ + --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 \ + --hash=sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5 + # via + # anyio + # httpx2 + # huggingface-hub + # pydantic + # pydantic-core + # torch + # typing-inspection +typing-inspection==0.4.5 \ + --hash=sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7 \ + --hash=sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39 + # via pydantic diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/__init__.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/__init__.py index ef96be5..6866e9f 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/__init__.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/__init__.py @@ -1,5 +1,5 @@ """Qwen-Image 2.1 through mflux, with an optional LoRA merged into the transformer (mlx-agent port).""" -from .qwen_image_21 import generate, load, merge_lora +from .qwen_image_21 import generate, load, merge_lora, prepare_references -__all__ = ["generate", "load", "merge_lora"] +__all__ = ["generate", "load", "merge_lora", "prepare_references"] diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/convert.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/convert.py index c12136b..a85f829 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/convert.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/convert.py @@ -1,5 +1,7 @@ """Convert Qwen-Image 2.1 (diffusers layout, already in the cache) to an mflux MLX directory. +The output keeps the Qwen3-VL vision tower and processor, so it renders from +text or from up to ten reference images. ``--lora`` merges a PEFT LoRA into the transformer first (``--lora-scale``). Nothing is downloaded: ``--hf-path`` and ``--lora`` are local paths. """ @@ -17,12 +19,12 @@ def convert(hf_path: str, mlx_path: str, quantize: bool = False, q_bits: int = 8, lora: str = None, lora_scale: float = 1.0) -> Path: import mlx.core as mx - from mlx import nn from mflux.models.common.config import ModelConfig - from mflux.models.qwen21.qwen21_initializer import Qwen21Initializer - from mflux.models.qwen21.variants.txt2img.qwen_image_21 import QwenImage21 + from mflux.models.common.weights.loading.weight_applier import WeightApplier + from mflux.models.qwen21.variants.edit.qwen_image_21_edit import QwenImage21Edit + from mflux.models.qwen21.weights.qwen_image21_weight_definition import QwenImage21WeightDefinition - from .qwen_image_21 import MFLUX_MODEL, merge_lora + from .qwen_image_21 import MAX_REFERENCES, MFLUX_MODEL, merge_lora base, out = Path(hf_path).expanduser(), Path(mlx_path).expanduser() if not base.is_dir(): @@ -38,24 +40,24 @@ def convert(hf_path: str, mlx_path: str, quantize: bool = False, q_bits: int = 8 if index.get("_class_name") != PIPELINE: raise SystemExit("{0} is a {1}, not a {2}.".format(base, index.get("_class_name"), PIPELINE)) print("[INFO] Loading {0}".format(base), flush=True) - model = QwenImage21.__new__(QwenImage21) - nn.Module.__init__(model) - Qwen21Initializer._init_config(model, ModelConfig.qwen_image_21()) - weights = Qwen21Initializer._load_weights(str(base)) + model = QwenImage21Edit(model_path=str(base), model_config=ModelConfig.qwen_image_21()) if lora: - count = merge_lora(weights.components["transformer"], mx.load(str(Path(lora).expanduser())), lora_scale) + weights = model.transformer.parameters() + count = merge_lora(weights, mx.load(str(Path(lora).expanduser())), lora_scale) + model.transformer.update(weights) print("[INFO] Merged {0} LoRA layers at scale {1}".format(count, lora_scale), flush=True) - Qwen21Initializer._init_tokenizers(model, str(base)) - Qwen21Initializer._init_models(model) bits = q_bits if quantize else None if bits: print("[INFO] Quantizing to {0} bits".format(bits), flush=True) - Qwen21Initializer._apply_weights(model, weights, bits) + components = {component.name: component for component in QwenImage21WeightDefinition.get_components()} + WeightApplier._quantize({name: getattr(model, name) for name in components}, bits, components, + QwenImage21WeightDefinition) + model.bits = bits print("[INFO] Writing {0}".format(out), flush=True) model.save_model(str(out)) config = { "model_type": "qwen_image_21", "mflux_model": MFLUX_MODEL, - "components": ["transformer", "text_encoder", "vae"], + "components": ["transformer", "text_encoder", "vae"], "max_references": MAX_REFERENCES, "quantization": {"bits": bits} if bits else None, "lora": {"file": Path(lora).name, "scale": lora_scale} if lora else None, } diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/qwen_image_21.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/qwen_image_21.py index baaace5..2c157d0 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/qwen_image_21.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mflux/qwen_image_21/qwen_image_21.py @@ -1,12 +1,17 @@ """Qwen-Image 2.1 (Qwen/Qwen-Image-2.1 diffusers layout) through mflux's implementation. -mflux 0.20 loads no LoRA for this model, so a LoRA is merged into the loaded -transformer weights before quantization: W + scale * B @ A in float32, rounded -to the weight's dtype, which reproduces a checkpoint that ships the merge. +A checkpoint whose config.json sets ``max_references`` keeps the Qwen3-VL vision +tower and loads as mflux's ``QwenImage21Edit``, which renders from text alone or +from up to ten reference images. An older text-only checkpoint loads as ``QwenImage21``. + +A LoRA is merged into the loaded transformer weights before quantization: +W + scale * B @ A in float32, rounded to the weight's dtype, which reproduces a +checkpoint that ships the merge. """ from __future__ import annotations +import json import time from pathlib import Path @@ -14,6 +19,7 @@ import numpy as np MFLUX_MODEL = "qwen-image-2.1" +MAX_REFERENCES = 10 def _node(blocks, module: str): @@ -51,23 +57,63 @@ def merge_lora(transformer: dict, lora: dict, scale: float) -> int: def load(path): from mflux.models.common.config import ModelConfig + + config = json.loads((Path(path) / "config.json").read_text(encoding="utf-8")) + if config.get("max_references"): + from mflux.models.qwen21.variants.edit.qwen_image_21_edit import QwenImage21Edit + + return QwenImage21Edit(model_path=str(path), model_config=ModelConfig.qwen_image_21()) from mflux.models.qwen21.variants.txt2img.qwen_image_21 import QwenImage21 return QwenImage21(model_path=str(path), model_config=ModelConfig.qwen_image_21()) +def prepare_references(images): + """Decode references before model loading and keep source paths out of mflux metadata.""" + from PIL import Image + + if len(images) > MAX_REFERENCES: + raise ValueError("Qwen-Image 2.1 takes at most {0} reference images.".format(MAX_REFERENCES)) + references = [] + for reference in images: + if isinstance(reference, Image.Image): + references.append(reference) + continue + try: + with Image.open(reference, formats=("PNG", "JPEG", "WEBP")) as image: + references.append(image.copy()) + except (OSError, ValueError, SyntaxError, Image.DecompressionBombError) as error: + raise ValueError("--image {0} is not a readable PNG, JPEG or WebP file.".format(reference)) from error + return references + + def generate(model, prompt: str, out: str, width: int = 1024, height: int = 1024, steps: int = 40, seed: int = 42, - guidance: float = 1.0) -> dict: - """Render one image to ``out`` (PNG); returns its dimensions, timing, and pixel spread.""" + guidance: float = 1.0, images=()) -> dict: + """Render one image to ``out`` (PNG), conditioned on ``images`` when given; returns its dimensions, timing, and pixel spread.""" + from mflux.models.qwen21.variants.edit.qwen_image_21_edit import QwenImage21Edit + + images = list(images) + references = prepare_references(images) + paths = [str(path) for path in images if isinstance(path, (str, Path))] + render_width, render_height = width, height + if isinstance(model, QwenImage21Edit): + # The edit backend needs multiples of 32; the CLI accepts multiples of 16. + render_width = ((width + 31) // 32) * 32 + render_height = ((height + 31) // 32) * 32 started = time.time() image = model.generate_image( - seed=seed, prompt=prompt, num_inference_steps=steps, width=width, height=height, guidance=guidance, + seed=seed, prompt=prompt, num_inference_steps=steps, width=render_width, height=render_height, guidance=guidance, + **({"image_paths": references} if references else {}), ) seconds = time.time() - started + if (render_width, render_height) != (width, height): + left, top = (render_width - width) // 2, (render_height - height) // 2 + image.image = image.image.crop((left, top, left + width, top + height)) + image.width, image.height = width, height Path(out).parent.mkdir(parents=True, exist_ok=True) image.save(path=out) pixels = np.asarray(image.image).astype(np.float32) return { "path": str(out), "width": int(pixels.shape[1]), "height": int(pixels.shape[0]), "steps": steps, "seed": seed, - "seconds": round(seconds, 3), "pixel_std": round(float(pixels.std()), 3), + "seconds": round(seconds, 3), "pixel_std": round(float(pixels.std()), 3), "images": paths, } diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/pixal3d/convert.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/pixal3d/convert.py index 27b5424..075160c 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/pixal3d/convert.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/pixal3d/convert.py @@ -9,8 +9,8 @@ from pathlib import Path from ..trellis2.convert import ( - ENCODER_TYPE, FLOW_FLAGS, PIPELINE_NAME, PROVENANCE_NAME, SAMPLERS, UNQUANTIZED_BITS, _convert_tensors, _read, - _source, + CASCADE_FLOOR, ENCODER_TYPE, FLOW_FLAGS, MAX_TOKENS, PIPELINE_NAME, PROVENANCE_NAME, SAMPLERS, UNQUANTIZED_BITS, + _convert_tensors, _read, _source, ) MODELS = { @@ -151,7 +151,7 @@ def convert(hf_path, mlx_path, sources=None, downloads=None, quantize=False, q_b del converted sampler = settings["shape_slat_sampler"] mesh = {"resolutions": list(RESOLUTIONS), "resolution": default, "steps": sampler["steps"], - "guidance": sampler["guidance_strength"]} + "guidance": sampler["guidance_strength"], "max_tokens": MAX_TOKENS, "cascade_floor": CASCADE_FLOOR} config = {"model_type": "pixal3d", "components": configs, "pipeline": settings, "mesh": mesh} if quantize: config["quantization"] = {"bits": q_bits, "group_size": 64} diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/pixal3d/pipeline.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/pixal3d/pipeline.py index 3036cee..f1a60ec 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/pixal3d/pipeline.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/pixal3d/pipeline.py @@ -10,15 +10,16 @@ from . import moge, naf, projection from ..trellis2 import dinov3, dual_grid, flow, sparse, structure -from ..trellis2.pipeline import _denormalize, _kernels, _noise, _sampler, gltf_axes +from ..trellis2.convert import CASCADE_FLOOR, MAX_TOKENS +from ..trellis2.pipeline import ( + HIGH_CONDITION_PIXELS, _denormalize, _kernels, _noise, _sampler, cascade_settings, gltf_axes, +) from ..triposg.geometry import decimate, write_glb from ..triposg.weights import Weights COMPONENTS = ("image_encoder", "ss_flow", "ss_decoder", "shape_flow_512", "shape_flow_1024", "shape_decoder", "moge", "naf") RESOLUTIONS = (1024, 1536) -MAX_TOKENS = 49152 -CASCADE_FLOOR = 1024 LOW_RESOLUTION = 512 CROP_MARGIN = 1.1 NAF_SIZE = (512, 512) @@ -44,12 +45,13 @@ def load(path): return config, weights -def cascade_coords(coords, low, high, max_tokens=MAX_TOKENS): - """Rounded high-resolution latent coordinates, lowering ``high`` by 128 until they fit the token cap.""" +def cascade_coords(coords, low, high, max_tokens=MAX_TOKENS, floor=CASCADE_FLOOR): + """Rounded high-resolution latent coordinates, lowering ``high`` by 128 until they fit the token cap or the next + level would fall below ``floor``.""" coords = np.asarray(coords, dtype=np.float64) while True: quantized = np.unique(np.round((coords + 0.5) / low * (high // 16 - 1)).astype(np.int32), axis=0) - if len(quantized) < max_tokens or high == CASCADE_FLOOR: + if len(quantized) <= max_tokens or high - 128 < floor: return quantized, high high -= 128 @@ -127,12 +129,12 @@ def generate(model, image, out, steps=12, seed=42, resolution=1536, guidance=7.5 slat = _denormalize(slat[0], normalization) decoder = config["components"]["shape_decoder"] upsampled = sparse.run(weights["shape_decoder"], decoder, slat, coords, stop_level=4) - coords, level_resolution = cascade_coords(upsampled, LOW_RESOLUTION, resolution) + coords, level_resolution = cascade_coords(upsampled, LOW_RESOLUTION, resolution, *cascade_settings(config)) del cond, slat, upsampled previous, cursor = cursor, time.perf_counter() stages["shape_latent_512"] = cursor - previous - cond = Condition(weights, config, picture, CASCADE_FLOOR, upsample=True) + cond = Condition(weights, config, picture, HIGH_CONDITION_PIXELS, upsample=True) high = config["components"]["shape_flow_1024"] slat = flow.sample(weights["shape_flow_1024"], high, _noise(rng, (1, len(coords), high["in_channels"])), cond.globals, mx.zeros_like(cond.globals), 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 1f87e4b..1b6f05a 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 @@ -29,6 +29,10 @@ ENCODER_TYPE = "dinov3_vit" RESOLUTIONS = (512, 1024, 1536) DEFAULT_RESOLUTION = 1024 +# Mesh-block defaults: the high-resolution level drops by 128 while its voxels exceed max_tokens, down to +# cascade_floor. +MAX_TOKENS = 49152 +CASCADE_FLOOR = 1024 def _read(path): @@ -134,7 +138,7 @@ def convert(hf_path, mlx_path, sources=None, quantize=False, q_bits=8): del converted sampler = settings["shape_slat_sampler"] mesh = {"resolutions": list(RESOLUTIONS), "resolution": DEFAULT_RESOLUTION, "steps": sampler["steps"], - "guidance": sampler["guidance_strength"]} + "guidance": sampler["guidance_strength"], "max_tokens": MAX_TOKENS, "cascade_floor": CASCADE_FLOOR} config = {"model_type": "trellis2", "components": configs, "pipeline": settings, "mesh": mesh} if quantize: config["quantization"] = {"bits": q_bits, "group_size": 64} 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 94a77b3..b670f0f 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 @@ -8,6 +8,21 @@ FREQUENCY_SIZE = 256 SIGMA_MIN = 1e-5 +DTYPES = {"float32": mx.float32, "float16": mx.float16, "bfloat16": mx.bfloat16} + + +def compute_dtype(config): + """The dtype a flow's checkpoint config names for its transformer blocks; float32 when it names none.""" + name = config.get("dtype", "float32") + if name not in DTYPES: + raise ValueError("TRELLIS.2 flow dtype must be one of " + ", ".join(DTYPES) + ".") + return DTYPES[name] + + +def block_values(values, dtype): + """Floating ``blocks.*`` tensors in ``dtype``, as the reference converts its blocks; packed weights stay packed.""" + return {name: value.astype(dtype) if name.startswith("blocks.") and mx.issubdtype(value.dtype, mx.floating) + else value for name, value in values.items()} def timestep_embedding(t, dim=FREQUENCY_SIZE, max_period=10000): @@ -33,18 +48,20 @@ def grid_positions(resolution): def _rotate(x, cos, sin): - pairs = x.reshape(*x.shape[:-1], -1, 2) + # Rotations, head norms and layer norms run in float32 and return the block dtype, as in the reference. + pairs = x.astype(mx.float32).reshape(*x.shape[:-1], -1, 2) even, odd = pairs[..., 0], pairs[..., 1] - return mx.stack([even * cos - odd * sin, even * sin + odd * cos], axis=-1).reshape(x.shape) + return mx.stack([even * cos - odd * sin, even * sin + odd * cos], axis=-1).reshape(x.shape).astype(x.dtype) def _head_norm(x, gamma): - norm = mx.sqrt(mx.sum(x * x, axis=-1, keepdims=True)) - return x / mx.maximum(norm, 1e-12) * gamma[:, None, :] * math.sqrt(x.shape[-1]) + y = x.astype(mx.float32) + norm = mx.sqrt(mx.sum(y * y, axis=-1, keepdims=True)) + return (y / mx.maximum(norm, 1e-12) * gamma[:, None, :].astype(mx.float32) * math.sqrt(x.shape[-1])).astype(x.dtype) def _layer_norm(x, eps=1e-6): - return mx.fast.layer_norm(x, None, None, eps) + return mx.fast.layer_norm(x.astype(mx.float32), None, None, eps).astype(x.dtype) def _block(w, name, x, mod, context, cos, sin, heads, proj=None): @@ -80,15 +97,20 @@ def _block(w, name, x, mod, context, cos, sin, heads, proj=None): def velocity(w, config, x, t, context, rope, proj=None): """Predicted flow velocity for tokens ``x`` (B, N, in) at timesteps ``t`` (B,) given image tokens ``context`` - and, for projection-conditioned models, image features ``proj`` (B, N, P) aligned with the tokens.""" + and, for projection-conditioned models, image features ``proj`` (B, N, P) aligned with the tokens. + TRELLIS.2 blocks run in the configured dtype; input, timestep and output layers stay float32.""" + # The Pixal3D loader keeps float32 block weights and quantization scales. + dtype = mx.float32 if proj is not None else compute_dtype(config) cos, sin = rope - h = w.linear("input_layer", x) + h = w.linear("input_layer", x).astype(dtype) mod = w.linear("t_embedder.mlp.0", timestep_embedding(t)) mod = w.linear("t_embedder.mlp.2", nn.silu(mod)) - mod = w.linear("adaLN_modulation.1", nn.silu(mod)) + mod = w.linear("adaLN_modulation.1", nn.silu(mod)).astype(dtype) + context = context.astype(dtype) + proj = None if proj is None else proj.astype(dtype) for index in range(config["num_blocks"]): h = _block(w, "blocks.{0}".format(index), h, mod, context, cos, sin, config["num_heads"], proj) - return w.linear("out_layer", _layer_norm(h, 1e-5)) + return w.linear("out_layer", _layer_norm(h.astype(mx.float32), 1e-5)) def schedule(steps, rescale_t): 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 index 5e63504..1827060 100644 --- 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 @@ -143,6 +143,43 @@ def surface_coords(path, resolution): def place(path, center, extent): """Rewrite a generated unit-cube GLB's positions as ``position * extent + center``, the guide's frame.""" + _rewrite(path, lambda positions: positions * extent + center) + + +def fit_size(size): + """Validate extents in the standalone backend before sampling or writing a GLB.""" + message = "TRELLIS.2 bbox sizes must fit centered float32 GLB coordinates." + try: + size = np.asarray(tuple(size), dtype=np.float64) + except (TypeError, ValueError, OverflowError) as error: + raise ValueError(message) from error + limits = np.finfo(np.float32) + minimum = 2 * float(limits.smallest_subnormal) + maximum = 2 * float(limits.max) + if size.shape != (3,) or not np.all((minimum <= size) & (size <= maximum)): + raise ValueError(message) + return size + + +def fit(path, size): + """Rewrite a generated GLB's positions so their bounds span ``size`` (glTF x, y, z), centered on the origin.""" + size = fit_size(size) + + def stretch(positions): + if not np.isfinite(positions).all(): + raise ValueError("Generated positions must be finite before bbox fitting.") + low, high = positions.min(axis=0), positions.max(axis=0) + if not (high > low).all(): + raise ValueError("The generated mesh is flat along an axis.") + placed = (((positions - low) / (high - low) - 0.5) * size).astype(" placed.min(axis=0)).all(): + raise ValueError("The fitted mesh must have finite float32 positions spanning all three axes.") + return placed + _rewrite(path, stretch) + + +def _rewrite(path, transform): + """Rewrite a generated GLB's packed float32 positions as ``transform(positions)``.""" document, binary = _chunks(path) binary = bytearray(binary) accessor = document["accessors"][document["meshes"][0]["primitives"][0]["attributes"]["POSITION"]] @@ -151,7 +188,7 @@ def place(path, center, extent): 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, HIGH_CONDITION_PIXELS)) for picture in pictures] cursor = time.perf_counter() stages["conditioning"] = cursor - started @@ -197,7 +239,7 @@ def generate(model, image, out, steps=12, seed=42, resolution=1024, guidance=7.5 **_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) + coords = structure.occupied(logits, LOW_RESOLUTION // 16, box=bbox) else: coords, guide_center, guide_extent = surface_coords(guide, LOW_RESOLUTION // 16) previous, cursor = cursor, time.perf_counter() @@ -216,7 +258,7 @@ def generate(model, image, out, steps=12, seed=42, resolution=1024, guidance=7.5 level_resolution = LOW_RESOLUTION if resolution > LOW_RESOLUTION: upsampled = sparse.run(weights["shape_decoder"], decoder, slat, coords, stop_level=4) - coords, level_resolution = cascade_coords(upsampled, LOW_RESOLUTION, resolution) + coords, level_resolution = cascade_coords(upsampled, LOW_RESOLUTION, resolution, *cascade_settings(config)) 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[0]), flow.rope_tables(coords, head_dim), **shape_params) @@ -248,13 +290,9 @@ def generate(model, image, out, steps=12, seed=42, resolution=1024, guidance=7.5 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) - previous, cursor = cursor, time.perf_counter() - stages["mesh"] = cursor - previous - 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, seconds = surface(voxels, vertices, crossed, split, level_resolution) + stages.update(seconds) + cursor = time.perf_counter() vertices, faces = closed.without_fins(*decimate(vertices, faces, max_faces, aggression=3)) previous, cursor = cursor, time.perf_counter() stages["decimation"] = cursor - previous @@ -262,13 +300,13 @@ def generate(model, image, out, steps=12, seed=42, resolution=1024, guidance=7.5 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) + _write_mesh(out, vertices, faces, colors, materials, bbox) 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, + "views": len(pictures), "guided": guide is not None, "bbox": bbox, "seed": seed, "resolution": level_resolution, "vertices": len(vertices), "faces": len(faces), "voxels": len(voxels), "vertex_colors": paint, "pbr": paint, "stage_seconds": {name: round(value, 3) for name, value in stages.items()}, diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/structure.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/structure.py index 923e521..d3368b9 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/structure.py +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-3d/trellis2/structure.py @@ -47,9 +47,37 @@ def decode(w, config, latent): return h[..., 0] -def occupied(logits, resolution): - """Integer (x, y, z) coordinates of occupied voxels at ``resolution``, pooled from the decoder grid.""" +def fit(grid, box): + """Fit occupied bounds to a centered box, pooling on shrinking axes to retain thin geometry.""" + found = np.argwhere(grid) + if not len(found): + return grid + low, high = found.min(axis=0), found.max(axis=0) + 1 + size = grid.shape[0] + box = np.asarray(box, dtype=np.float64) + spans = np.maximum(np.rint(box / box.max() * size), 1).astype(np.int64) + starts = (size - spans) // 2 + occupied = grid[tuple(slice(start, stop) for start, stop in zip(low, high))] + for axis, span in enumerate(spans): + width = occupied.shape[axis] + if span < width: + # Partition the full source axis into nonempty bins, including both ends. + edges = (np.arange(span) * width + span // 2) // span + occupied = np.logical_or.reduceat(occupied, edges, axis=axis) + elif span > width: + picks = ((np.arange(span) + 0.5) * width / span).astype(np.intp) + occupied = np.take(occupied, picks, axis=axis) + fitted = np.zeros_like(grid) + fitted[tuple(slice(start, start + span) for start, span in zip(starts, spans))] = occupied + return fitted + + +def occupied(logits, resolution, box=None): + """Integer (x, y, z) coordinates of occupied voxels at ``resolution``, pooled from the decoder grid after + fitting it to ``box`` proportions when given.""" grid = np.array(logits[0] > 0) + if box is not None: + grid = fit(grid, box) ratio = grid.shape[0] // resolution if ratio > 1: grid = grid.reshape(resolution, ratio, resolution, ratio, resolution, ratio).any(axis=(1, 3, 5)) 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 ceb89be..423779f 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 @@ -38,17 +38,27 @@ def extract_mesh(query, depth=9, bounds=DEFAULT_BOUNDS, seconds=None): def decimate(vertices, faces, max_faces, aggression=7): - """Quadric edge collapse down to `max_faces` triangles; meshes at or under the cap pass through. + """Quadric edge collapse down to at most `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. + Retry above the cap with increasing aggression up to 10 (or the starting value if higher). + At that limit, stop if a pass removes no faces. """ 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, agg=aggression) - return points.astype(np.float32), triangles + max_aggression = max(aggression, 10) + points, triangles = np.ascontiguousarray(vertices, dtype=np.float32), np.ascontiguousarray(faces, dtype=np.int32) + while len(triangles) > max_faces: + count = len(triangles) + points, triangles = simplify(points, triangles, target_count=max_faces, agg=aggression) + points, triangles = np.ascontiguousarray(points, dtype=np.float32), np.ascontiguousarray(triangles, dtype=np.int32) + if len(triangles) >= count and aggression == max_aggression: + raise ValueError("Decimation stopped at {0} faces above the {1} cap; raise --max-faces.".format( + len(triangles), max_faces)) + aggression = min(aggression + 1, max_aggression) + return points, triangles def _material_atlas(materials, faces): diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-audio/mel_band_roformer/__init__.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-audio/mel_band_roformer/__init__.py new file mode 100644 index 0000000..65cfa3a --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-audio/mel_band_roformer/__init__.py @@ -0,0 +1,114 @@ +"""Split a mix into a vocal stem and the rest with a Mel-Band-RoFormer checkpoint on mlx-audio's model.""" + +import errno +import os +import shutil +import wave +from contextlib import ExitStack, suppress +from pathlib import Path +from tempfile import TemporaryDirectory + +import numpy as np + +PCM_BLOCK_FRAMES = 65_536 + + +def load(path): + from mlx_audio.sts.models.mel_roformer import MelRoFormer + + model = MelRoFormer.from_pretrained(path) + model.eval() + return model + + +def separate(model, mixture): + """Vocals for a [channels, samples] float32 mix. + + The model sees `chunk_size` samples at a time, `num_overlap` chunks over each sample; the chunk + outputs are Hann-weighted and normalized by the summed weights, so every sample gets full weight. + """ + import mlx.core as mx + + chunk = int(model.config.chunk_size) + step = chunk // int(model.config.num_overlap) + border = chunk - step + length = mixture.shape[1] + starts = range(0, border + length, step) + padded = np.zeros((mixture.shape[0], starts[-1] + chunk), dtype=np.float32) + padded[:, border:border + length] = mixture + window = (np.hanning(chunk) if border else np.ones(chunk)).astype(np.float32) + total = np.zeros_like(padded) + weight = np.zeros(padded.shape[1], dtype=np.float32) + for start in starts: + vocals = model(mx.array(padded[None, :, start:start + chunk]))[0] + total[:, start:start + chunk] += np.array(vocals.astype(mx.float32)) * window + weight[start:start + chunk] += window + return total[:, border:border + length] / weight[border:border + length] + + +def _stage_stem(stack, target, vocals, rate, mixture=None): + directory = stack.enter_context(TemporaryDirectory(prefix=".mlx-separate-", dir=Path(target).parent)) + path = Path(directory) / "stem.wav" + channels, frames = vocals.shape + with wave.open(str(path), "wb") as wav: + wav.setparams((channels, 2, rate, frames, "NONE", "not compressed")) + for start in range(0, frames, PCM_BLOCK_FRAMES): + end = start + PCM_BLOCK_FRAMES + block = vocals[:, start:end] + if mixture is not None: + block = mixture[:, start:end] - block + pcm = (np.clip(block, -1.0, 1.0) * 32767).astype(np.int16) + wav.writeframesraw(pcm.T.tobytes()) + return path + + +def _remove_owned_stem(target, identity): + with suppress(FileNotFoundError): + if os.path.samestat(identity, os.lstat(target)): + os.unlink(target) + + +def _publish_stem(staged, target): + # A hard link publishes the completed file without replacing an existing destination. + try: + os.link(staged, target) + except OSError as error: + if error.errno not in (errno.ENOTSUP, errno.EOPNOTSUPP, errno.EPERM): + raise + else: + return staged.stat() + + # Volumes without hard links can still claim the destination with exclusive creation. + identity = None + try: + with staged.open("rb") as source, open(target, "xb") as output: + identity = os.fstat(output.fileno()) + shutil.copyfileobj(source, output) + except OSError: + if identity is not None: + _remove_owned_stem(target, identity) + raise + return identity + + +def generate(model, audio, out, rest=None): + from mlx_audio.audio_io import read + + rate = int(model.config.sample_rate) + samples, _ = read(audio, always_2d=True, dtype="float32", sample_rate=rate, nchannels=2) + mixture = np.ascontiguousarray(samples.T) + vocals = separate(model, mixture) + with ExitStack() as stack: + staged_vocals = _stage_stem(stack, out, vocals, rate) + staged_rest = _stage_stem(stack, rest, vocals, rate, mixture) if rest else None + vocal_identity = _publish_stem(staged_vocals, out) + if staged_rest is not None: + try: + _publish_stem(staged_rest, rest) + except OSError: + _remove_owned_stem(out, vocal_identity) + raise + result = {"path": out, "sample_rate": rate, "audio_seconds": round(mixture.shape[1] / rate, 3)} + if rest: + result["rest"] = rest + return result diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-audio/sam_audio/__init__.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-audio/sam_audio/__init__.py new file mode 100644 index 0000000..0a43349 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/mlx-audio/sam_audio/__init__.py @@ -0,0 +1,124 @@ +"""Separate the sound a text prompt names from a mix with a SAM-Audio checkpoint on mlx-audio's model. + +The T5 text encoder the checkpoint's config names is read from the folder of that name beside the +checkpoint, so nothing is fetched. +""" + +import dataclasses +import importlib +import json +from contextlib import ExitStack +from pathlib import Path + +import numpy as np + + +def _stems(): + """The Mel-Band-RoFormer port's staged, non-replacing WAV writer, installed beside this port.""" + package = __name__.rpartition(".")[0] + return importlib.import_module(package + ".mel_band_roformer" if package else "mel_band_roformer") + + +def text_encoder_folder(path): + folder = Path(path) + config = json.loads((folder / "config.json").read_text(encoding="utf-8")) + name = config["text_encoder"]["name"] + encoder = folder.parent / name + missing = [file for file in ("config.json", "model.safetensors") if not (encoder / file).is_file()] + if missing: + raise FileNotFoundError( + "SAM-Audio reads its {0} text encoder from {1}, which lacks {2}; place that model folder beside " + "the checkpoint.".format(name, encoder, ", ".join(missing)) + ) + return encoder + + +def _t5(folder): + """T5 encoder weights from a local folder, configured as mlx-audio configures its hub copy.""" + import mlx.core as mx + from mlx_audio.sts.models.sam_audio.text_encoder import T5Config, T5Encoder + + values = json.loads((folder / "config.json").read_text(encoding="utf-8")) + defaults = T5Config(is_gated_act=False, dense_act_fn="relu") + config = T5Config(**{field.name: values.get(field.name, getattr(defaults, field.name)) + for field in dataclasses.fields(T5Config)}) + model = T5Encoder(config) + model.load_weights(list(T5Encoder.sanitize(mx.load(str(folder / "model.safetensors"))).items())) + mx.eval(model.parameters()) + model.eval() + return model + + +def _checkpoint_weights(folder): + import mlx.core as mx + + shards = sorted(folder.glob("*.safetensors")) + if shards: + weights = {} + for shard in shards: + weights.update(mx.load(str(shard))) + return weights + + checkpoint = folder / "checkpoint.pt" + if checkpoint.is_file(): + import torch + + weights = torch.load(str(checkpoint), map_location="cpu", weights_only=True) + return {name: mx.array(tensor.numpy()) for name, tensor in weights.items()} + + raise FileNotFoundError("No SAM-Audio weights in {0}; expected safetensors or checkpoint.pt.".format(folder)) + + +def load(path): + folder = Path(path) + encoder = text_encoder_folder(folder) + import mlx.core as mx + import transformers + from mlx_audio.sts.models.sam_audio import SAMAudio, SAMAudioConfig + + config = SAMAudioConfig.from_dict(json.loads((folder / "config.json").read_text(encoding="utf-8"))) + weights = _checkpoint_weights(folder) + model = SAMAudio(config) + # mlx-audio's from_pretrained can return a partially initialized model without a warning. + model.load_weights(list(model.sanitize(weights).items()), strict=True) + mx.eval(model.parameters()) + model = model.post_load_hook(folder) + model.text_encoder.tokenizer = transformers.AutoTokenizer.from_pretrained(str(encoder), local_files_only=True) + model.text_encoder.model = _t5(encoder) + model.eval() + return model + + +def fit(samples, length): + """A [1, length] row: the decoder's output trimmed or zero-padded to the mix length.""" + row = np.asarray(samples, dtype=np.float32).reshape(1, -1)[:, :length] + return np.pad(row, ((0, 0), (0, length - row.shape[1]))) + + +def generate(model, audio, out, rest=None, prompt=None): + import mlx.core as mx + from mlx_audio.audio_io import read + + if not prompt: + raise ValueError("SAM-Audio separates the sound a prompt names; pass a prompt.") + rate = int(model.sample_rate) + samples, _ = read(audio, always_2d=True, dtype="float32", sample_rate=rate, nchannels=1) + length = samples.shape[0] + result = model.separate_long(mx.array(np.ascontiguousarray(samples.T)[None]), [prompt]) + target = fit(np.array(result.target[0].astype(mx.float32)), length) + residual = fit(np.array(result.residual[0].astype(mx.float32)), length) if rest else None + stems = _stems() + with ExitStack() as stack: + staged_target = stems._stage_stem(stack, out, target, rate) + staged_rest = stems._stage_stem(stack, rest, residual, rate) if rest else None + identity = stems._publish_stem(staged_target, out) + if staged_rest is not None: + try: + stems._publish_stem(staged_rest, rest) + except OSError: + stems._remove_owned_stem(out, identity) + raise + value = {"path": out, "prompt": prompt, "sample_rate": rate, "audio_seconds": round(length / rate, 3)} + if rest: + value["rest"] = rest + return value diff --git a/packages/codex/mlx-agent/src/mlx_agent/resources/ports/sam2/segment/__init__.py b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/sam2/segment/__init__.py new file mode 100644 index 0000000..21af776 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/resources/ports/sam2/segment/__init__.py @@ -0,0 +1,97 @@ +"""Run a prompted image mask on an explicitly selected local SAM 2 checkpoint.""" + +import hashlib +from pathlib import Path + +VIDEO_ONLY = ( + 'mask_downsample.', 'memory_attention.', 'memory_encoder.', + 'memory_temporal_positional_encoding', 'no_memory_positional_encoding', + 'no_object_pointer', 'object_pointer_proj.', + 'occlusion_spatial_embedding_parameter', 'temporal_positional_encoding_projection_layer.', +) + + +def is_video_key(key): + return any(key.startswith(name) if name.endswith('.') else key == name for name in VIDEO_ONLY) + + +def validate_loading(info): + """Reject incomplete image weights and retain only known video-specific extras.""" + fields = ('missing_keys', 'unexpected_keys', 'mismatched_keys', 'error_msgs') + if not isinstance(info, dict) or any(not isinstance(info.get(key), (list, tuple, set)) for key in fields): + raise ValueError('The checkpoint loading report is absent or invalid.') + if info.get('missing_keys') or info.get('mismatched_keys') or info.get('error_msgs'): + raise ValueError('The checkpoint did not load all image model parameters.') + unexpected = sorted(info.get('unexpected_keys', ())) + if any(not is_video_key(key) for key in unexpected): + raise ValueError('The checkpoint contains unexpected non-video parameters.') + return unexpected + + +def validate_checkpoint_keys(model_keys, checkpoint_keys): + """Require exact image keys and allow only identified video-specific extras.""" + model_keys, checkpoint_keys = set(model_keys), set(checkpoint_keys) + if not model_keys or model_keys - checkpoint_keys: + raise ValueError('The checkpoint is missing image model parameters.') + extras = sorted(checkpoint_keys - model_keys) + if any(not is_video_key(key) for key in extras): + raise ValueError('The checkpoint contains unexpected non-video parameters.') + return extras + + +def load(path): + import torch + from safetensors import safe_open + from transformers import Sam2Model, Sam2Processor + if not torch.backends.mps.is_available(): + raise RuntimeError('The MPS device is unavailable.') + directory = Path(path) + files = list(directory.glob('*.safetensors')) + if len(files) != 1 or files[0].name != 'model.safetensors' or list(directory.glob('*.safetensors.index.json')): + raise ValueError('Only a single unsharded model.safetensors checkpoint is supported.') + processor = Sam2Processor.from_pretrained(path, local_files_only=True, trust_remote_code=False) + model, info = Sam2Model.from_pretrained( + path, local_files_only=True, use_safetensors=True, trust_remote_code=False, + torch_dtype=torch.float32, output_loading_info=True, + ) + validate_loading(info) + with safe_open(files[0], framework='pt', device='cpu') as checkpoint: + extras = validate_checkpoint_keys(model.state_dict().keys(), checkpoint.keys()) + report = {key: sorted(value) for key, value in info.items()} + return model.to('mps').eval(), processor, extras, report + + +def generate(loaded, image_path, output_path, box, points, labels, threshold): + import torch + from PIL import Image, ImageOps + model, processor, unexpected, loading_report = loaded + source = Path(image_path) + with source.open('rb') as stream: + digest = hashlib.file_digest(stream, 'sha256').hexdigest() + with Image.open(source) as original: + image = ImageOps.exif_transpose(original).convert('RGB') + width, height = image.size + if not (0 <= box[0] < box[2] <= width and 0 <= box[1] < box[3] <= height): + raise ValueError('Box is outside the oriented image.') + if any(not (0 <= x < width and 0 <= y < height) for x, y in points): + raise ValueError('Point is outside the oriented image.') + kwargs = {'images': image, 'input_boxes': [[box]], 'return_tensors': 'pt'} + if points: + kwargs.update(input_points=[[points]], input_labels=[[labels]]) + inputs = processor(**kwargs) + sizes = inputs.pop('original_sizes') + inputs = {key: value.to('mps') if hasattr(value, 'to') else value for key, value in inputs.items()} + with torch.inference_mode(): + output = model(**inputs, multimask_output=False) + masks = processor.post_process_masks(output.pred_masks.cpu(), sizes, mask_threshold=threshold) + if len(masks) != 1 or tuple(masks[0].shape) != (1, 1, height, width): + raise ValueError('The mask output has an unexpected shape.') + mask = masks[0][0, 0].to(dtype=torch.uint8).numpy() * 255 + Image.fromarray(mask, mode='L').save(output_path, format='PNG') + return {'path': str(output_path), 'device': 'mps', 'input_sha256': digest, + 'dimensions': [width, height], 'threshold': threshold, + 'iou_score': float(output.iou_scores.reshape(-1)[0].cpu()), + 'unused_video_keys': unexpected, + 'loading_report': loading_report, + 'memory': {'framework': 'torch', 'active_bytes': torch.mps.current_allocated_memory(), + 'cache_bytes': None, 'peak_bytes': None}} diff --git a/packages/codex/mlx-agent/src/mlx_agent/segment.py b/packages/codex/mlx-agent/src/mlx_agent/segment.py new file mode 100644 index 0000000..70c656e --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/segment.py @@ -0,0 +1,53 @@ +"""Plan and run a source-oriented local image-segmentation task.""" + +import json +import subprocess +from pathlib import Path + +from .backends import ( + backend_python, + is_installed, + load_manifests, + load_registries, + lookup, +) +from .inference_runner import InferenceError, RunnerContract, invoke + + +class SegmentError(InferenceError): + """A segmentation failure safe to return to the caller.""" + + +def plan_segment(model_path, parameters, output, image, directory): + model, source, target = (Path(value).expanduser().absolute() for value in (model_path, image, output)) + try: + config = json.loads((model / 'config.json').read_text()) + except (OSError, ValueError) as error: + raise SegmentError('model_unreadable', 'The model config cannot be read.', 'Select a local SAM 2 model.') from error + if not isinstance(config, dict): + raise SegmentError('model_unreadable', 'The model config must be a JSON object.', 'Select a local SAM 2 model.') + manifests = load_manifests() + registries = load_registries(manifests) + hits = [hit for hit in lookup(config.get('model_type'), manifests, registries) + if hit['category'] == 'image_segmentation' and hit['backend'] == 'sam2'] + if not hits or not is_installed(manifests['sam2']): + raise SegmentError('backend_not_installed', 'The selected segmentation backend is unavailable.', + 'Install the SAM 2 backend and select a supported model.') + if not source.is_file() or target.exists() or target.is_symlink() or not target.parent.is_dir(): + raise SegmentError('invalid_arguments', 'Input or output path is invalid.', 'Choose an existing image and new output path.') + argv = [str(backend_python(manifests['sam2'])), str(Path(__file__).with_name('segment_runner.py')), + '--module', hits[0]['module'], '--model', str(model), '--image', str(source), '--out', str(target), + '--box', json.dumps(parameters['box']), '--points', json.dumps(parameters.get('points', [])), + '--labels', json.dumps(parameters.get('labels', [])), '--threshold', str(parameters['mask_threshold'])] + return {'backend': 'sam2', 'model': str(model), 'out': str(target), 'argv': argv} + + +CONTRACT = RunnerContract(verb='segment', error=SegmentError, + accept=lambda value, plan: value.get('path') == plan['out'], action='generate the mask', + remediation='Check the model and source image.', activity='Image segmentation', + timeout_remediation='Retry using a new task.') + + +def run_segment(plan, manifests=None, root=None, timeout=3600, runner=subprocess.run): + result = invoke(plan, CONTRACT, manifests, root, timeout, runner) + return dict(result, schema='segment/1', backend=plan['backend'], model=plan['model']) diff --git a/packages/codex/mlx-agent/src/mlx_agent/segment_runner.py b/packages/codex/mlx-agent/src/mlx_agent/segment_runner.py new file mode 100644 index 0000000..86020f6 --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/segment_runner.py @@ -0,0 +1,33 @@ +"""Execute a local prompted image-segmentation task.""" + +import argparse +import importlib +import json +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__) + for name in ('module', 'model', 'image', 'out', 'box', 'points', 'labels'): + parser.add_argument('--' + name, required=True) + parser.add_argument('--threshold', type=float, required=True) + args = parser.parse_args(argv) + port = importlib.import_module(args.module) + start = time.monotonic() + model = load_model(port.load, args.model) + loaded = time.monotonic() + result = port.generate(model, args.image, args.out, json.loads(args.box), + json.loads(args.points), json.loads(args.labels), args.threshold) + result['load_seconds'] = round(loaded - start, 3) + result['stage_seconds'] = {'load': result['load_seconds'], 'inference': round(time.monotonic() - loaded, 3)} + print(json.dumps(result), flush=True) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/packages/codex/mlx-agent/src/mlx_agent/separate.py b/packages/codex/mlx-agent/src/mlx_agent/separate.py new file mode 100644 index 0000000..2c67b5b --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/separate.py @@ -0,0 +1,123 @@ +"""Split one audio mix into a stem and the rest with a source-separation model through its backend. + +Vocal models split out the vocals; text-prompted models split out the sound a prompt names. +""" + +from __future__ import annotations + +import json +import subprocess +from pathlib import Path + +from .backends import ( + backend_python, + is_installed, + load_manifests, + load_registries, + lookup, + port_is_prompted, +) +from .inference_runner import InferenceError, RunnerContract, invoke + +SEPARATE_SCHEMA = "separate/1" +SEPARATE_RUNNER = Path(__file__).resolve().with_name("separate_runner.py") +DEFAULT_TIMEOUT_SECONDS = 1800 +MAX_PROMPT_CHARACTERS = 500 + + +class SeparateError(InferenceError): + """Classified separation failure safe to surface in a result envelope.""" + + +def _invalid(message, remediation): + return SeparateError("invalid_arguments", message, remediation) + + +def _new_wav(value, flag): + target = Path(value).expanduser() + if not target.is_absolute() or target.suffix.lower() != ".wav" or target.exists() or target.is_symlink(): + raise _invalid("{0} must be a new absolute .wav path.".format(flag), "Pass a path such as /Users/me/Music/vocals.wav.") + if not target.parent.is_dir(): + raise _invalid("The directory of {0} does not exist.".format(flag), "Create the directory or pass a path inside an existing one.") + return target + + +def _prompt(value): + if value is None: + return None + text = value.strip() if isinstance(value, str) else "" + if not text or len(text) > MAX_PROMPT_CHARACTERS or any(not character.isprintable() for character in text): + raise _invalid("--prompt must be one line of 1 to {0} characters.".format(MAX_PROMPT_CHARACTERS), + "Name the sound to separate, such as --prompt drums.") + return text + + +def plan_separate(model_path, audio_path, out, rest=None, manifests=None, registries=None, root=None, prompt=None): + """Pick the separation backend and port for a model directory; pure apart from reading config.json.""" + model = Path(model_path).expanduser().resolve() + try: + config = json.loads((model / "config.json").read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + raise SeparateError( + "model_unreadable", "No readable config.json in {0}: {1}".format(model, error), + "Pass the separation model directory.", + ) from error + model_type = config.get("model_type") if isinstance(config, dict) else None + audio = Path(audio_path).expanduser().resolve() + if not audio.is_file(): + raise SeparateError("audio_not_found", "No audio file at {0}.".format(audio), "Pass a WAV, FLAC, or MP3 file.") + target = _new_wav(out, "--out") + remainder = None if rest is None else _new_wav(rest, "--rest") + if remainder is not None and remainder.resolve() == target.resolve(): + raise _invalid("--rest must differ from --out.", "Pass two different output paths.") + prompt = _prompt(prompt) + manifests = load_manifests() if manifests is None else manifests + registries = load_registries(manifests, root) if registries is None else registries + hits = sorted((hit for hit in lookup(model_type, manifests, registries) if hit["category"] == "source_separation"), + key=lambda hit: hit["backend"]) + if not hits: + raise SeparateError( + "not_separation_model", "No source-separation backend implements model_type {0!r}.".format(model_type), + "Separation applies to vocal separation models such as Mel-Band-RoFormer and text-prompted models " + "such as SAM-Audio.", + ) + manifest = manifests[hits[0]["backend"]] + prompted = port_is_prompted(model_type, manifest["id"], manifests) + if prompted and prompt is None: + raise _invalid("{0} separates the sound a --prompt names.".format(model_type), + "Pass --prompt, such as --prompt drums.") + if not prompted and prompt is not None: + raise _invalid("{0} separates vocals and takes no --prompt.".format(model_type), + "Drop --prompt, or pass a text-prompted model such as SAM-Audio.") + if not is_installed(manifest, root): + raise SeparateError( + "backend_not_installed", "The {0} backend is not installed.".format(manifest["id"]), + "Install it first: mlx-agent backend install {0}.".format(manifest["id"]), + ) + argv = [str(backend_python(manifest, root)), str(SEPARATE_RUNNER), "--module", hits[0]["module"], + "--model", str(model), "--audio", str(audio), "--out", str(target)] + if remainder is not None: + argv += ["--rest", str(remainder)] + if prompt is not None: + argv.append("--prompt=" + prompt) + return {"backend": manifest["id"], "model": str(model), "audio": str(audio), "out": str(target), + "rest": None if remainder is None else str(remainder), "prompt": prompt, "argv": argv} + + +CONTRACT = RunnerContract( + verb="separate", error=SeparateError, + accept=lambda value, plan: value.get("path") == plan["out"] and value.get("rest") == plan["rest"], + action="separate the mix", remediation="Check that the directory is a complete source-separation model.", + activity="Source separation", timeout_remediation="Use a shorter mix or a larger --timeout.", +) + + +def run_separate(plan, manifests=None, root=None, timeout=DEFAULT_TIMEOUT_SECONDS, runner=subprocess.run): + result = invoke(plan, CONTRACT, manifests, root, timeout, runner) + return { + "schema": SEPARATE_SCHEMA, "backend": plan["backend"], "model": plan["model"], "audio": plan["audio"], + "path": result["path"], "rest": result.get("rest"), "prompt": plan.get("prompt"), + "sample_rate": result.get("sample_rate"), + "audio_seconds": result.get("audio_seconds"), "seconds": result.get("seconds"), + "load_seconds": result.get("load_seconds"), + } diff --git a/packages/codex/mlx-agent/src/mlx_agent/separate_runner.py b/packages/codex/mlx-agent/src/mlx_agent/separate_runner.py new file mode 100644 index 0000000..456ee1a --- /dev/null +++ b/packages/codex/mlx-agent/src/mlx_agent/separate_runner.py @@ -0,0 +1,35 @@ +"""Run inside an audio backend's environment: split one mix into a stem and the rest, print JSON.""" + +import argparse +import importlib +import json +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__) + for name in ("module", "model", "audio", "out"): + parser.add_argument("--" + name, required=True) + parser.add_argument("--rest", default=None) + parser.add_argument("--prompt", default=None) + arguments = parser.parse_args(argv) + port = importlib.import_module(arguments.module) + started = time.monotonic() + model = load_model(port.load, arguments.model) + loaded = time.monotonic() + prompt = {} if arguments.prompt is None else {"prompt": arguments.prompt} + result = port.generate(model, arguments.audio, arguments.out, arguments.rest, **prompt) + result["load_seconds"] = round(loaded - started, 3) + result["seconds"] = round(time.monotonic() - started, 3) + print(json.dumps(result), flush=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packages/codex/mlx-agent/src/mlx_agent/serve.py b/packages/codex/mlx-agent/src/mlx_agent/serve.py index c86d135..b85f859 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/serve.py +++ b/packages/codex/mlx-agent/src/mlx_agent/serve.py @@ -244,6 +244,9 @@ def plan_start(repo, runtime, recipes, port=None, max_tokens=MAX_TOKENS_DEFAULT, 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 splash_tuning.get("splash_project_cache") is not None and (not jit or api_key_sha256 is None): + raise ServeError("invalid_arguments", "A Splash project cache requires a keyed JIT endpoint.", + "Use --jit and an API key file or digest.") 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.") @@ -485,6 +488,15 @@ def plan_start(repo, runtime, recipes, port=None, max_tokens=MAX_TOKENS_DEFAULT, if "--host" not in worker: worker.extend(["--host", "127.0.0.1"]) root = receipts_root(receipts_dir).absolute() + if splash_tuning.get("splash_project_cache") is not None: + from .splash_runtime import project_cache_directory + binding_keys = ("splash_runtime_fingerprint", "splash_model_fingerprint", "splash_draft_fingerprint", + "splash_chat_template_sha256", "weight_format", "splash_cached_states", "splash_kv_format", + "splash_max_context_tokens") + cache_dir = project_cache_directory(root, splash_tuning["splash_project_cache"], api_key_sha256, + {**{key: plan.get(key) for key in binding_keys}, "port": selected_port}) + worker.extend(["--cache-dir", cache_dir]) + plan["splash_project_cache_dir"] = cache_dir plan.update(jit=True, local_path=str(local), fingerprint=model_fingerprint(local), worker_argv=worker, control_config=str(root / "{}.jit-config.json".format(selected_port))) plan["argv"] = [sys.executable, str(Path(__file__).with_name("jit_serve.py").resolve()), @@ -703,6 +715,12 @@ def start_serve(plan, receipts_dir=None, confirm=False, preview_hash=None, "Run serve stop --port {0} first.".format(plan["port"]), ) + if plan.get("splash_project_cache_dir"): + from .splash_runtime import prepare_project_cache + try: + prepare_project_cache(plan["splash_project_cache_dir"]) + except (OSError, ValueError) as error: + raise ServeError("unsafe_splash_cache", str(error), "Use a private cache directory and review a fresh plan.") from error root.mkdir(parents=True, exist_ok=True) if spawn is _default_spawn: from .service_registry import register_receipts diff --git a/packages/codex/mlx-agent/src/mlx_agent/served.py b/packages/codex/mlx-agent/src/mlx_agent/served.py index bf98667..5597bba 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/served.py +++ b/packages/codex/mlx-agent/src/mlx_agent/served.py @@ -17,7 +17,7 @@ VERBS = { "speak": ("speak", ("text", "voice", "speed", "lang_code")), "music": ("music_generation", ("caption", "lyrics", "duration", "steps", "seed", "bpm", "time_signature", - "reference")), + "reference", "key", "keep_caption")), "generate": ("image_generation", ("prompt", "width", "height", "steps", "seed")), "video": ("video_generation", ("prompt", "width", "height", "frames", "steps", "seed", "fps", "denoiser_cache", "cache_memory_mib", "image", "audio", "audio_start")), @@ -53,9 +53,13 @@ def request(verb, arguments): parameters["views"] = [str(Path(path).expanduser().absolute()) for path in arguments.view] if arguments.guide is not None: parameters["guide"] = str(Path(arguments.guide).expanduser().absolute()) + if arguments.bbox is not None: + parameters["bbox"] = list(arguments.bbox) else: kind, names = VERBS[verb] parameters = {name: getattr(arguments, name) for name in names} + if verb == "music" and not parameters["keep_caption"]: + del parameters["keep_caption"] if verb == "video": for name in ("image", "audio"): if parameters[name] is not None: diff --git a/packages/codex/mlx-agent/src/mlx_agent/serving_plan.py b/packages/codex/mlx-agent/src/mlx_agent/serving_plan.py index 9751fa9..b788cfe 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/serving_plan.py +++ b/packages/codex/mlx-agent/src/mlx_agent/serving_plan.py @@ -104,7 +104,7 @@ def worker_config(plan, *, control_token, state_path, log_path=None, config_path for key in ( "jit", "prefill_kernel", "decode_profile", "vision_profile", "shared_prefix_cache", "splash_model_dir", "splash_model_fingerprint", "splash_draft_model", "splash_draft_fingerprint", - "splash_launcher", "splash_runtime_fingerprint", + "splash_launcher", "splash_runtime_fingerprint", "splash_project_cache_dir", "strata_memory_estimate_bytes", "strata_memory_growth_bytes", ): if key in plan: diff --git a/packages/codex/mlx-agent/src/mlx_agent/splash_runtime.py b/packages/codex/mlx-agent/src/mlx_agent/splash_runtime.py index 6640055..6c9f48c 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/splash_runtime.py +++ b/packages/codex/mlx-agent/src/mlx_agent/splash_runtime.py @@ -2,13 +2,16 @@ from __future__ import annotations +import errno import hashlib import json import math import os import re import shutil +import stat import subprocess +import sys from pathlib import Path from .serving_plan import Contribution @@ -32,6 +35,8 @@ "splash_thinking_token_budget": ("--thinking-token-budget", None), "splash_persistent_cache": ("--persistent-cache", None), "splash_max_cache_disk_gb": ("--max-cache-disk", None), + "splash_project_cache": ("--cache-dir", None), + "splash_max_cache_disk_writes_gb": ("--max-cache-disk-writes", None), } _TEMPLATE_BYTES = 1 << 20 @@ -284,10 +289,23 @@ def tuning_arguments(tuning): unknown = sorted(set(tuning) - set(TUNING)) if unknown: raise SplashError("invalid_arguments", "Unknown Splash settings: " + ", ".join(unknown), "Remove them.") + name = tuning.get("splash_project_cache") + writes = tuning.get("splash_max_cache_disk_writes_gb") + if name is not None: + if not isinstance(name, str) or not re.fullmatch(r"[a-z][a-z0-9_-]{0,63}", name): + raise _invalid("Splash project cache name must be a lowercase slug of at most 64 characters.", "--splash-project-cache") + if tuning.get("splash_persistent_cache") is False: + raise _invalid("A Splash project cache requires persistent caching.", "--splash-persistent-cache") + for key in ("splash_max_cache_disk_gb", "splash_max_cache_disk_writes_gb"): + value = tuning.get(key) + if type(value) not in (int, float) or not math.isfinite(value) or not 1 <= value * 1e9 <= 4096e9: + raise _invalid("A Splash project cache requires positive disk and write caps of at least one byte.", "--" + key.replace("_", "-")) + elif writes is not None: + raise _invalid("A Splash write cap requires a named project cache.", "--splash-project-cache") args = [] for key, (flag, choices) in TUNING.items(): value = tuning.get(key) - if value is None: + if value is None or key == "splash_project_cache": continue cli = "--splash-" + flag[2:] if choices is not None: @@ -307,9 +325,85 @@ def tuning_arguments(tuning): raise _invalid("Splash SSD cache size must be a finite value from 0 to 4096 GB; 0 turns it off.", cli + "-gb") else: args += [flag, str(math.floor(value * 1e9))] + if name is not None and not tuning.get("splash_persistent_cache"): + args.append("--persistent-cache") return args +def project_cache_directory(root, name, digest, fields): + """Derive a project cache namespace without creating it.""" + binding = {"project": name, "auth": digest, **fields} + namespace = hashlib.sha256(json.dumps(binding, sort_keys=True, separators=(",", ":")).encode()).hexdigest() + return str(Path(root).absolute() / "splash-cache" / namespace) + + +def _macos_acl_allows_access(fd): + """Check extended ACLs on the opened directory, independent of mode bits.""" + import ctypes + + libc = ctypes.CDLL(None, use_errno=True) + libc.acl_get_fd.argtypes = [ctypes.c_int] + libc.acl_get_fd.restype = ctypes.c_void_p + libc.acl_get_entry.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)] + libc.acl_get_tag_type.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)] + libc.acl_free.argtypes = [ctypes.c_void_p] + + acl = libc.acl_get_fd(fd) + if acl is None: + error = ctypes.get_errno() + if error == errno.ENOENT: # The opened directory has no ACL. + return False + raise OSError(error, os.strerror(error)) + try: + entry = ctypes.c_void_p() + tag = ctypes.c_int() + entry_id = 0 # ACL_FIRST_ENTRY + while libc.acl_get_entry(acl, entry_id, ctypes.byref(entry)) == 0: + if libc.acl_get_tag_type(entry, ctypes.byref(tag)) != 0: + error = ctypes.get_errno() + raise OSError(error, os.strerror(error)) + if tag.value != 2: # ACL_EXTENDED_DENY + return True + entry_id = -1 # ACL_NEXT_ENTRY + error = ctypes.get_errno() + if error != errno.EINVAL: # Darwin signals the end of the ACL with EINVAL. + raise OSError(error, os.strerror(error)) + return False + finally: + libc.acl_free(acl) + + +def prepare_project_cache(path): + """Create a private cache whose path other users cannot replace.""" + from .transactions import _walk_directory + + cache = Path(path) + uid = os.geteuid() + + def check_acl(fd): + if sys.platform == "darwin" and _macos_acl_allows_access(fd): + raise ValueError("Splash cache path must have no allow ACL entries: " + str(cache)) + + def check_ancestor(fd, child): + info = os.fstat(fd) + writable_by_others = info.st_mode & (stat.S_IWGRP | stat.S_IWOTH) + # A trusted sticky directory protects each child owned by root or uid. + # The traversal checks that child's ownership before descending again. + if info.st_uid not in (0, uid) or (writable_by_others and not info.st_mode & stat.S_ISVTX): + raise ValueError(f"Splash cache ancestor before {child!r} must be protected from other users' writes: {cache}") + check_acl(fd) + + for directory in (cache.parent, cache): + _, fd = _walk_directory(directory, create=True, component_hook=check_ancestor) + try: + info = os.fstat(fd) + if info.st_uid != uid or stat.S_IMODE(info.st_mode) != 0o700: + raise ValueError("Splash cache directory must be owned by the current user and mode 0700: " + str(directory)) + check_acl(fd) + finally: + os.close(fd) + + def reported_context_tokens(payload): if not isinstance(payload, dict): return None @@ -379,7 +473,8 @@ def plan_contribution(local_path, has_repo, repo, hf_cache, adapter_path, jit, r "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, - **{key: (tuning or {}).get(key) for key in TUNING}, + **{key: (tuning or {}).get(key) for key in TUNING + if key not in ("splash_project_cache", "splash_max_cache_disk_writes_gb") or key in (tuning or {})}, "splash_chat_template": template["path"] if template else None, "splash_chat_template_sha256": template["sha256"] if template else None, "weight_format": target["format"], "weight_bytes": target["weight_bytes"], 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 a748dfd..74957f1 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/task_kinds.py +++ b/packages/codex/mlx-agent/src/mlx_agent/task_kinds.py @@ -17,7 +17,8 @@ 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 .mesh import MeshError, plan_mesh, run_mesh, validate_bbox, validate_glb +from .segment import plan_segment, run_segment 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) @@ -129,12 +130,13 @@ def _validate_classification(parameters): def _validate_music(parameters): - allowed = {"caption", "lyrics", "duration", "steps", "seed", "bpm", "time_signature", "reference"} + allowed = {"caption", "lyrics", "duration", "steps", "seed", "bpm", "time_signature", "reference", "key", "keep_caption"} 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("bpm"), parameters.get("time_signature"), parameters.get("reference")) + parameters.get("bpm"), parameters.get("time_signature"), parameters.get("reference"), + parameters.get("key"), parameters.get("keep_caption", False)) def _validate_transcribe(parameters): @@ -162,6 +164,24 @@ def _validate_image_generation(parameters): return parameters +def _validate_segmentation(parameters): + _require_keys(parameters, ('image_path', 'box', 'mask_threshold'), ('points', 'labels'), + 'Segmentation requires image_path, box and mask_threshold.') + _require_absolute(parameters, 'image_path') + box = parameters['box'] + if not isinstance(box, list) or len(box) != 4 or any(type(n) is not int for n in box): + raise _invalid('box must contain four integer pixel coordinates.') + if box[0] < 0 or box[1] < 0 or box[0] >= box[2] or box[1] >= box[3]: + raise _invalid('box must be a nonempty positive pixel rectangle.') + points, labels = parameters.get('points', []), parameters.get('labels', []) + if (not isinstance(points, list) or not isinstance(labels, list) or len(points) != len(labels) + or any(not isinstance(p, list) or len(p) != 2 or any(type(n) is not int or n < 0 for n in p) for p in points) + or any(type(label) is not int or label not in (0, 1) for label in labels)): + raise _invalid('points and binary labels must be paired.') + _require_finite(parameters, 'mask_threshold') + return parameters + + def _validate_image_understanding(parameters): _require_keys(parameters, ("image_path", "prompt"), ("max_tokens", "temperature", "max_pixels"), "Image-understanding parameters need image_path, prompt and supported options.") @@ -203,7 +223,7 @@ def _validate_video_understanding(parameters): def _validate_mesh(parameters): - _require_keys(parameters, ("image_path",), ("steps", "seed", "resolution", "guidance", "max_faces", "denoiser_cache", "cache_memory_mib", "views", "guide"), + _require_keys(parameters, ("image_path",), ("steps", "seed", "resolution", "guidance", "max_faces", "denoiser_cache", "cache_memory_mib", "views", "guide", "bbox"), "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") @@ -216,6 +236,13 @@ def _validate_mesh(parameters): _require_finite(parameters, "guidance") if "guide" in parameters: _require_absolute(parameters, "guide") + if "bbox" in parameters: + if not isinstance(parameters["bbox"], list): + raise _invalid("bbox must be a list of three sizes.") + try: + validate_bbox(parameters["bbox"], parameters.get("guide")) + except ValueError as error: + raise _invalid(str(error)) from error if "views" in parameters and (not isinstance(parameters["views"], list) or any(not absolute_path(path) for path in parameters["views"])): raise _invalid("views must be an ordered list of absolute local paths.") @@ -240,7 +267,8 @@ 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"], bpm=parameters.get("bpm"), time_signature=parameters.get("time_signature"), - reference=parameters.get("reference")) + reference=parameters.get("reference"), key=parameters.get("key"), + keep_caption=parameters.get("keep_caption", False)) def _plan_transcribe(model, parameters, output, media, directory): @@ -272,7 +300,7 @@ def _plan_video_understanding(model, parameters, output, media, directory): 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", "views", "guide"))) + return plan_mesh(model, media, output, **_options(parameters, ("steps", "seed", "resolution", "guidance", "max_faces", "denoiser_cache", "cache_memory_mib", "views", "guide", "bbox"))) def _check_mesh_output(path, plan): @@ -329,6 +357,9 @@ def check(path, plan, runner=subprocess.run): KINDS: Dict[str, TaskKind] = {kind.name: kind for kind in ( + TaskKind('image_segmentation', 'segment/1', False, _validate_segmentation, plan_segment, + lambda plan, **options: run_segment(plan, **options), input_field='image_path', input_media='image', + output='output.png', output_check=lambda path, plan: check_png(path, plan)), 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, **options: run_decide(plan, **options)), diff --git a/packages/codex/mlx-agent/src/mlx_agent/task_serving.py b/packages/codex/mlx-agent/src/mlx_agent/task_serving.py index e35946a..16e78fd 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/task_serving.py +++ b/packages/codex/mlx-agent/src/mlx_agent/task_serving.py @@ -26,6 +26,7 @@ from .task_store import TaskStore _TASK_IDENTITY_KEYS = ("model_path", "model_fingerprint", "executable", "executable_identity", "backend_manifest_hash") +WORKER_MARGIN_BYTES = 512_000_000 def same_task_identity(left, right): @@ -33,7 +34,6 @@ def same_task_identity(left, right): return isinstance(left, dict) and isinstance(right, dict) and all( left.get(key) == right.get(key) for key in _TASK_IDENTITY_KEYS) - def runtime_fingerprint(backend): source = Path(__file__).parent from .resident_worker import RUNNERS @@ -77,7 +77,7 @@ def _trellis_component_budget(model_path, kind, plan, telemetry, *, warm): 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']} + 'mesh_generation': ['mesh_generation'], 'image_segmentation': ['image_segmentation']} def resolve_model(path, manifests=None, registries=None, root=None, capture=True): @@ -372,7 +372,7 @@ def submit(self, body): self.release() raise error - def _admit_task_memory(self, request, plan, budget_gb, lease, check_cancelled): + def _admit_task_memory(self, request, plan, budget_gb, lease, check_cancelled, diagnostics=None): """Retry complete admission once after an opted-in idle cache reclaim.""" for attempt in range(2): try: @@ -384,7 +384,8 @@ def _admit_task_memory(self, request, plan, budget_gb, lease, check_cancelled): 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) + None if budget_gb is None else math.ceil(budget_gb * 1e9), self.memory_probe, diagnostics, + overhead_bytes=WORKER_MARGIN_BYTES if budget_gb is None else 0) except MemoryAdmissionError as error: self._record_memory_failure('task_admission', error.code, error.details) raise GatewayError(503, error.code, str(error)) from error @@ -451,9 +452,11 @@ def check_cancelled(): if self._task_cancelled(identifier): cancelled_before_dispatch = True raise InterruptedError('Inference cancelled.') - capacity = self._admit_task_memory(request, plan, budget_gb, lease, check_cancelled) + memory_admission = {} + capacity = self._admit_task_memory(request, plan, budget_gb, lease, check_cancelled, memory_admission) check_cancelled() - worker_limit = None if capacity is None else max(1, capacity - 512_000_000) + worker_limit = (None if capacity is None else capacity if budget_gb is None + else max(1, capacity - WORKER_MARGIN_BYTES)) with self.condition: if self.closed: raise InterruptedError('Endpoint stopping.') @@ -487,6 +490,7 @@ def check_cancelled(): if kind.name == 'video_generation' and releases_after_request(policy): plan['argv'].append('--no-retain-weights') result = kind.run(plan, runner=runner) + result['memory_admission'] = memory_admission self._confirm_identity(record) self.store.read_request(identifier) if record['schema'] == 'task-run/3': diff --git a/packages/codex/mlx-agent/src/mlx_agent/taxonomy.py b/packages/codex/mlx-agent/src/mlx_agent/taxonomy.py index f570915..65e3fc1 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", "vision_projector", "other", + "embedding", "classification", "image_generation", "image_segmentation", "source_separation", "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 = { @@ -26,6 +26,8 @@ "embedding": ("reranking", "retrieval"), "classification": ("moderation", "routing", "classification"), "image_generation": ("image_generation",), + "image_segmentation": ("image_segmentation",), + "source_separation": ("source_separation",), "video_generation": ("video_generation",), "mesh_generation": ("mesh_generation",), "music_generation": ("music_generation",), @@ -51,10 +53,12 @@ "text-ranking": "embedding", "text-classification": "classification", "zero-shot-classification": "classification", + "token-classification": "classification", "text-to-image": "image_generation", "image-to-image": "image_generation", "text-to-video": "video_generation", "image-to-3d": "mesh_generation", + "text-to-3d": "mesh_generation", } _SPECIFIC_TOKENS = ( ("coding", ("code", "coder", "coding", "starcoder", "codestral", "devstral")), @@ -117,6 +121,10 @@ def _type_from_hits(hits, config_keys, haystack, vision_module=False, allow_visi return "classification" if "image_generation" in categories: return "image_generation" + if "image_segmentation" in categories: + return "image_segmentation" + if "source_separation" in categories: + return "source_separation" if "mesh_generation" in categories: return "mesh_generation" if "video_generation" in categories: @@ -218,7 +226,7 @@ def read_config_type(directory): def annotate_inventory(report, manifests=None, registries=None): - """Add a "task" object to every scanned GGUF model and MLX output.""" + """Add a "task" object to every scanned GGUF model, MLX output and Ollama model.""" if manifests is None: try: manifests = load_manifests() @@ -249,6 +257,14 @@ def annotate_inventory(report, manifests=None, registries=None): backend = output_backend(model_type, keys, output["task"]["type"], manifests, registries) if backend is not None: output["backend"] = backend + for model in report.get("ollama", []): + # An Ollama GGUF names a llama.cpp architecture; a safetensors import names its config model_type. + gguf_format = model.get("format") == "gguf" + model["task"] = classify( + model.get("name"), model_type=None if gguf_format else model.get("architecture"), + gguf_architecture=model.get("architecture") if gguf_format else None, + manifests=manifests, registries=registries, local=True, draft=model.get("draft") is not None, + ) return report diff --git a/packages/codex/mlx-agent/src/mlx_agent/transcribe.py b/packages/codex/mlx-agent/src/mlx_agent/transcribe.py index 8acfe32..7b3f515 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/transcribe.py +++ b/packages/codex/mlx-agent/src/mlx_agent/transcribe.py @@ -26,7 +26,7 @@ class TranscribeError(InferenceError): """Classified transcription failure safe to surface in a result envelope.""" -def plan_transcribe(model_path, audio_path, language=None, manifests=None, registries=None, root=None): +def plan_transcribe(model_path, audio_path, language=None, manifests=None, registries=None, root=None, words=False): """Pick the speech backend for a converted model directory; pure apart from reading config.json.""" model = Path(model_path).expanduser().resolve() try: @@ -59,20 +59,30 @@ def plan_transcribe(model_path, audio_path, language=None, manifests=None, regis argv = [str(backend_python(manifest, root)), str(TRANSCRIBE_RUNNER), "--model", str(model), "--audio", str(audio)] if language: argv += ["--language", language] - return {"backend": manifest["id"], "model": str(model), "audio": str(audio), "language": language, "argv": argv} + if words: + argv.append("--words") + return {"backend": manifest["id"], "model": str(model), "audio": str(audio), "language": language, + "words": bool(words), "argv": argv} CONTRACT = RunnerContract( - verb="transcribe", error=TranscribeError, accept=lambda value, plan: isinstance(value.get("text"), str), + verb="transcribe", error=TranscribeError, + accept=lambda value, plan: isinstance(value.get("text"), str) and ( + not plan.get("words") or isinstance(value.get("words"), list)), action="transcribe the clip", remediation="Check that the directory is a complete converted speech model.", activity="Transcription", timeout_remediation="Use a shorter clip or a larger --timeout.", + refusals={"words_unsupported": lambda plan, detail: ( + "{0} gives no word times.".format(detail), "Use a Whisper model for --words.")}, ) def run_transcribe(plan, manifests=None, root=None, timeout=DEFAULT_TIMEOUT_SECONDS, runner=subprocess.run): result = invoke(plan, CONTRACT, manifests, root, timeout, runner) - return { + transcript = { "schema": TRANSCRIBE_SCHEMA, "backend": plan["backend"], "model": plan["model"], "audio": plan["audio"], "language": plan["language"], "text": result["text"], "seconds": result.get("seconds"), "audio_seconds": result.get("audio_seconds"), } + if plan.get("words"): + transcript["words"] = result["words"] + return transcript 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 e793124..5fb0778 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/transcribe_runner.py +++ b/packages/codex/mlx-agent/src/mlx_agent/transcribe_runner.py @@ -11,6 +11,9 @@ else: from runner_model_cache import load_model as retained_load +# Audio left after the last heard segment that is decoded again. +RESUME_SECONDS = 1.0 + def _restore_whisper_end_token(model): """Give a Whisper tokenizer the no-speech token its vocabulary has. @@ -46,6 +49,7 @@ def main(argv=None): parser.add_argument("--model", required=True) parser.add_argument("--audio", required=True) parser.add_argument("--language", default=None) + parser.add_argument("--words", action="store_true") arguments = parser.parse_args(argv) from mlx_audio.stt.utils import load_audio, load_model @@ -55,15 +59,38 @@ def main(argv=None): _restore_whisper_end_token(model) samples = load_audio(arguments.audio) kwargs = {} - if arguments.language and "language" in inspect.signature(model.generate).parameters: + parameters = inspect.signature(model.generate).parameters + if arguments.language and "language" in parameters: kwargs["language"] = arguments.language + if arguments.words: + if "word_timestamps" not in parameters: + print(json.dumps({"error": "words_unsupported", "detail": type(model).__name__}), flush=True) + return 2 + kwargs["word_timestamps"] = True output = model.generate(arguments.audio, **kwargs) - text = getattr(output, "text", output if isinstance(output, str) else "") - print(json.dumps({ - "text": str(text).strip(), + text = str(getattr(output, "text", output if isinstance(output, str) else "")) + segments = list(getattr(output, "segments", None) or []) + audio_seconds = int(samples.shape[0]) / 16000 + # Whisper can end a clip's text early on sung audio and skip the rest; decode again from the last segment. + while "clip_timestamps" in parameters and segments and audio_seconds - float(segments[-1]["end"]) >= RESUME_SECONDS: + heard_until = float(segments[-1]["end"]) + later = list(getattr(model.generate(arguments.audio, **kwargs, clip_timestamps=[heard_until]), "segments", None) or []) + if not later or float(later[-1]["end"]) <= heard_until: + break + segments += later + # Whisper's decoded segments carry their own spacing. + text += "".join(str(segment["text"]) for segment in later) + result = { + "text": text.strip(), "seconds": round(time.time() - started, 3), - "audio_seconds": round(int(samples.shape[0]) / 16000, 3), - }), flush=True) + "audio_seconds": round(audio_seconds, 3), + } + if arguments.words: + result["words"] = [ + {"word": str(word["word"]).strip(), "start": round(float(word["start"]), 3), "end": round(float(word["end"]), 3)} + for segment in segments for word in segment.get("words") or [] + ] + print(json.dumps(result), flush=True) return 0 diff --git a/packages/codex/mlx-agent/src/mlx_agent/worker_telemetry.py b/packages/codex/mlx-agent/src/mlx_agent/worker_telemetry.py index e7a8fee..3c9bf36 100644 --- a/packages/codex/mlx-agent/src/mlx_agent/worker_telemetry.py +++ b/packages/codex/mlx-agent/src/mlx_agent/worker_telemetry.py @@ -39,13 +39,23 @@ def validate(value): return value -def capture(statistics): +def capture(statistics, framework='mlx'): 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) + if framework == 'torch': + torch = sys.modules.get('torch') + mps = getattr(torch, 'mps', None) try: - result[field]=function() if callable(function) else None - except (RuntimeError,NotImplementedError): - result[field]=None + result['active_bytes'] = mps.current_allocated_memory() if mps is not None else None + except (RuntimeError, NotImplementedError): + result['active_bytes'] = None + result['cache_bytes'] = None + result['peak_bytes'] = None + else: + 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/providers/agy/catalog.json b/providers/agy/catalog.json index 4de33c7..02ae039 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.16.0 --depth 1 https://github.com/cavi-ai/mlx-agent.git && agy plugin install ./mlx-agent/providers/agy" + "command": "git clone --branch v0.17.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 3b52e14..f5d0574 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.16.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.17.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 55b35aa..8dd6850 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.16.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.17.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 4582747..edd2cce 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.16.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.17.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 d787354..b8ee58e 100644 --- a/releases.json +++ b/releases.json @@ -1,7 +1,7 @@ { "mlx-agent": { - "tag": "v0.16.0", - "commit": "854341a6ce44a0b09dea2dbf012b411919de9847" + "tag": "v0.17.0", + "commit": "26e35745620679c60ae70b017213717f63e03252" }, "obsidian-agent": { "tag": "v0.3.0",