ACloudCenter Claude Fable 5.1 commited on
Commit
d875227
·
1 Parent(s): 797f6c7

Cut Modal cold start from ~3 min to ~30 s: bake weights, memory snapshot

Browse files

Every cold container was re-downloading both VibeVoice checkpoints (~17 GB)
from the Hub inside container start. The image now bakes the checkpoints plus
the Qwen2.5-1.5B/7B tokenizer files the processor loads, and the class runs
with enable_memory_snapshot: load_models (snap=True) fills CPU RAM once per
deploy, move_to_gpu (snap=False) copies to the A100 on every boot.

Measured on the deployed app (v21, 2026-09-12): 29 s from request to a ready
GPU, versus 110-180 s before. Standing cost unchanged (tail profile).

Also: boot_check local entrypoint (--deployed pokes the live app), UI/README
cold-start copy updated to ~30 s, VRAM baseline comment corrected to the
measured 24.1 GB. Not HF_HUB_OFFLINE: v20 crash-looped when the un-baked
tokenizer repo could not be fetched.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017bjX8vNkBk9Rjt2SToVF75

Files changed (5) hide show
  1. README.md +1 -1
  2. app.py +1 -1
  3. backend_modal/modal_runner.py +92 -26
  4. static/app.js +2 -2
  5. static/index.html +1 -1
README.md CHANGED
@@ -87,7 +87,7 @@ The lightweight FastAPI frontend (this repo, hosted as a Docker Space) is separa
87
 
88
  - **Frontend** (`app.py` + `static/`): script generation via the HF Inference API, script parsing, an SSE endpoint that relays progress and streamed chunk audio from Modal, post-processing (tone shelves, loudness normalization, spectral denoise, time-stretch), MP3 encoding, and byte-range serving of finished takes. Takes live in memory for 15 minutes.
89
  - **Backend** (`backend_modal/modal_runner.py`): a Modal class that loads both models at container start and exposes `generate_podcast` as a streaming generator. Deployed separately. The VibeVoice model code and reference voice WAVs alongside it are gitignored.
90
- - **Scaling profiles**: the backend deploys with `VIBEVOICE_PROFILE=launch` (one container always warm, one buffer under load) or `tail` (scale to zero). Both cap at 4 concurrent GPUs; extra requests queue. The first generation after idle in `tail` mode takes ~3 minutes to load models, and the UI says so when the GPU is cold.
91
  - **Limits** (public demo): scripts up to 7,000 words (~45 min), 3 generations per hour per IP, 60 per day across all visitors, 4 in flight globally. The backend has no length ceiling; the multi-hour records were rendered by calling it directly.
92
 
93
  ---
 
87
 
88
  - **Frontend** (`app.py` + `static/`): script generation via the HF Inference API, script parsing, an SSE endpoint that relays progress and streamed chunk audio from Modal, post-processing (tone shelves, loudness normalization, spectral denoise, time-stretch), MP3 encoding, and byte-range serving of finished takes. Takes live in memory for 15 minutes.
89
  - **Backend** (`backend_modal/modal_runner.py`): a Modal class that loads both models at container start and exposes `generate_podcast` as a streaming generator. Deployed separately. The VibeVoice model code and reference voice WAVs alongside it are gitignored.
90
+ - **Scaling profiles**: the backend deploys with `VIBEVOICE_PROFILE=launch` (one container always warm, one buffer under load) or `tail` (scale to zero). Both cap at 4 concurrent GPUs; extra requests queue. The model weights are baked into the image and the loaded process is memory-snapshotted, so a cold container in `tail` mode restores the snapshot and copies weights to the GPU instead of re-downloading ~17 GB from the Hub (which was most of the old ~3 minute cold start). Measured 2026-09-12: 29 s from request to a ready GPU. The UI still warns when the GPU is cold.
91
  - **Limits** (public demo): scripts up to 7,000 words (~45 min), 3 generations per hour per IP, 60 per day across all visitors, 4 in flight globally. The backend has no length ceiling; the multi-hour records were rendered by calling it directly.
92
 
93
  ---
app.py CHANGED
@@ -727,7 +727,7 @@ async def _backend_stats() -> dict | None:
727
  @app.get("/api/status")
728
  async def api_status() -> dict:
729
  """Backend reachability plus, when Modal reports it, whether a GPU container
730
- is already hot — the UI uses that to warn about the ~3 min cold path."""
731
  payload = {
732
  "backend": "ready" if remote_generate_function is not None else "offline",
733
  "daily_remaining": _audio_budget_remaining(),
 
727
  @app.get("/api/status")
728
  async def api_status() -> dict:
729
  """Backend reachability plus, when Modal reports it, whether a GPU container
730
+ is already hot — the UI uses that to warn about the ~30 s cold path (snapshot restore + GPU copy)."""
731
  payload = {
732
  "backend": "ready" if remote_generate_function is not None else "offline",
733
  "daily_remaining": _audio_budget_remaining(),
backend_modal/modal_runner.py CHANGED
@@ -17,7 +17,7 @@ import modal
17
  # --- Scaling profiles (2026-09-06) ---------------------------------------
18
  # Chosen at deploy time: VIBEVOICE_PROFILE=launch modal deploy backend_modal/modal_runner.py
19
  # "launch": one container always hot + one pre-warmed buffer under load, so a
20
- # public-post burst lands warm instead of paying the ~3 min model load.
21
  # "tail": scale to zero when idle (default). Same cap and idle window, so the
22
  # only thing that changes is the standing spend.
23
  # max_containers is the spending cap in both: a 5th concurrent request queues
@@ -31,6 +31,32 @@ if SCALING_PROFILE not in SCALING_PROFILES:
31
  raise SystemExit(f"VIBEVOICE_PROFILE must be one of {sorted(SCALING_PROFILES)}, got {SCALING_PROFILE!r}")
32
  print(f"Deploying with scaling profile '{SCALING_PROFILE}': {SCALING_PROFILES[SCALING_PROFILE]}")
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  # Define the Modal Stub
35
  image = (
36
  modal.Image.debian_slim(python_version="3.10")
@@ -58,6 +84,14 @@ image = (
58
  )
59
  .env({"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}) # fights fragmentation across waves
60
  .env({"VIBEVOICE_PROFILE": SCALING_PROFILE}) # so container logs name the profile they run under
 
 
 
 
 
 
 
 
61
  .add_local_dir("backend_modal/modular", remote_path="/root/modular")
62
  .add_local_dir("backend_modal/processor", remote_path="/root/processor")
63
  .add_local_dir("backend_modal/voices", remote_path="/root/voices")
@@ -88,16 +122,21 @@ cache_volume = modal.Volume.from_name("vibevoice-cache", create_if_missing=True)
88
  # with cloned voices runs slower than the preset-voice record
89
  # pace (bigger reference prefill per chunk), so give 2h.
90
  volumes={"/cache": cache_volume},
 
 
 
 
 
 
 
91
  **SCALING_PROFILES[SCALING_PROFILE],
92
  )
93
  class VibeVoiceModel:
94
- @modal.enter()
95
  def load_models(self):
96
- """Run once when the container starts. Loads both models to GPU."""
97
- self.model_paths = {
98
- "VibeVoice-1.5B": "microsoft/VibeVoice-1.5B",
99
- "VibeVoice-7B": "vibevoice/VibeVoice-7B",
100
- }
101
  self.device = "cuda"
102
  self.inference_steps = 5
103
  self.cache_dir = "/cache"
@@ -107,40 +146,53 @@ class VibeVoiceModel:
107
  from modular.modeling_vibevoice_inference import VibeVoiceForConditionalGenerationInference
108
  from processor.vibevoice_processor import VibeVoiceProcessor
109
 
110
- self.boot_started = time.time()
111
- print(f"CONTAINER_START profile={SCALING_PROFILE} at={datetime.utcnow().isoformat()}Z "
112
- "— loading models to GPU...")
113
-
114
- # Set compiler flags for better performance
115
- if torch.cuda.is_available() and hasattr(torch, '_inductor'):
116
- if hasattr(torch._inductor, 'config'):
117
- torch._inductor.config.conv_1x1_as_mm = True
118
- torch._inductor.config.coordinate_descent_tuning = True
119
- torch._inductor.config.epilogue_fusion = False
120
- torch._inductor.config.coordinate_descent_check_all_directions = True
121
 
122
  self.models = {}
123
  self.processors = {}
124
  self.current_model_name = None
125
-
126
- # Load all models directly to GPU (A100-40GB holds both; ~17 GB baseline)
127
  for name, path in self.model_paths.items():
128
- print(f" - Loading {name} from {path}")
129
  proc = VibeVoiceProcessor.from_pretrained(path)
130
  mdl = VibeVoiceForConditionalGenerationInference.from_pretrained(
131
- path,
132
  torch_dtype=torch.bfloat16,
133
  attn_implementation="sdpa"
134
- ).to(self.device) # Load directly to GPU
135
  mdl.eval()
136
- print(f" {name} loaded to {self.device}")
137
  self.processors[name] = proc
138
  self.models[name] = mdl
139
-
140
  # Set default model
141
  self.current_model_name = "VibeVoice-1.5B"
142
-
143
  self.setup_voice_presets()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  self.ready_at = time.time() # for cold-start detection in timing reports
145
  self.jobs_served = 0
146
  print(f"CONTAINER_READY load_seconds={self.ready_at - self.boot_started:.0f}")
@@ -1367,3 +1419,17 @@ class VibeVoiceModel:
1367
  status="Generation failed.",
1368
  log_text=error_msg,
1369
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  # --- Scaling profiles (2026-09-06) ---------------------------------------
18
  # Chosen at deploy time: VIBEVOICE_PROFILE=launch modal deploy backend_modal/modal_runner.py
19
  # "launch": one container always hot + one pre-warmed buffer under load, so a
20
+ # public-post burst lands warm instead of paying the ~30 s snapshot restore.
21
  # "tail": scale to zero when idle (default). Same cap and idle window, so the
22
  # only thing that changes is the standing spend.
23
  # max_containers is the spending cap in both: a 5th concurrent request queues
 
31
  raise SystemExit(f"VIBEVOICE_PROFILE must be one of {sorted(SCALING_PROFILES)}, got {SCALING_PROFILE!r}")
32
  print(f"Deploying with scaling profile '{SCALING_PROFILE}': {SCALING_PROFILES[SCALING_PROFILE]}")
33
 
34
+ MODEL_PATHS = {
35
+ "VibeVoice-1.5B": "microsoft/VibeVoice-1.5B",
36
+ "VibeVoice-7B": "vibevoice/VibeVoice-7B",
37
+ }
38
+
39
+
40
+ # The processor loads its text tokenizer from the Qwen repo named in each
41
+ # checkpoint's preprocessor_config.json ("language_model_pretrained_name"), so
42
+ # those must ship in the image too (2026-09-12: the first bake missed them and
43
+ # the deploy crash-looped on "Can't load tokenizer for 'Qwen/Qwen2.5-1.5B'").
44
+ TOKENIZER_REPOS = ["Qwen/Qwen2.5-1.5B", "Qwen/Qwen2.5-7B"]
45
+
46
+
47
+ def _bake_weights():
48
+ """Image build step: pull both checkpoints and their tokenizers into HF_HOME
49
+ so nothing is fetched from the Hub at container start."""
50
+ from huggingface_hub import snapshot_download
51
+ for repo in MODEL_PATHS.values():
52
+ print(f"Baking {repo} into image ...")
53
+ snapshot_download(repo)
54
+ for repo in TOKENIZER_REPOS:
55
+ print(f"Baking tokenizer files from {repo} into image ...")
56
+ # json/txt only: tokenizer.json, vocab.json, merges.txt, configs — not the LLM weights
57
+ snapshot_download(repo, allow_patterns=["*.json", "*.txt"])
58
+
59
+
60
  # Define the Modal Stub
61
  image = (
62
  modal.Image.debian_slim(python_version="3.10")
 
84
  )
85
  .env({"PYTORCH_CUDA_ALLOC_CONF": "expandable_segments:True"}) # fights fragmentation across waves
86
  .env({"VIBEVOICE_PROFILE": SCALING_PROFILE}) # so container logs name the profile they run under
87
+ # Bake both checkpoints (~17 GB) plus tokenizers into the image at build
88
+ # time. Before this (2026-09-12) every cold container re-downloaded them from
89
+ # the Hub inside @modal.enter, which was most of the 110-180 s cold start.
90
+ # Not HF_HUB_OFFLINE on purpose: with everything cached, from_pretrained only
91
+ # does cheap etag checks, falls back to the cache if the Hub is unreachable,
92
+ # and any file the bake missed downloads instead of crash-looping the app.
93
+ .env({"HF_HOME": "/root/hf_home"})
94
+ .run_function(_bake_weights)
95
  .add_local_dir("backend_modal/modular", remote_path="/root/modular")
96
  .add_local_dir("backend_modal/processor", remote_path="/root/processor")
97
  .add_local_dir("backend_modal/voices", remote_path="/root/voices")
 
122
  # with cloned voices runs slower than the preset-voice record
123
  # pace (bigger reference prefill per chunk), so give 2h.
124
  volumes={"/cache": cache_volume},
125
+ # Cold-start work (2026-09-12): the process is checkpointed right after both
126
+ # models are loaded to CPU RAM (@modal.enter(snap=True)). A cold container
127
+ # restores that checkpoint instead of re-running from_pretrained, then only
128
+ # pays the CPU->GPU copy (@modal.enter(snap=False)). GPUs are not attached
129
+ # during the snapshot phase, so nothing there may touch CUDA.
130
+ enable_memory_snapshot=True,
131
+ memory=40 * 1024, # MiB; both checkpoints in bf16 (~17 GB) sit in RAM before the GPU copy
132
  **SCALING_PROFILES[SCALING_PROFILE],
133
  )
134
  class VibeVoiceModel:
135
+ @modal.enter(snap=True)
136
  def load_models(self):
137
+ """Snapshot phase: load both models to CPU. Captured once per deploy,
138
+ restored on every later cold start. No CUDA here (no GPU attached)."""
139
+ self.model_paths = MODEL_PATHS
 
 
140
  self.device = "cuda"
141
  self.inference_steps = 5
142
  self.cache_dir = "/cache"
 
146
  from modular.modeling_vibevoice_inference import VibeVoiceForConditionalGenerationInference
147
  from processor.vibevoice_processor import VibeVoiceProcessor
148
 
149
+ snap_started = time.time()
150
+ print(f"SNAPSHOT_START profile={SCALING_PROFILE} at={datetime.utcnow().isoformat()}Z "
151
+ "— loading models to CPU for the memory snapshot...")
 
 
 
 
 
 
 
 
152
 
153
  self.models = {}
154
  self.processors = {}
155
  self.current_model_name = None
156
+
 
157
  for name, path in self.model_paths.items():
158
+ print(f" - Loading {name} from {path} (baked into image)")
159
  proc = VibeVoiceProcessor.from_pretrained(path)
160
  mdl = VibeVoiceForConditionalGenerationInference.from_pretrained(
161
+ path,
162
  torch_dtype=torch.bfloat16,
163
  attn_implementation="sdpa"
164
+ )
165
  mdl.eval()
166
+ print(f" {name} loaded to CPU")
167
  self.processors[name] = proc
168
  self.models[name] = mdl
169
+
170
  # Set default model
171
  self.current_model_name = "VibeVoice-1.5B"
 
172
  self.setup_voice_presets()
173
+ print(f"SNAPSHOT_READY load_seconds={time.time() - snap_started:.0f}")
174
+
175
+ @modal.enter(snap=False)
176
+ def move_to_gpu(self):
177
+ """Restore phase: runs on every container start (after a snapshot restore,
178
+ or right after load_models the one time the snapshot is created)."""
179
+ self.boot_started = time.time()
180
+ print(f"CONTAINER_START profile={SCALING_PROFILE} at={datetime.utcnow().isoformat()}Z "
181
+ "— moving models to GPU...")
182
+
183
+ # Set compiler flags for better performance
184
+ if torch.cuda.is_available() and hasattr(torch, '_inductor'):
185
+ if hasattr(torch._inductor, 'config'):
186
+ torch._inductor.config.conv_1x1_as_mm = True
187
+ torch._inductor.config.coordinate_descent_tuning = True
188
+ torch._inductor.config.epilogue_fusion = False
189
+ torch._inductor.config.coordinate_descent_check_all_directions = True
190
+
191
+ # A100-40GB holds both; ~24 GB baseline (2.7B + 9.3B params in bf16, measured 24.1 GB on 2026-09-12)
192
+ for name, mdl in self.models.items():
193
+ self.models[name] = mdl.to(self.device)
194
+ print(f" {name} on {self.device}")
195
+
196
  self.ready_at = time.time() # for cold-start detection in timing reports
197
  self.jobs_served = 0
198
  print(f"CONTAINER_READY load_seconds={self.ready_at - self.boot_started:.0f}")
 
1419
  status="Generation failed.",
1420
  log_text=error_msg,
1421
  )
1422
+
1423
+
1424
+ @app.local_entrypoint()
1425
+ def boot_check(deployed: bool = False):
1426
+ """`modal run backend_modal/modal_runner.py`: boot one container and report the
1427
+ load path without generating anything. Ephemeral by default; pass
1428
+ `--deployed` to poke the deployed app instead (this is what creates, and then
1429
+ exercises, its memory snapshot). Watch `modal app logs vibevoice-generator`
1430
+ for CONTAINER_READY load_seconds=."""
1431
+ t0 = time.time()
1432
+ cls = modal.Cls.from_name("vibevoice-generator", "VibeVoiceModel") if deployed else VibeVoiceModel
1433
+ scripts, _ = cls().get_example_scripts.remote()
1434
+ print(f"boot_check: container answered in {time.time() - t0:.0f}s, "
1435
+ f"{len(scripts)} example scripts")
static/app.js CHANGED
@@ -1999,7 +1999,7 @@ function paintProgress() {
1999
  let warm;
2000
  if (expectedWarmup && elapsed > 10) {
2001
  // Ramp toward the last observed cold start — an estimate in motion beats
2002
- // a bare sweep that looks frozen for three minutes.
2003
  const width = `${(Math.min(0.95, elapsed / expectedWarmup) * 100).toFixed(1)}%`;
2004
  el.progressTrack.classList.remove("indeterminate");
2005
  el.genStageTrack.classList.remove("indeterminate");
@@ -2010,7 +2010,7 @@ function paintProgress() {
2010
  el.progressTrack.classList.add("indeterminate");
2011
  el.genStageTrack.classList.add("indeterminate");
2012
  warm = `GPU warming up · ${formatMinutes(elapsed) || "0s"}` +
2013
- (elapsed > 20 ? " — a cold start loads the whole model, usually a few minutes" : "");
2014
  }
2015
  el.progressMeta.textContent = warm;
2016
  el.genStagePct.textContent = "Warming up…";
 
1999
  let warm;
2000
  if (expectedWarmup && elapsed > 10) {
2001
  // Ramp toward the last observed cold start — an estimate in motion beats
2002
+ // a bare sweep that looks frozen for half a minute.
2003
  const width = `${(Math.min(0.95, elapsed / expectedWarmup) * 100).toFixed(1)}%`;
2004
  el.progressTrack.classList.remove("indeterminate");
2005
  el.genStageTrack.classList.remove("indeterminate");
 
2010
  el.progressTrack.classList.add("indeterminate");
2011
  el.genStageTrack.classList.add("indeterminate");
2012
  warm = `GPU warming up · ${formatMinutes(elapsed) || "0s"}` +
2013
+ (elapsed > 20 ? " — a cold start restores the model snapshot, usually about half a minute" : "");
2014
  }
2015
  el.progressMeta.textContent = warm;
2016
  el.genStagePct.textContent = "Warming up…";
static/index.html CHANGED
@@ -141,7 +141,7 @@
141
  <button id="generateBtn" class="btn btn-ink" type="button">Generate Audio</button>
142
  </div>
143
  <p class="cold-note" id="coldNote" hidden>
144
- First generation after idle can take ~3 minutes to spin up the GPU. After that it's fast.
145
  </p>
146
  </main>
147
 
 
141
  <button id="generateBtn" class="btn btn-ink" type="button">Generate Audio</button>
142
  </div>
143
  <p class="cold-note" id="coldNote" hidden>
144
+ First generation after idle takes about 30 seconds to wake the GPU. After that it's fast.
145
  </p>
146
  </main>
147