swsn21 commited on
Commit
00b7955
·
verified ·
1 Parent(s): f57a51f

Delete go.sh

Browse files
Files changed (1) hide show
  1. go.sh +0 -356
go.sh DELETED
@@ -1,356 +0,0 @@
1
- #!/usr/bin/env bash
2
- # =============================================================================
3
- # Anima LoRA — RunPod one-shot bootstrap (provision + dataset + train)
4
- #
5
- # First run: ~8-10 min (downloads run in parallel with the python env build)
6
- # Later runs: ~30 sec (everything cached on the Network Volume)
7
- #
8
- # Usage inside the pod:
9
- # export HF_REPO_URL=https://huggingface.co/swsn21/anma/resolve/main
10
- # export DATASET_ZIP=dataset_309.zip
11
- # wget -qO- $HF_REPO_URL/go.sh | bash
12
- #
13
- # Add TRAIN=1 to launch training as soon as setup finishes:
14
- # ... | TRAIN=1 bash
15
- #
16
- # Parameter provenance is documented in the CONFIG block further down.
17
- # =============================================================================
18
- set -euo pipefail
19
-
20
- # ----------------------------- what you set ----------------------------------
21
- HF_REPO_URL="${HF_REPO_URL:-}" # e.g. https://huggingface.co/swsn21/anma/resolve/main
22
- DATASET_ZIP="${DATASET_ZIP:-}" # e.g. dataset_309.zip
23
- DATASET_NAME="${DATASET_NAME:-momostyle}"
24
- HF_TOKEN="${HF_TOKEN:-}" # only if a repo is gated/private
25
- TRAIN="${TRAIN:-0}" # 1 = start training when ready
26
-
27
- # ----------------------------- fixed paths -----------------------------------
28
- WORKSPACE="${WORKSPACE:-/workspace}"
29
- VENV="$WORKSPACE/venv-anima"
30
- SD_DIR="$WORKSPACE/sd-scripts"
31
- MODELS="$WORKSPACE/models"
32
- DS_DIR="$WORKSPACE/dataset/$DATASET_NAME"
33
- CONFIG="$WORKSPACE/config"
34
- LOGS="$WORKSPACE/logs"
35
-
36
- TORCH_VER="2.8.0"
37
- TORCH_INDEX="https://download.pytorch.org/whl/cu128"
38
- ANIMA_REPO="circlestone-labs/Anima"
39
- ANIMA_BASE="https://huggingface.co/${ANIMA_REPO}/resolve/main/split_files"
40
-
41
- log() { printf '\n\033[1;36m[%s]\033[0m %s\n' "$(date +%H:%M:%S)" "$*"; }
42
- warn() { printf '\033[1;33m[WARN]\033[0m %s\n' "$*"; }
43
- die() { printf '\n\033[1;31m[FAIL]\033[0m %s\n' "$*" >&2; exit 1; }
44
-
45
- # ----------------------------- 0. sanity -------------------------------------
46
- log "Environment"
47
- command -v nvidia-smi >/dev/null || die "not a GPU pod"
48
- nvidia-smi --query-gpu=name,memory.total --format=csv,noheader
49
- mountpoint -q "$WORKSPACE" 2>/dev/null || warn "$WORKSPACE is not a Network Volume — everything here dies with the pod"
50
- mkdir -p "$MODELS" "$DS_DIR" "$CONFIG" "$LOGS" "$WORKSPACE/output"
51
-
52
- log "apt (aria2 + git, needed before anything can download)"
53
- export DEBIAN_FRONTEND=noninteractive
54
- if ! command -v aria2c >/dev/null || ! command -v git >/dev/null || ! command -v unzip >/dev/null; then
55
- apt-get update -qq
56
- apt-get install -y -qq --no-install-recommends git wget curl aria2 unzip python3-venv libgl1 libglib2.0-0
57
- fi
58
-
59
- # ----------------------------- 1. downloads (BACKGROUND) ---------------------
60
- # These are the long pole. Fork them now so the python env builds at the same time.
61
- DL_LOG="$LOGS/download.log"
62
- : > "$DL_LOG"
63
-
64
- download_all() {
65
- local -a auth=()
66
- [ -n "$HF_TOKEN" ] && auth=(--header="Authorization: Bearer ${HF_TOKEN}")
67
-
68
- get() { # get <url> <dest>
69
- local url="$1" dest="$2" name; name="$(basename "$dest")"
70
- if [ -s "$dest" ]; then echo "skip $name ($(du -h "$dest" | cut -f1))"; return 0; fi
71
- echo "get $name"
72
- aria2c -x16 -s16 -k1M --console-log-level=warn --summary-interval=0 \
73
- --auto-file-renaming=false --allow-overwrite=true --retry-wait=3 -m5 \
74
- "${auth[@]}" -d "$(dirname "$dest")" -o "$name" "$url"
75
- }
76
-
77
- get "$ANIMA_BASE/diffusion_models/anima-base-v1.0.safetensors" "$MODELS/anima-base-v1.0.safetensors"
78
- get "$ANIMA_BASE/text_encoders/qwen_3_06b_base.safetensors" "$MODELS/qwen_3_06b_base.safetensors"
79
- get "$ANIMA_BASE/vae/qwen_image_vae.safetensors" "$MODELS/qwen_image_vae.safetensors"
80
-
81
- # dataset straight from HF — no browser upload
82
- if [ -n "$HF_REPO_URL" ] && [ -n "$DATASET_ZIP" ]; then
83
- local have
84
- have=$(find "$DS_DIR" -maxdepth 1 -type f \
85
- \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' \) | wc -l | tr -d ' ')
86
- if [ "$have" -gt 0 ]; then
87
- echo "skip dataset ($have images already in $DS_DIR)"
88
- else
89
- get "$HF_REPO_URL/$DATASET_ZIP" "$WORKSPACE/$DATASET_ZIP"
90
- echo "unzip dataset"
91
- unzip -q -o -j "$WORKSPACE/$DATASET_ZIP" -d "$DS_DIR"
92
- fi
93
- fi
94
- }
95
-
96
- download_all >>"$DL_LOG" 2>&1 &
97
- DL_PID=$!
98
- log "downloads running in background (pid $DL_PID) -> $DL_LOG"
99
-
100
- # ----------------------------- 2. sd-scripts ---------------------------------
101
- log "sd-scripts"
102
- PIN_FILE="$WORKSPACE/sd-scripts.commit"
103
- SD_COMMIT="${SD_COMMIT:-$( [ -f "$PIN_FILE" ] && cat "$PIN_FILE" || echo "" )}"
104
- [ -d "$SD_DIR/.git" ] || git clone -q https://github.com/kohya-ss/sd-scripts.git "$SD_DIR"
105
- git -C "$SD_DIR" fetch -q origin
106
- if [ -n "$SD_COMMIT" ] && [ "$SD_COMMIT" != "latest" ]; then
107
- git -C "$SD_DIR" checkout -q --force "$SD_COMMIT"
108
- log " pinned to ${SD_COMMIT:0:8}"
109
- else
110
- git -C "$SD_DIR" checkout -q --force origin/main
111
- git -C "$SD_DIR" rev-parse HEAD > "$PIN_FILE"
112
- log " origin/main, recorded $(cut -c1-8 "$PIN_FILE")"
113
- fi
114
- [ -f "$SD_DIR/anima_train_network.py" ] || die "anima_train_network.py missing from sd-scripts"
115
-
116
- # ----------------------------- 3. python env (uv) ----------------------------
117
- # uv resolves and installs several times faster than pip; pip is the fallback.
118
- log "python env"
119
- if [ ! -x "$VENV/bin/python" ]; then
120
- python3 -m pip install -q uv 2>/dev/null || true
121
- if command -v uv >/dev/null || [ -x "$(python3 -m site --user-base 2>/dev/null)/bin/uv" ]; then
122
- export PATH="$(python3 -m site --user-base)/bin:$PATH"
123
- fi
124
- if command -v uv >/dev/null; then uv venv -q "$VENV"; else python3 -m venv "$VENV"; fi
125
- fi
126
- export PATH="$(python3 -m site --user-base 2>/dev/null)/bin:$PATH"
127
-
128
- PIP=("$VENV/bin/python" -m pip install -q)
129
- if command -v uv >/dev/null; then PIP=(uv pip install -q --python "$VENV/bin/python"); fi
130
-
131
- "$VENV/bin/python" -m pip install -qU pip wheel setuptools 2>/dev/null || true
132
-
133
- CUR="$("$VENV/bin/python" -c 'import torch;print(torch.__version__)' 2>/dev/null || echo none)"
134
- case "$CUR" in
135
- ${TORCH_VER}*cu128*) log " torch $CUR ok" ;;
136
- *)
137
- log " installing torch ${TORCH_VER}+cu128 (found $CUR)"
138
- # torchaudio is not used by sd-scripts — skipped on purpose
139
- "${PIP[@]}" --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision \
140
- || { warn "uv failed, falling back to pip"
141
- PIP=("$VENV/bin/python" -m pip install -q)
142
- "${PIP[@]}" --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision; }
143
- ;;
144
- esac
145
-
146
- log " sd-scripts requirements"
147
- "${PIP[@]}" -r "$SD_DIR/requirements.txt" \
148
- || { warn "uv failed on requirements, falling back to pip"
149
- PIP=("$VENV/bin/python" -m pip install -q)
150
- "${PIP[@]}" -r "$SD_DIR/requirements.txt"; }
151
- "${PIP[@]}" bitsandbytes accelerate safetensors
152
-
153
- POST="$("$VENV/bin/python" -c 'import torch;print(torch.__version__)')"
154
- if [[ "$POST" != ${TORCH_VER}*cu128* ]]; then
155
- warn " requirements replaced torch with $POST — reinstalling pinned build"
156
- "$VENV/bin/python" -m pip install -q --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision
157
- fi
158
- "$VENV/bin/python" -c 'import torch;assert torch.cuda.is_available();print(f" torch {torch.__version__} | {torch.cuda.get_device_name(0)}")'
159
-
160
- # ----------------------------- 4. accelerate ---------------------------------
161
- mkdir -p /root/.cache/huggingface/accelerate
162
- cat > /root/.cache/huggingface/accelerate/default_config.yaml <<'YAML'
163
- compute_environment: LOCAL_MACHINE
164
- debug: false
165
- distributed_type: 'NO'
166
- downcast_bf16: 'no'
167
- enable_cpu_affinity: false
168
- gpu_ids: all
169
- machine_rank: 0
170
- main_training_function: main
171
- mixed_precision: bf16
172
- num_machines: 1
173
- num_processes: 1
174
- rdzv_backend: static
175
- same_network: true
176
- tpu_use_cluster: false
177
- tpu_use_sudo: false
178
- use_cpu: false
179
- YAML
180
-
181
- # ----------------------------- 5. join downloads -----------------------------
182
- log "waiting on downloads"
183
- wait "$DL_PID" || die "download job failed — see $DL_LOG
184
- 401/403 means a gated repo: accept the license, then
185
- export HF_TOKEN=hf_xxxx and re-run."
186
- tail -n 20 "$DL_LOG" | sed 's/^/ /'
187
-
188
- log "verifying safetensors headers"
189
- "$VENV/bin/python" - "$MODELS" <<'PY'
190
- import json, os, struct, sys
191
- d = sys.argv[1]; bad = []
192
- for fn in ("anima-base-v1.0.safetensors","qwen_3_06b_base.safetensors","qwen_image_vae.safetensors"):
193
- p = os.path.join(d, fn)
194
- try:
195
- with open(p,"rb") as f:
196
- n = struct.unpack("<Q", f.read(8))[0]
197
- assert 0 < n < 200_000_000, f"implausible header length {n}"
198
- h = json.loads(f.read(n))
199
- print(f" OK {fn:36s} {os.path.getsize(p)/1024**3:5.2f} GB {len(h)-('__metadata__' in h)} tensors")
200
- except Exception as e:
201
- bad.append(p); print(f" BAD {fn:36s} -> {type(e).__name__}: {e}")
202
- if bad:
203
- print("\n delete these and re-run (a gated download saves an HTML page as .safetensors):")
204
- for p in bad: print(" ", p)
205
- sys.exit(1)
206
- PY
207
-
208
- # ----------------------------- 6. dataset check ------------------------------
209
- IMG=$(find "$DS_DIR" -maxdepth 2 -type f \
210
- \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' -o -iname '*.bmp' \) | wc -l | tr -d ' ')
211
- CAP=$(find "$DS_DIR" -maxdepth 2 -type f -iname '*.txt' | wc -l | tr -d ' ')
212
- log "dataset: $IMG images / $CAP captions in $DS_DIR"
213
- [ "$IMG" -gt 0 ] || warn "no images yet — set HF_REPO_URL + DATASET_ZIP, or unzip into $DS_DIR yourself"
214
- [ "$IMG" -eq "$CAP" ] || warn "image/caption count mismatch — unpaired images train on an empty caption"
215
-
216
- # ----------------------------- 7. write trainer ------------------------------
217
- # CONFIG / provenance:
218
- # ENO (metadata stripped, recovered by tensor inspection)
219
- # -> self_attn + cross_attn + mlp, DiT only, bf16. This is the DEFAULT
220
- # target set of networks.lora_anima, so it needs no option at all.
221
- # 2n5 (SDXL LoCon, full ss_ metadata)
222
- # -> AdamW weight_decay 0.1, constant, warmup 0, max_grad_norm 1.0,
223
- # 1024 + bucket, all augmentation off, caption dropout 0
224
- # Your verified 51-image Anima run
225
- # -> dim 16 / alpha 32 / LR 1e-4 => effective LR (alpha/dim)*LR = 2.0e-4
226
- # 4,300 updates => movement 0.86 (2n5 measured: 0.84)
227
- # NOT recoverable from either file:
228
- # -> timestep_sampling / weighting_scheme / sigmoid_scale.
229
- # Values below are sd-scripts defaults, used for lack of evidence.
230
- # Keep them fixed across runs or cross-run comparison breaks.
231
- TRAINER="$CONFIG/train_anima_eno.sh"
232
- cat > "$TRAINER" <<'TRAINEOF'
233
- #!/usr/bin/env bash
234
- set -euo pipefail
235
- WORKSPACE="${WORKSPACE:-/workspace}"
236
- VENV="$WORKSPACE/venv-anima"; SD_DIR="$WORKSPACE/sd-scripts"; MODELS="$WORKSPACE/models"
237
- DATASET_NAME="${DATASET_NAME:-momostyle}"
238
- OUTPUT_NAME="${OUTPUT_NAME:-${DATASET_NAME}_eno}"
239
-
240
- NETWORK_DIM=16
241
- NETWORK_ALPHA=32 # scale = 2.0
242
- LR="${LR:-1e-4}" # effective 2.0e-4 (6e-5 -> 1.2e-4 | 2.5e-4 -> 5.0e-4)
243
- TARGET_UPDATES="${TARGET_UPDATES:-4300}"
244
- TRAIN_BATCH="${TRAIN_BATCH:-1}"
245
- GRAD_ACCUM="${GRAD_ACCUM:-1}"
246
- NUM_REPEATS="${NUM_REPEATS:-1}"
247
- EPOCHS="${EPOCHS:-auto}"
248
- SEED="${SEED:-42}"
249
- BLOCKS_TO_SWAP="${BLOCKS_TO_SWAP:-0}"
250
-
251
- DS_DIR="$WORKSPACE/dataset/$DATASET_NAME"
252
- TOML="$WORKSPACE/config/anima_ds_${DATASET_NAME}.toml"
253
- OUT_DIR="$WORKSPACE/output/$OUTPUT_NAME"
254
- die(){ printf '\n\033[1;31m[FAIL]\033[0m %s\n' "$*" >&2; exit 1; }
255
-
256
- [ -x "$VENV/bin/python" ] || die "venv missing — run go.sh first"
257
- [ -d "$DS_DIR" ] || die "dataset not found: $DS_DIR"
258
- mkdir -p "$OUT_DIR" "$WORKSPACE/logs"
259
-
260
- 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 ' ')
261
- [ "$IMG" -gt 0 ] || die "no images in $DS_DIR"
262
- EFF=$(( TRAIN_BATCH * GRAD_ACCUM ))
263
- VIEWS=$(( IMG * NUM_REPEATS ))
264
- UPE=$(( (VIEWS + EFF - 1) / EFF ))
265
- [ "$EPOCHS" = "auto" ] && EPOCHS=$(( (TARGET_UPDATES + UPE - 1) / UPE ))
266
- [ "$EPOCHS" -lt 1 ] && EPOCHS=1
267
- ACT=$(( EPOCHS * UPE ))
268
- SAVE=$(( EPOCHS / 18 )); [ "$SAVE" -lt 1 ] && SAVE=1
269
-
270
- "$VENV/bin/python" -c "
271
- lr=$LR; s=$NETWORK_ALPHA/$NETWORK_DIM; u=$ACT
272
- print(f'''
273
- scale {s:.2f}
274
- effective LR {s*lr:.3e}
275
- total movement {s*lr*u:.3f} (2n5 0.84 / verified run 0.86)''')"
276
- cat <<EOF
277
- images x repeats $IMG x $NUM_REPEATS = $VIEWS views/epoch
278
- effective batch $TRAIN_BATCH x $GRAD_ACCUM = $EFF
279
- epochs $EPOCHS -> $ACT updates (target $TARGET_UPDATES)
280
- save every $SAVE epoch(s) | output: $OUT_DIR
281
- EOF
282
- if [ "${YES:-0}" != "1" ]; then
283
- read -rp " Proceed? [y/N] " go || die "no tty — use YES=1"
284
- [[ "$go" =~ ^[Yy]$ ]] || exit 0
285
- fi
286
-
287
- cat > "$TOML" <<EOF
288
- [general]
289
- resolution = 1024
290
- enable_bucket = true
291
- min_bucket_reso = 256
292
- max_bucket_reso = 4096
293
- bucket_no_upscale = false
294
- # OFF on purpose: Anima conditions through Qwen3, which is token-order
295
- # sensitive. 2n5 says true, but that came from an SDXL/CLIP run.
296
- shuffle_caption = false
297
- keep_tokens = 0
298
- caption_dropout_rate = 0.0
299
- caption_tag_dropout_rate = 0.0
300
- flip_aug = false
301
- color_aug = false
302
-
303
- [[datasets]]
304
- [[datasets.subsets]]
305
- image_dir = "$DS_DIR"
306
- num_repeats = $NUM_REPEATS
307
- caption_extension = ".txt"
308
- EOF
309
-
310
- SWAP=(); [ "$BLOCKS_TO_SWAP" -gt 0 ] && SWAP=(--blocks_to_swap "$BLOCKS_TO_SWAP")
311
- cd "$SD_DIR"; source "$VENV/bin/activate"
312
- accelerate launch --num_cpu_threads_per_process 1 anima_train_network.py \
313
- --pretrained_model_name_or_path="$MODELS/anima-base-v1.0.safetensors" \
314
- --qwen3="$MODELS/qwen_3_06b_base.safetensors" \
315
- --vae="$MODELS/qwen_image_vae.safetensors" \
316
- --dataset_config="$TOML" \
317
- --output_dir="$OUT_DIR" --output_name="$OUTPUT_NAME" \
318
- --logging_dir="$WORKSPACE/logs" --log_prefix="$OUTPUT_NAME" \
319
- --save_model_as=safetensors --save_precision=bf16 --mixed_precision=bf16 --seed="$SEED" \
320
- --network_module=networks.lora_anima \
321
- --network_dim="$NETWORK_DIM" --network_alpha="$NETWORK_ALPHA" --network_train_unet_only \
322
- --learning_rate="$LR" \
323
- --optimizer_type=AdamW --optimizer_args "weight_decay=0.1" \
324
- --lr_scheduler=constant --lr_warmup_steps=0 --max_grad_norm=1.0 \
325
- --train_batch_size="$TRAIN_BATCH" --gradient_accumulation_steps="$GRAD_ACCUM" \
326
- --max_train_epochs="$EPOCHS" --save_every_n_epochs="$SAVE" \
327
- --timestep_sampling=sigmoid --sigmoid_scale=1.0 --weighting_scheme=uniform \
328
- --gradient_checkpointing \
329
- --cache_latents --cache_latents_to_disk \
330
- --cache_text_encoder_outputs --cache_text_encoder_outputs_to_disk \
331
- --qwen_image_vae_2d --persistent_data_loader_workers \
332
- "${SWAP[@]}" 2>&1 | tee "$WORKSPACE/logs/${OUTPUT_NAME}.log"
333
- TRAINEOF
334
- chmod +x "$TRAINER"
335
-
336
- # ----------------------------- 8. done ---------------------------------------
337
- cat <<EOF
338
-
339
- =============================================================================
340
- Ready. trainer: $TRAINER
341
-
342
- DATASET_NAME=$DATASET_NAME bash $TRAINER
343
-
344
- Background (survives closing the browser):
345
- YES=1 DATASET_NAME=$DATASET_NAME nohup bash $TRAINER > $LOGS/run.out 2>&1 &
346
- tail -f $LOGS/run.out
347
-
348
- Next session: re-run go.sh. Downloads, venv and latent cache are all on the
349
- Network Volume, so it finishes in about 30 seconds.
350
- =============================================================================
351
- EOF
352
-
353
- if [ "$TRAIN" = "1" ] && [ "$IMG" -gt 0 ]; then
354
- log "TRAIN=1 — launching"
355
- YES=1 DATASET_NAME="$DATASET_NAME" bash "$TRAINER"
356
- fi