Skip to content

Commit 226705d

Browse files
authored
add run audiocraft and videogen scripts (#51)
1 parent ba0c68a commit 226705d

2 files changed

Lines changed: 726 additions & 0 deletions

File tree

src/run_audiocraft.sh

Lines changed: 365 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,365 @@
1+
2+
3+
#!/usr/bin/env bash
4+
set -Eeuo pipefail
5+
6+
PROJECT_DIR="$HOME/audiocraft-local"
7+
VENV_DIR="$PROJECT_DIR/.venv"
8+
TOOLS_DIR="$PROJECT_DIR/.tools"
9+
UV_DIR="$TOOLS_DIR/uv-bin"
10+
UV_BIN="$UV_DIR/uv"
11+
OUTPUT_DIR="$PROJECT_DIR/outputs"
12+
13+
PROMPT="${1:-dark fantasy dungeon ambience with distant choir}"
14+
DURATION="${2:-10}"
15+
MODEL="${3:-facebook/musicgen-small}"
16+
KIND="${4:-auto}"
17+
18+
# KIND:
19+
# auto = detect from model name
20+
# music = force MusicGen
21+
# sfx = force AudioGen
22+
23+
if [[ "$MODEL" == "sfx" || "$MODEL" == "audiogen" ]]; then
24+
MODEL="facebook/audiogen-medium"
25+
KIND="sfx"
26+
fi
27+
28+
if [[ "$MODEL" == "music" || "$MODEL" == "musicgen" ]]; then
29+
MODEL="facebook/musicgen-medium"
30+
KIND="music"
31+
fi
32+
33+
mkdir -p "$PROJECT_DIR" "$TOOLS_DIR" "$OUTPUT_DIR"
34+
cd "$PROJECT_DIR"
35+
36+
echo "AudioCraft local directory: $PROJECT_DIR"
37+
echo "Prompt: $PROMPT"
38+
echo "Duration: $DURATION seconds"
39+
echo "Model: $MODEL"
40+
echo "Kind: $KIND"
41+
echo ""
42+
43+
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
44+
cat <<'EOF'
45+
Usage:
46+
./run_audiocraft.sh "prompt" duration model kind
47+
48+
Examples:
49+
50+
Music:
51+
./run_audiocraft.sh "ancient roman battle music, war drums and horns" 30 facebook/musicgen-medium music
52+
53+
Sound effects:
54+
./run_audiocraft.sh "arrows whistling overhead, impacts into wooden shields, dry foley recording" 5 facebook/audiogen-medium sfx
55+
56+
Shortcut for AudioGen:
57+
./run_audiocraft.sh "horse cavalry charge, galloping, dust, shouting soldiers" 5 sfx
58+
59+
Arguments:
60+
prompt Text prompt
61+
duration Seconds
62+
model Hugging Face model name, or shortcut: sfx/music
63+
kind auto/music/sfx
64+
65+
Recommended models:
66+
facebook/musicgen-small
67+
facebook/musicgen-medium
68+
facebook/musicgen-large
69+
facebook/audiogen-medium
70+
EOF
71+
exit 0
72+
fi
73+
74+
echo "Checking required system tools..."
75+
76+
if ! command -v ffmpeg >/dev/null 2>&1 || ! command -v curl >/dev/null 2>&1; then
77+
echo "Installing required system tools..."
78+
sudo apt update
79+
sudo apt install -y \
80+
curl \
81+
ffmpeg \
82+
pkg-config \
83+
build-essential \
84+
libavformat-dev \
85+
libavcodec-dev \
86+
libavdevice-dev \
87+
libavutil-dev \
88+
libavfilter-dev \
89+
libswscale-dev \
90+
libswresample-dev
91+
fi
92+
93+
if [ ! -x "$UV_BIN" ]; then
94+
echo "Installing uv locally inside project..."
95+
mkdir -p "$UV_DIR"
96+
curl -LsSf https://astral.sh/uv/install.sh | UV_INSTALL_DIR="$UV_DIR" sh
97+
fi
98+
99+
export UV_CACHE_DIR="$PROJECT_DIR/.uv-cache"
100+
export UV_PYTHON_INSTALL_DIR="$PROJECT_DIR/.uv-python"
101+
102+
echo "Installing private Python 3.10 with uv..."
103+
"$UV_BIN" python install 3.10
104+
105+
RECREATE_VENV=0
106+
107+
if [ ! -x "$VENV_DIR/bin/python" ]; then
108+
RECREATE_VENV=1
109+
else
110+
CURRENT_VERSION="$("$VENV_DIR/bin/python" -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')"
111+
112+
if [ "$CURRENT_VERSION" != "3.10" ]; then
113+
echo "Existing venv uses Python $CURRENT_VERSION. Recreating with Python 3.10..."
114+
RECREATE_VENV=1
115+
elif ! "$VENV_DIR/bin/python" -m pip --version >/dev/null 2>&1; then
116+
echo "Existing venv has no pip. Recreating with pip seeded..."
117+
RECREATE_VENV=1
118+
fi
119+
fi
120+
121+
if [ "$RECREATE_VENV" = "1" ]; then
122+
rm -rf "$VENV_DIR"
123+
echo "Creating private Python 3.10 venv with pip..."
124+
"$UV_BIN" venv --seed --python 3.10 "$VENV_DIR"
125+
fi
126+
127+
source "$VENV_DIR/bin/activate"
128+
129+
echo "Using Python:"
130+
python --version
131+
which python
132+
echo ""
133+
134+
echo "Installing package tools..."
135+
python -m pip install --upgrade "pip<25" setuptools wheel packaging
136+
137+
echo ""
138+
echo "Installing PyTorch CUDA 12.8 for RTX 50-series..."
139+
python -m pip install --upgrade \
140+
torch torchvision torchaudio \
141+
--index-url https://download.pytorch.org/whl/cu128
142+
143+
echo ""
144+
echo "Installing AudioCraft without old pinned torch dependencies..."
145+
python -m pip install --no-deps audiocraft==1.3.0
146+
147+
echo ""
148+
echo "Installing AudioCraft runtime dependencies manually..."
149+
python -m pip install \
150+
"numpy<2.0.0" \
151+
"av==11.0.0" \
152+
einops \
153+
"flashy>=0.0.1" \
154+
"hydra-core>=1.1" \
155+
hydra_colorlog \
156+
julius \
157+
num2words \
158+
sentencepiece \
159+
"spacy==3.7.6" \
160+
huggingface_hub \
161+
tqdm \
162+
"transformers>=4.31.0,<4.58" \
163+
demucs \
164+
librosa \
165+
soundfile \
166+
gradio \
167+
torchmetrics \
168+
encodec \
169+
protobuf \
170+
pesq \
171+
pystoi \
172+
torchdiffeq
173+
174+
echo ""
175+
echo "Forcing PyTorch CUDA 12.8 again in case another package touched it..."
176+
python -m pip install --upgrade \
177+
torch torchvision torchaudio \
178+
--index-url https://download.pytorch.org/whl/cu128
179+
180+
echo ""
181+
echo "Patching AudioCraft to run without xformers..."
182+
python - <<'PY'
183+
from pathlib import Path
184+
import sys
185+
186+
site_packages = Path(sys.prefix) / "lib"
187+
matches = list(site_packages.glob("python*/site-packages/audiocraft/modules/transformer.py"))
188+
189+
if not matches:
190+
raise SystemExit("Could not find audiocraft/modules/transformer.py")
191+
192+
path = matches[0]
193+
text = path.read_text()
194+
195+
if "class _AudioCraftXformersOpsFallback" not in text:
196+
text = text.replace(
197+
"from xformers import ops",
198+
"""try:
199+
from xformers import ops
200+
except Exception:
201+
class _AudioCraftXformersOpsFallback:
202+
@staticmethod
203+
def unbind(x, dim=0):
204+
return torch.unbind(x, dim=dim)
205+
206+
@staticmethod
207+
def memory_efficient_attention(*args, **kwargs):
208+
raise RuntimeError(
209+
"xformers is not installed. AudioCraft has been patched to use PyTorch attention instead."
210+
)
211+
212+
ops = _AudioCraftXformersOpsFallback()"""
213+
)
214+
215+
if "if _efficient_attention_backend == 'torch':\n if current_steps == 1:" not in text:
216+
text = text.replace(
217+
""" if self.memory_efficient:
218+
from xformers.ops import LowerTriangularMask
219+
""",
220+
""" if self.memory_efficient:
221+
if _efficient_attention_backend == 'torch':
222+
if current_steps == 1:
223+
return None
224+
return torch.empty(0, device=device, dtype=dtype)
225+
from xformers.ops import LowerTriangularMask
226+
"""
227+
)
228+
229+
if "def _verify_xformers_memory_efficient_compat():\n if _efficient_attention_backend == 'torch':" not in text:
230+
text = text.replace(
231+
"""def _verify_xformers_memory_efficient_compat():
232+
try:
233+
""",
234+
"""def _verify_xformers_memory_efficient_compat():
235+
if _efficient_attention_backend == 'torch':
236+
return
237+
try:
238+
"""
239+
)
240+
241+
if "self.checkpointing.startswith('xformers') and _efficient_attention_backend == 'torch'" not in text:
242+
text = text.replace(
243+
""" self.checkpointing = checkpointing
244+
assert checkpointing in ['none', 'torch', 'xformers_default', 'xformers_mm']
245+
""",
246+
""" self.checkpointing = checkpointing
247+
if self.checkpointing.startswith('xformers') and _efficient_attention_backend == 'torch':
248+
self.checkpointing = 'none'
249+
assert self.checkpointing in ['none', 'torch', 'xformers_default', 'xformers_mm']
250+
"""
251+
)
252+
253+
path.write_text(text)
254+
print(f"Patched: {path}")
255+
PY
256+
257+
echo ""
258+
echo "Checking GPU support..."
259+
python - <<'PY'
260+
import torch
261+
262+
print("Torch:", torch.__version__)
263+
print("Torch CUDA runtime:", torch.version.cuda)
264+
print("CUDA available:", torch.cuda.is_available())
265+
266+
if not torch.cuda.is_available():
267+
raise SystemExit("CUDA is not available. Check NVIDIA driver.")
268+
269+
print("GPU:", torch.cuda.get_device_name(0))
270+
print("Capability:", torch.cuda.get_device_capability(0))
271+
272+
x = torch.randn((1024, 1024), device="cuda")
273+
y = x @ x
274+
torch.cuda.synchronize()
275+
print("CUDA tensor test: OK")
276+
PY
277+
278+
echo ""
279+
echo "Generating audio..."
280+
281+
python - "$PROMPT" "$DURATION" "$MODEL" "$OUTPUT_DIR" "$KIND" <<'PY'
282+
import sys
283+
import re
284+
import time
285+
from pathlib import Path
286+
287+
import torch
288+
289+
from audiocraft.modules.transformer import set_efficient_attention_backend
290+
set_efficient_attention_backend("torch")
291+
292+
from audiocraft.models import MusicGen, AudioGen
293+
from audiocraft.data.audio import audio_write
294+
295+
prompt = sys.argv[1]
296+
duration = int(float(sys.argv[2]))
297+
model_name = sys.argv[3]
298+
output_dir = Path(sys.argv[4])
299+
kind = sys.argv[5].lower().strip()
300+
301+
output_dir.mkdir(parents=True, exist_ok=True)
302+
303+
safe_prompt = re.sub(r"[^a-zA-Z0-9_-]+", "_", prompt.lower()).strip("_")[:60]
304+
safe_model = re.sub(r"[^a-zA-Z0-9_-]+", "_", model_name.lower()).strip("_")[:40]
305+
306+
if not safe_prompt:
307+
safe_prompt = "audiocraft_output"
308+
309+
device = "cuda" if torch.cuda.is_available() else "cpu"
310+
311+
if kind == "auto":
312+
lower_model = model_name.lower()
313+
314+
if "audiogen" in lower_model:
315+
kind = "sfx"
316+
elif "musicgen" in lower_model:
317+
kind = "music"
318+
else:
319+
raise SystemExit(
320+
f"Could not auto-detect model type from: {model_name}\n"
321+
"Pass kind explicitly as the 4th argument: music or sfx"
322+
)
323+
324+
if kind in {"sfx", "sound", "soundfx", "audiogen"}:
325+
model_class = AudioGen
326+
resolved_kind = "sfx"
327+
elif kind in {"music", "musicgen"}:
328+
model_class = MusicGen
329+
resolved_kind = "music"
330+
else:
331+
raise SystemExit(
332+
f"Unknown kind: {kind}\n"
333+
"Use: auto, music, or sfx"
334+
)
335+
336+
print(f"Loading model on: {device}")
337+
print(f"Resolved kind: {resolved_kind}")
338+
print(f"Model class: {model_class.__name__}")
339+
print(f"Model name: {model_name}")
340+
341+
model = model_class.get_pretrained(model_name, device=device)
342+
model.set_generation_params(duration=duration)
343+
344+
print("Generating...")
345+
with torch.no_grad():
346+
wav = model.generate([prompt])
347+
348+
timestamp = time.strftime("%Y%m%d_%H%M%S")
349+
out_base = output_dir / f"{resolved_kind}_{safe_model}_{safe_prompt}_{timestamp}"
350+
351+
audio_write(
352+
str(out_base),
353+
wav[0].cpu(),
354+
model.sample_rate,
355+
strategy="loudness",
356+
loudness_compressor=True,
357+
)
358+
359+
print(f"Generated: {out_base}.wav")
360+
PY
361+
362+
echo ""
363+
echo "Done."
364+
echo "Output folder:"
365+
echo "$OUTPUT_DIR"

0 commit comments

Comments
 (0)