Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .claude-plugin/marketplace.json
Original file line number Diff line number Diff line change
Expand Up @@ -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."
},
Expand Down
4 changes: 2 additions & 2 deletions packages/codex/expected-integrity.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
2 changes: 1 addition & 1 deletion packages/codex/mlx-agent/.codex-plugin/plugin.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
4 changes: 2 additions & 2 deletions packages/codex/mlx-agent/provenance.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"repository": "cavi-ai/mlx-agent",
"source_commit": "854341a6ce44a0b09dea2dbf012b411919de9847",
"source_commit": "26e35745620679c60ae70b017213717f63e03252",
"source_path": "providers/codex",
"included": [
".codex-plugin",
Expand All @@ -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"
}
}
2 changes: 1 addition & 1 deletion packages/codex/mlx-agent/src/mlx_agent/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
from .contracts import ResultEnvelope

__all__ = ["ResultEnvelope"]
__version__ = "0.16.0"
__version__ = "0.17.0"
68 changes: 68 additions & 0 deletions packages/codex/mlx-agent/src/mlx_agent/acestep_compose_runner.py
Original file line number Diff line number Diff line change
@@ -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())
46 changes: 40 additions & 6 deletions packages/codex/mlx-agent/src/mlx_agent/acestep_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand All @@ -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)
Expand All @@ -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, \
Expand All @@ -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:
Expand All @@ -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()
Expand All @@ -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


Expand Down
26 changes: 25 additions & 1 deletion packages/codex/mlx-agent/src/mlx_agent/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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}")
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 {}
Expand Down
Loading