#!/usr/bin/env bash # ============================================================================= # Anima LoRA — RunPod one-shot bootstrap (provision + dataset + train) # # First run: ~8-10 min (downloads run in parallel with the python env build) # Later runs: ~30 sec (everything cached on the Network Volume) # # Usage inside the pod: # export HF_REPO_URL=https://huggingface.co/swsn21/anma/resolve/main # export DATASET_ZIP=dataset_309.zip # wget -qO- $HF_REPO_URL/go.sh | bash # # Add TRAIN=1 to launch training as soon as setup finishes: # ... | TRAIN=1 bash # # Parameter provenance is documented in the CONFIG block further down. # ============================================================================= set -euo pipefail # ----------------------------- what you set ---------------------------------- HF_REPO_URL="${HF_REPO_URL:-}" # e.g. https://huggingface.co/swsn21/anma/resolve/main DATASET_ZIP="${DATASET_ZIP:-}" # e.g. dataset_309.zip DATASET_NAME="${DATASET_NAME:-momostyle}" HF_TOKEN="${HF_TOKEN:-}" # only if a repo is gated/private TRAIN="${TRAIN:-0}" # 1 = start training when ready # ----------------------------- fixed paths ----------------------------------- WORKSPACE="${WORKSPACE:-/workspace}" VENV="$WORKSPACE/venv-anima" SD_DIR="$WORKSPACE/sd-scripts" MODELS="$WORKSPACE/models" DS_DIR="$WORKSPACE/dataset/$DATASET_NAME" CONFIG="$WORKSPACE/config" LOGS="$WORKSPACE/logs" TORCH_VER="2.8.0" TORCH_INDEX="https://download.pytorch.org/whl/cu128" ANIMA_REPO="circlestone-labs/Anima" ANIMA_BASE="https://huggingface.co/${ANIMA_REPO}/resolve/main/split_files" log() { printf '\n\033[1;36m[%s]\033[0m %s\n' "$(date +%H:%M:%S)" "$*"; } warn() { printf '\033[1;33m[WARN]\033[0m %s\n' "$*"; } die() { printf '\n\033[1;31m[FAIL]\033[0m %s\n' "$*" >&2; exit 1; } # ----------------------------- 0. sanity ------------------------------------- log "Environment" command -v nvidia-smi >/dev/null || die "not a GPU pod" nvidia-smi --query-gpu=name,memory.total --format=csv,noheader mountpoint -q "$WORKSPACE" 2>/dev/null || warn "$WORKSPACE is not a Network Volume — everything here dies with the pod" mkdir -p "$MODELS" "$DS_DIR" "$CONFIG" "$LOGS" "$WORKSPACE/output" log "apt (aria2 + git, needed before anything can download)" export DEBIAN_FRONTEND=noninteractive if ! command -v aria2c >/dev/null || ! command -v git >/dev/null || ! command -v unzip >/dev/null; then apt-get update -qq apt-get install -y -qq --no-install-recommends git wget curl aria2 unzip python3-venv libgl1 libglib2.0-0 fi # ----------------------------- 1. downloads (BACKGROUND) --------------------- # These are the long pole. Fork them now so the python env builds at the same time. DL_LOG="$LOGS/download.log" : > "$DL_LOG" download_all() { local -a auth=() [ -n "$HF_TOKEN" ] && auth=(--header="Authorization: Bearer ${HF_TOKEN}") get() { # get local url="$1" dest="$2" name; name="$(basename "$dest")" if [ -s "$dest" ]; then echo "skip $name ($(du -h "$dest" | cut -f1))"; return 0; fi echo "get $name" aria2c -x16 -s16 -k1M --console-log-level=warn --summary-interval=0 \ --auto-file-renaming=false --allow-overwrite=true --retry-wait=3 -m5 \ "${auth[@]}" -d "$(dirname "$dest")" -o "$name" "$url" } get "$ANIMA_BASE/diffusion_models/anima-base-v1.0.safetensors" "$MODELS/anima-base-v1.0.safetensors" get "$ANIMA_BASE/text_encoders/qwen_3_06b_base.safetensors" "$MODELS/qwen_3_06b_base.safetensors" get "$ANIMA_BASE/vae/qwen_image_vae.safetensors" "$MODELS/qwen_image_vae.safetensors" # dataset straight from HF — no browser upload if [ -n "$HF_REPO_URL" ] && [ -n "$DATASET_ZIP" ]; then local have have=$(find "$DS_DIR" -maxdepth 1 -type f \ \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' \) | wc -l | tr -d ' ') if [ "$have" -gt 0 ]; then echo "skip dataset ($have images already in $DS_DIR)" else get "$HF_REPO_URL/$DATASET_ZIP" "$WORKSPACE/$DATASET_ZIP" echo "unzip dataset" unzip -q -o -j "$WORKSPACE/$DATASET_ZIP" -d "$DS_DIR" fi fi } download_all >>"$DL_LOG" 2>&1 & DL_PID=$! log "downloads running in background (pid $DL_PID) -> $DL_LOG" # ----------------------------- 2. sd-scripts --------------------------------- log "sd-scripts" PIN_FILE="$WORKSPACE/sd-scripts.commit" SD_COMMIT="${SD_COMMIT:-$( [ -f "$PIN_FILE" ] && cat "$PIN_FILE" || echo "" )}" [ -d "$SD_DIR/.git" ] || git clone -q https://github.com/kohya-ss/sd-scripts.git "$SD_DIR" git -C "$SD_DIR" fetch -q origin if [ -n "$SD_COMMIT" ] && [ "$SD_COMMIT" != "latest" ]; then git -C "$SD_DIR" checkout -q --force "$SD_COMMIT" log " pinned to ${SD_COMMIT:0:8}" else git -C "$SD_DIR" checkout -q --force origin/main git -C "$SD_DIR" rev-parse HEAD > "$PIN_FILE" log " origin/main, recorded $(cut -c1-8 "$PIN_FILE")" fi [ -f "$SD_DIR/anima_train_network.py" ] || die "anima_train_network.py missing from sd-scripts" # ----------------------------- 3. python env (uv) ---------------------------- # Two things this has to survive on the cu1281/ubuntu2404 image: # - Ubuntu 24.04 marks system python as externally-managed (PEP 668), so # `pip install uv` into it fails. Use uv's standalone installer instead. # - Its system python is 3.12; sd-scripts is not verified there. Pin 3.11, # which uv fetches as a standalone build if the image lacks it. PYTHON_VER="${PYTHON_VER:-3.11}" log "python env (target python $PYTHON_VER)" export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH" if ! command -v uv >/dev/null; then curl -LsSf https://astral.sh/uv/install.sh 2>/dev/null | sh >/dev/null 2>&1 || true export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH" fi if [ ! -x "$VENV/bin/python" ]; then if command -v uv >/dev/null; then uv python install -q "$PYTHON_VER" 2>/dev/null || true uv venv -q --python "$PYTHON_VER" "$VENV" \ || { warn "uv could not provide python $PYTHON_VER — using system python"; uv venv -q "$VENV"; } else warn "uv unavailable — falling back to system python $(python3 -V 2>&1 | awk '{print $2}')" python3 -m venv "$VENV" fi fi VENV_PY="$("$VENV/bin/python" -V 2>&1 | awk '{print $2}')" log " venv python $VENV_PY" case "$VENV_PY" in 3.1[0-2].*) : ;; *) warn " python $VENV_PY is outside the range sd-scripts is tested on (3.10-3.12)" ;; esac PIP=("$VENV/bin/python" -m pip install -q) if command -v uv >/dev/null; then PIP=(uv pip install -q --python "$VENV/bin/python"); fi # `uv venv` creates the environment WITHOUT pip, so the pip fallback paths below # would die with "No module named pip". Seed it explicitly. if ! "$VENV/bin/python" -c 'import pip' 2>/dev/null; then "${PIP[@]}" pip 2>/dev/null || "$VENV/bin/python" -m ensurepip 2>/dev/null || true fi "${PIP[@]}" -U pip wheel setuptools 2>/dev/null || true CUR="$("$VENV/bin/python" -c 'import torch;print(torch.__version__)' 2>/dev/null || echo none)" case "$CUR" in ${TORCH_VER}*cu128*) log " torch $CUR ok" ;; *) log " installing torch ${TORCH_VER}+cu128 (found $CUR)" # torchaudio is not used by sd-scripts — skipped on purpose "${PIP[@]}" --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision \ || { warn "uv failed, falling back to pip" PIP=("$VENV/bin/python" -m pip install -q) "${PIP[@]}" --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision; } ;; esac log " sd-scripts requirements" # The last line of sd-scripts' requirements.txt is `-e .` — an editable install # of the repo itself. It resolves against the CURRENT directory, so this must # run from inside $SD_DIR or it fails with "not a Python project". ( cd "$SD_DIR" && "${PIP[@]}" -r requirements.txt ) \ || { warn "uv failed on requirements, falling back to pip" PIP=("$VENV/bin/python" -m pip install -q) ( cd "$SD_DIR" && "${PIP[@]}" -r requirements.txt ); } "${PIP[@]}" bitsandbytes accelerate safetensors POST="$("$VENV/bin/python" -c 'import torch;print(torch.__version__)')" if [[ "$POST" != ${TORCH_VER}*cu128* ]]; then warn " requirements replaced torch with $POST — reinstalling pinned build" "$VENV/bin/python" -m pip install -q --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision fi "$VENV/bin/python" -c 'import torch;assert torch.cuda.is_available();print(f" torch {torch.__version__} | {torch.cuda.get_device_name(0)}")' # ----------------------------- 4. accelerate --------------------------------- mkdir -p /root/.cache/huggingface/accelerate cat > /root/.cache/huggingface/accelerate/default_config.yaml <<'YAML' compute_environment: LOCAL_MACHINE debug: false distributed_type: 'NO' downcast_bf16: 'no' enable_cpu_affinity: false gpu_ids: all machine_rank: 0 main_training_function: main mixed_precision: bf16 num_machines: 1 num_processes: 1 rdzv_backend: static same_network: true tpu_use_cluster: false tpu_use_sudo: false use_cpu: false YAML # ----------------------------- 5. join downloads ----------------------------- log "waiting on downloads" wait "$DL_PID" || die "download job failed — see $DL_LOG 401/403 means a gated repo: accept the license, then export HF_TOKEN=hf_xxxx and re-run." tail -n 20 "$DL_LOG" | sed 's/^/ /' log "verifying safetensors headers" "$VENV/bin/python" - "$MODELS" <<'PY' import json, os, struct, sys d = sys.argv[1]; bad = [] for fn in ("anima-base-v1.0.safetensors","qwen_3_06b_base.safetensors","qwen_image_vae.safetensors"): p = os.path.join(d, fn) try: with open(p,"rb") as f: n = struct.unpack(" {type(e).__name__}: {e}") if bad: print("\n delete these and re-run (a gated download saves an HTML page as .safetensors):") for p in bad: print(" ", p) sys.exit(1) PY # ----------------------------- 6. dataset check ------------------------------ IMG=$(find "$DS_DIR" -maxdepth 2 -type f \ \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' -o -iname '*.bmp' \) | wc -l | tr -d ' ') CAP=$(find "$DS_DIR" -maxdepth 2 -type f -iname '*.txt' | wc -l | tr -d ' ') log "dataset: $IMG images / $CAP captions in $DS_DIR" [ "$IMG" -gt 0 ] || warn "no images yet — set HF_REPO_URL + DATASET_ZIP, or unzip into $DS_DIR yourself" [ "$IMG" -eq "$CAP" ] || warn "image/caption count mismatch — unpaired images train on an empty caption" # ----------------------------- 7. write trainer ------------------------------ # CONFIG / provenance: # ENO (metadata stripped, recovered by tensor inspection) # -> self_attn + cross_attn + mlp, DiT only, bf16. This is the DEFAULT # target set of networks.lora_anima, so it needs no option at all. # 2n5 (SDXL LoCon, full ss_ metadata) # -> AdamW weight_decay 0.1, constant, warmup 0, max_grad_norm 1.0, # 1024 + bucket, all augmentation off, caption dropout 0 # Your verified 51-image Anima run # -> dim 16 / alpha 32 / LR 1e-4 => effective LR (alpha/dim)*LR = 2.0e-4 # 4,300 updates => movement 0.86 (2n5 measured: 0.84) # NOT recoverable from either file: # -> timestep_sampling / weighting_scheme / sigmoid_scale. # Values below are sd-scripts defaults, used for lack of evidence. # Keep them fixed across runs or cross-run comparison breaks. TRAINER="$CONFIG/train_anima_eno.sh" cat > "$TRAINER" <<'TRAINEOF' #!/usr/bin/env bash # ============================================================================= # Anima LoRA trainer — ENO/2n5 reference reproduction # # Provenance: # ENO (metadata stripped, recovered by tensor inspection) # -> self_attn + cross_attn + mlp, DiT only, bf16. This is the DEFAULT # target set of networks.lora_anima, so it needs no option at all. # 2n5 (SDXL LoCon, full ss_ metadata) # -> AdamW weight_decay 0.1, constant, warmup 0, max_grad_norm 1.0, # 1024 + bucket, all augmentation off, caption dropout 0 # Verified 51-image Anima run # -> dim 16 / alpha 32 / LR 1e-4 => effective LR (alpha/dim)*LR = 2.0e-4 # 4,300 updates => movement 0.86 (2n5 measured: 0.84) # NOT recoverable from either file: # -> timestep_sampling / weighting_scheme / sigmoid_scale. # Defaults below are used for lack of evidence. Keep them fixed # across runs or cross-run comparison breaks. # ============================================================================= set -euo pipefail WORKSPACE="${WORKSPACE:-/workspace}" VENV="$WORKSPACE/venv-anima"; SD_DIR="$WORKSPACE/sd-scripts"; MODELS="$WORKSPACE/models" DATASET_NAME="${DATASET_NAME:-momofuki}" # folder under /workspace/dataset/ OUTPUT_NAME="${OUTPUT_NAME:-momostyle}" # LoRA filename NETWORK_DIM=16 NETWORK_ALPHA=32 # scale = 2.0 LR="${LR:-1e-4}" # effective 2.0e-4 (6e-5 -> 1.2e-4 | 2.5e-4 -> 5.0e-4) TARGET_UPDATES="${TARGET_UPDATES:-4300}" TRAIN_BATCH="${TRAIN_BATCH:-1}" GRAD_ACCUM="${GRAD_ACCUM:-1}" NUM_REPEATS="${NUM_REPEATS:-1}" EPOCHS="${EPOCHS:-auto}" SEED="${SEED:-42}" BLOCKS_TO_SWAP="${BLOCKS_TO_SWAP:-0}" # --- sampling ---------------------------------------------------------------- SAMPLE_EVERY="${SAMPLE_EVERY:-1}" # epochs between sample sets; 0 = disable SAMPLE_W="${SAMPLE_W:-896}" SAMPLE_H="${SAMPLE_H:-1152}" SAMPLE_STEPS="${SAMPLE_STEPS:-30}" SAMPLE_CFG="${SAMPLE_CFG:-5}" SAMPLE_SEED="${SAMPLE_SEED:-42}" # fixed, so epochs are comparable DS_DIR="$WORKSPACE/dataset/$DATASET_NAME" TOML="$WORKSPACE/config/anima_ds_${DATASET_NAME}.toml" PROMPTS="$WORKSPACE/config/sample_prompts_${OUTPUT_NAME}.txt" OUT_DIR="$WORKSPACE/output/$OUTPUT_NAME" die(){ printf '\n\033[1;31m[FAIL]\033[0m %s\n' "$*" >&2; exit 1; } [ -x "$VENV/bin/python" ] || die "venv missing — run go.sh first" [ -d "$DS_DIR" ] || die "dataset not found: $DS_DIR" mkdir -p "$OUT_DIR" "$WORKSPACE/logs" "$WORKSPACE/config" IMG=$(find "$DS_DIR" -maxdepth 2 -type f \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' -o -iname '*.bmp' \) | wc -l | tr -d ' ') [ "$IMG" -gt 0 ] || die "no images in $DS_DIR" EFF=$(( TRAIN_BATCH * GRAD_ACCUM )) VIEWS=$(( IMG * NUM_REPEATS )) UPE=$(( (VIEWS + EFF - 1) / EFF )) [ "$EPOCHS" = "auto" ] && EPOCHS=$(( (TARGET_UPDATES + UPE - 1) / UPE )) [ "$EPOCHS" -lt 1 ] && EPOCHS=1 ACT=$(( EPOCHS * UPE )) SAVE=$(( EPOCHS / 18 )); [ "$SAVE" -lt 1 ] && SAVE=1 "$VENV/bin/python" -c " lr=$LR; s=$NETWORK_ALPHA/$NETWORK_DIM; u=$ACT print(f''' scale {s:.2f} effective LR {s*lr:.3e} total movement {s*lr*u:.3f} (2n5 0.84 / verified run 0.86)''')" cat < $ACT updates (target $TARGET_UPDATES) save every $SAVE epoch(s) sample every $SAMPLE_EVERY epoch(s) ${SAMPLE_W}x${SAMPLE_H}, 3 prompts, seed $SAMPLE_SEED output $OUT_DIR/$OUTPUT_NAME-*.safetensors EOF if [ "${YES:-0}" != "1" ]; then read -rp " Proceed? [y/N] " go || die "no tty — use YES=1" [[ "$go" =~ ^[Yy]$ ]] || exit 0 fi # ----------------------------- dataset toml ---------------------------------- cat > "$TOML" < "$PROMPTS" <&1 | tee "$WORKSPACE/logs/${OUTPUT_NAME}.log" TRAINEOF chmod +x "$TRAINER" # ----------------------------- 8. done --------------------------------------- cat < $LOGS/run.out 2>&1 & tail -f $LOGS/run.out Next session: re-run go.sh. Downloads, venv and latent cache are all on the Network Volume, so it finishes in about 30 seconds. ============================================================================= EOF if [ "$TRAIN" = "1" ] && [ "$IMG" -gt 0 ]; then log "TRAIN=1 — launching" YES=1 DATASET_NAME="$DATASET_NAME" bash "$TRAINER" fi