Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: keep music renders alive during inference

Adam Eivyfd8eab81e368
diff --git a/scripts/_runner_common.py b/scripts/_runner_common.py
index 1ba93f4425..a212421e06 100644
--- a/scripts/_runner_common.py
+++ b/scripts/_runner_common.py
@@ -1,13 +1,16 @@
"""
-Shared helpers for the PortOS local image-gen Python runners
-(`flux2_macos.py` and `z_image_turbo.py`).
+Shared helpers for the PortOS local image and music-generation Python runners.
-Both runners present the same CLI surface to `server/services/imageGen/local.js`
+The image runners present the same CLI surface to `server/services/imageGen/local.js`
— STAGE: markers, USER_ERROR: lines, stepwise PNG previews, sidecar JSON — and
the bits that own that contract live here. Keeping these in one module means a
fix to the HF error mapping or the stepwise decode lands in both runners at
once, instead of drifting.
+Music sidecars reuse the liveness portion of that contract: a long model load or
+inference call must emit periodic STAGE heartbeat markers so the media queue can
+distinguish a slow render from a wedged child.
+
The runner-specific bits each script still owns:
- argparse + which pipeline class / weight repo to load
- `load_pipeline_*` (sdnq / int8 / auto-pipeline / ERNIE)
@@ -61,14 +64,15 @@ def register_source_namespace(package_name: str, package_dir: "str | Path"):
@contextmanager
def heartbeat(stage: "str | Callable[[], str]", interval: float = 20.0):
"""Emit a periodic STAGE:<stage>:heartbeat:Ns marker so the JS idle
- watchdog (default 5min) doesn't kill silent long pipeline loads.
-
- Diffusers' from_pretrained on a fully-cached 10-25 GB model is silent
- for several minutes (mmap + weight assignment, no tqdm), which trips
- the JS-side idle watchdog. `handleLine()` in imageGen/local.js sees
- the heartbeat line and resets lastActivityAt. True hangs (GIL-pinned
- C extension, no I/O) still trip the watchdog because the heartbeat
- thread can't print either.
+ watchdog doesn't kill a silent but active model load or inference call.
+
+ Diffusers' from_pretrained on a fully-cached 10-25 GB model, and music
+ inference calls, can be silent for several minutes (mmap + weight
+ assignment, no tqdm), which trips the JS-side idle watchdog.
+ `handleLine()` in imageGen/local.js and the audio sidecar bridge see the
+ heartbeat line and reset lastActivityAt. True hangs (GIL-pinned C
+ extension, no I/O) still trip the watchdog because the heartbeat thread
+ can't print either.
`stage` may be a callable resolved per beat, for a runner that wraps a
whole child process rather than one load step: generate_fastvideo.py scrapes
diff --git a/scripts/generate_acestep.py b/scripts/generate_acestep.py
index d6d653a8a8..51d0c2333c 100644
--- a/scripts/generate_acestep.py
+++ b/scripts/generate_acestep.py
@@ -40,6 +40,9 @@ import sys
import tempfile
import wave
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _runner_common import heartbeat # noqa: E402
+
def log_stage(name, detail=""):
"""Emit a STAGE: line the JS sidecar tails for phase/progress display."""
@@ -130,12 +133,13 @@ def main():
checkpoint_dir = os.environ.get("PORTOS_ACESTEP_CHECKPOINT_DIR", "") or None
log_stage("load-model", args.model)
- pipe = ACEStepPipeline(
- checkpoint_dir=checkpoint_dir,
- device_id=device_id,
- dtype=dtype,
- cpu_offload=is_cpu,
- )
+ with heartbeat("load-model"):
+ pipe = ACEStepPipeline(
+ checkpoint_dir=checkpoint_dir,
+ device_id=device_id,
+ dtype=dtype,
+ cpu_offload=is_cpu,
+ )
# ACE-Step's __call__ appends its OWN timestamped filename when save_path is a
# directory, so we render into a temp dir and then move the single produced
@@ -147,16 +151,17 @@ def main():
with tempfile.TemporaryDirectory(prefix="acestep-") as tmp:
log_stage("generate", f"{duration:.1f}s/{steps}steps")
manual_seeds = [int(args.seed)] if args.seed else None
- pipe(
- format="wav",
- audio_duration=duration,
- prompt=text,
- lyrics=(args.lyrics or ""),
- infer_step=steps,
- guidance_scale=float(args.guidance or 15.0),
- manual_seeds=manual_seeds,
- save_path=tmp,
- )
+ with heartbeat("generate"):
+ pipe(
+ format="wav",
+ audio_duration=duration,
+ prompt=text,
+ lyrics=(args.lyrics or ""),
+ infer_step=steps,
+ guidance_scale=float(args.guidance or 15.0),
+ manual_seeds=manual_seeds,
+ save_path=tmp,
+ )
log_stage("encode-wav")
produced = sorted(glob.glob(os.path.join(tmp, "*.wav")))
diff --git a/scripts/generate_acestep15.py b/scripts/generate_acestep15.py
index eb792a1705..0d2ee55a8e 100644
--- a/scripts/generate_acestep15.py
+++ b/scripts/generate_acestep15.py
@@ -16,6 +16,9 @@ import sys
import tempfile
import wave
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _runner_common import heartbeat # noqa: E402
+
MODEL_ID = "ACE-Step/Ace-Step1.5"
MODEL_VARIANT = "acestep-v15-turbo"
@@ -58,7 +61,8 @@ def main():
stage("resolve-model", args.model)
try:
- checkpoint_dir = cached_checkpoint_dir(args.model)
+ with heartbeat("resolve-model"):
+ checkpoint_dir = cached_checkpoint_dir(args.model)
except Exception as exc:
print(f"ERROR: ACE-Step 1.5 model weights are not installed: {exc}", file=sys.stderr, flush=True)
return 1
@@ -73,13 +77,14 @@ def main():
duration = max(1.0, min(float(args.duration or 60.0), 240.0))
stage("load-model", MODEL_VARIANT)
- dit_handler = AceStepHandler()
- status, initialized = dit_handler.initialize_service(
- project_root="",
- config_path=MODEL_VARIANT,
- device="auto",
- offload_to_cpu=False,
- )
+ with heartbeat("load-model"):
+ dit_handler = AceStepHandler()
+ status, initialized = dit_handler.initialize_service(
+ project_root="",
+ config_path=MODEL_VARIANT,
+ device="auto",
+ offload_to_cpu=False,
+ )
if not initialized:
print(f"ERROR: ACE-Step 1.5 could not initialize: {status}", file=sys.stderr, flush=True)
return 1
@@ -104,13 +109,14 @@ def main():
# failed/partial generation — is cleaned up automatically when the `with`
# block exits, instead of lingering as a phantom track in the library.
with tempfile.TemporaryDirectory(prefix="acestep15-") as tmp:
- result = generate_music(
- dit_handler=dit_handler,
- llm_handler=None,
- params=params,
- config=GenerationConfig(batch_size=1, audio_format="wav"),
- save_dir=tmp,
- )
+ with heartbeat("generate"):
+ result = generate_music(
+ dit_handler=dit_handler,
+ llm_handler=None,
+ params=params,
+ config=GenerationConfig(batch_size=1, audio_format="wav"),
+ save_dir=tmp,
+ )
if not result.success or not result.audios:
reason = getattr(result, "error", None) or getattr(result, "status_message", "unknown error")
print(f"ERROR: ACE-Step 1.5 generation failed: {reason}", file=sys.stderr, flush=True)
diff --git a/scripts/generate_audioldm2.py b/scripts/generate_audioldm2.py
index 509a27ffa2..061045c6a7 100644
--- a/scripts/generate_audioldm2.py
+++ b/scripts/generate_audioldm2.py
@@ -33,6 +33,9 @@ import os
import sys
import wave
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _runner_common import heartbeat # noqa: E402
+
# AudioLDM2 decodes audio at 16 kHz (fixed by the model's VAE / vocoder).
SAMPLE_RATE = 16000
@@ -180,8 +183,9 @@ def main():
dtype = torch.float32 if device == "cpu" else torch.float16
log_stage("load-model", args.model)
- pipe = AudioLDM2Pipeline.from_pretrained(args.model, torch_dtype=dtype)
- pipe = pipe.to(device)
+ with heartbeat("load-model"):
+ pipe = AudioLDM2Pipeline.from_pretrained(args.model, torch_dtype=dtype)
+ pipe = pipe.to(device)
# transformers >=4.50 compatibility: restore the generation helpers the
# pipeline's language-model loop relies on (see helper docstring).
_patch_language_model_generation(pipe)
@@ -194,13 +198,14 @@ def main():
generator = torch.Generator(device=generator_device).manual_seed(int(args.seed or 0))
log_stage("generate", f"{duration:.1f}s/{steps}steps")
- out = pipe(
- text,
- num_inference_steps=steps,
- audio_length_in_s=duration,
- guidance_scale=float(args.guidance or 3.5),
- generator=generator,
- )
+ with heartbeat("generate"):
+ out = pipe(
+ text,
+ num_inference_steps=steps,
+ audio_length_in_s=duration,
+ guidance_scale=float(args.guidance or 3.5),
+ generator=generator,
+ )
log_stage("encode-wav")
pcm = _to_int16_pcm(out.audios)
diff --git a/scripts/generate_minimax_music3.py b/scripts/generate_minimax_music3.py
index 25ef0c5849..284518b70a 100644
--- a/scripts/generate_minimax_music3.py
+++ b/scripts/generate_minimax_music3.py
@@ -8,7 +8,8 @@ import sys
import time
import wave
-from _runner_common import choose_cuda_pipeline_placement
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _runner_common import choose_cuda_pipeline_placement, heartbeat
FULL_CUDA_PROFILE = 'cuda-bf16-full'
@@ -130,22 +131,24 @@ def main():
if not torch.cuda.is_available():
raise RuntimeError('MiniMax Music 3 requires CUDA')
print('STAGE:load-model', file=sys.stderr, flush=True)
- components_manager = ComponentsManager()
- pipe = ModularPipeline.from_pretrained(args.model, components_manager=components_manager)
- pipe.load_components(dtype=torch.bfloat16)
- execution_profile = place_minimax_pipeline(pipe, components_manager, torch)
+ with heartbeat('load-model'):
+ components_manager = ComponentsManager()
+ pipe = ModularPipeline.from_pretrained(args.model, components_manager=components_manager)
+ pipe.load_components(dtype=torch.bfloat16)
+ execution_profile = place_minimax_pipeline(pipe, components_manager, torch)
print('STAGE:generate', file=sys.stderr, flush=True)
torch.cuda.reset_peak_memory_stats()
generation_kwargs = seeded_generation_kwargs(pipe, torch, args.seed)
if args.seed is not None and not generation_kwargs:
raise RuntimeError('this Diffusers pipeline does not support deterministic --seed generation')
- audio = to_numpy(pipe(
- prompt=args.text,
- lyrics=args.lyrics,
- audio_duration=float(max(1, min(300, args.duration))),
- output='audios',
- **generation_kwargs,
- )[0], np, torch)
+ with heartbeat('generate'):
+ audio = to_numpy(pipe(
+ prompt=args.text,
+ lyrics=args.lyrics,
+ audio_duration=float(max(1, min(300, args.duration))),
+ output='audios',
+ **generation_kwargs,
+ )[0], np, torch)
audio = to_stereo(audio, np)
torch.cuda.synchronize()
peak_vram_allocated_gb = torch.cuda.max_memory_allocated() / (1024 ** 3)
diff --git a/scripts/generate_minimax_music3_mlx.py b/scripts/generate_minimax_music3_mlx.py
index 1f240663ca..a6dbce90ea 100644
--- a/scripts/generate_minimax_music3_mlx.py
+++ b/scripts/generate_minimax_music3_mlx.py
@@ -7,6 +7,9 @@ import os
import sys
import wave
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _runner_common import heartbeat # noqa: E402
+
TARGET_SAMPLE_RATE = 32000
@@ -63,24 +66,26 @@ def main():
from mlx_audio.music import load
print("STAGE:load-model", file=sys.stderr, flush=True)
- model = load(args.model, revision=args.revision) if args.revision else load(args.model)
+ with heartbeat("load-model"):
+ model = load(args.model, revision=args.revision) if args.revision else load(args.model)
print("STAGE:generate", file=sys.stderr, flush=True)
requested_duration = float(max(1, min(300, args.duration)))
chunks = []
sample_rate = None
- for result in model.generate(
- text=args.text,
- lyrics=args.lyrics,
- duration=requested_duration,
- steps=args.steps,
- seed=args.seed,
- ):
- result_rate = int(result.sample_rate)
- if sample_rate is None:
- sample_rate = result_rate
- elif result_rate != sample_rate:
- raise RuntimeError("MiniMax Music 3 MLX returned inconsistent sample rates")
- chunks.append(to_stereo(result.audio, np))
+ with heartbeat("generate"):
+ for result in model.generate(
+ text=args.text,
+ lyrics=args.lyrics,
+ duration=requested_duration,
+ steps=args.steps,
+ seed=args.seed,
+ ):
+ result_rate = int(result.sample_rate)
+ if sample_rate is None:
+ sample_rate = result_rate
+ elif result_rate != sample_rate:
+ raise RuntimeError("MiniMax Music 3 MLX returned inconsistent sample rates")
+ chunks.append(to_stereo(result.audio, np))
if not chunks or sample_rate is None:
raise RuntimeError("MiniMax Music 3 MLX produced no audio")
diff --git a/scripts/generate_musicgen.py b/scripts/generate_musicgen.py
index 874d524b36..59aa59427e 100644
--- a/scripts/generate_musicgen.py
+++ b/scripts/generate_musicgen.py
@@ -31,6 +31,9 @@ import os
import sys
import wave
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from _runner_common import heartbeat # noqa: E402
+
# MusicGen decodes audio at 32 kHz; the EnCodec frame rate is 50 Hz, so one
# second of audio is 50 decoder steps. Both are fixed by the model.
@@ -114,10 +117,12 @@ def main():
MusicGen = _import_musicgen(args.runtime_dir)
log_stage("load-model", args.model)
- model = MusicGen.from_pretrained(args.model)
+ with heartbeat("load-model"):
+ model = MusicGen.from_pretrained(args.model)
log_stage("generate", f"{duration:.1f}s/{max_steps}steps")
- audio = model.generate(text, max_steps=max_steps)
+ with heartbeat("generate"):
+ audio = model.generate(text, max_steps=max_steps)
log_stage("encode-wav")
pcm = _to_int16_pcm(audio)
diff --git a/scripts/musicSidecarHeartbeat.test.js b/scripts/musicSidecarHeartbeat.test.js
new file mode 100644
index 0000000000..ad685714aa
--- /dev/null
+++ b/scripts/musicSidecarHeartbeat.test.js
@@ -0,0 +1,22 @@
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+import { describe, expect, it } from 'vitest';
+
+const SCRIPTS_DIR = dirname(fileURLToPath(import.meta.url));
+const MUSIC_SIDECARS = [
+ 'generate_acestep.py',
+ 'generate_acestep15.py',
+ 'generate_audioldm2.py',
+ 'generate_minimax_music3.py',
+ 'generate_minimax_music3_mlx.py',
+ 'generate_musicgen.py',
+];
+
+describe('music sidecar liveness contract', () => {
+ it.each(MUSIC_SIDECARS)('%s keeps the media-job watchdog alive during long work', (filename) => {
+ const source = readFileSync(join(SCRIPTS_DIR, filename), 'utf8');
+ expect(source).toMatch(/from _runner_common import[\s\S]*\bheartbeat\b/);
+ expect(source).toMatch(/with heartbeat\([\s\S]*?["']generate["']/);
+ });
+});