swsn21 commited on
Commit
e563677
·
verified ·
1 Parent(s): 3f420a4

Delete go.sh

Browse files
Files changed (1) hide show
  1. go.sh +0 -378
go.sh DELETED
@@ -1,378 +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
- # Two things this has to survive on the cu1281/ubuntu2404 image:
118
- # - Ubuntu 24.04 marks system python as externally-managed (PEP 668), so
119
- # `pip install uv` into it fails. Use uv's standalone installer instead.
120
- # - Its system python is 3.12; sd-scripts is not verified there. Pin 3.11,
121
- # which uv fetches as a standalone build if the image lacks it.
122
- PYTHON_VER="${PYTHON_VER:-3.11}"
123
- log "python env (target python $PYTHON_VER)"
124
-
125
- export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
126
- if ! command -v uv >/dev/null; then
127
- curl -LsSf https://astral.sh/uv/install.sh 2>/dev/null | sh >/dev/null 2>&1 || true
128
- export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$PATH"
129
- fi
130
-
131
- if [ ! -x "$VENV/bin/python" ]; then
132
- if command -v uv >/dev/null; then
133
- uv python install -q "$PYTHON_VER" 2>/dev/null || true
134
- uv venv -q --python "$PYTHON_VER" "$VENV" \
135
- || { warn "uv could not provide python $PYTHON_VER — using system python"; uv venv -q "$VENV"; }
136
- else
137
- warn "uv unavailable — falling back to system python $(python3 -V 2>&1 | awk '{print $2}')"
138
- python3 -m venv "$VENV"
139
- fi
140
- fi
141
-
142
- VENV_PY="$("$VENV/bin/python" -V 2>&1 | awk '{print $2}')"
143
- log " venv python $VENV_PY"
144
- case "$VENV_PY" in
145
- 3.1[0-2].*) : ;;
146
- *) warn " python $VENV_PY is outside the range sd-scripts is tested on (3.10-3.12)" ;;
147
- esac
148
-
149
- PIP=("$VENV/bin/python" -m pip install -q)
150
- if command -v uv >/dev/null; then PIP=(uv pip install -q --python "$VENV/bin/python"); fi
151
-
152
- "$VENV/bin/python" -m ensurepip -q 2>/dev/null || true
153
- "$VENV/bin/python" -m pip install -qU pip wheel setuptools 2>/dev/null || true
154
-
155
- CUR="$("$VENV/bin/python" -c 'import torch;print(torch.__version__)' 2>/dev/null || echo none)"
156
- case "$CUR" in
157
- ${TORCH_VER}*cu128*) log " torch $CUR ok" ;;
158
- *)
159
- log " installing torch ${TORCH_VER}+cu128 (found $CUR)"
160
- # torchaudio is not used by sd-scripts — skipped on purpose
161
- "${PIP[@]}" --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision \
162
- || { warn "uv failed, falling back to pip"
163
- PIP=("$VENV/bin/python" -m pip install -q)
164
- "${PIP[@]}" --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision; }
165
- ;;
166
- esac
167
-
168
- log " sd-scripts requirements"
169
- "${PIP[@]}" -r "$SD_DIR/requirements.txt" \
170
- || { warn "uv failed on requirements, falling back to pip"
171
- PIP=("$VENV/bin/python" -m pip install -q)
172
- "${PIP[@]}" -r "$SD_DIR/requirements.txt"; }
173
- "${PIP[@]}" bitsandbytes accelerate safetensors
174
-
175
- POST="$("$VENV/bin/python" -c 'import torch;print(torch.__version__)')"
176
- if [[ "$POST" != ${TORCH_VER}*cu128* ]]; then
177
- warn " requirements replaced torch with $POST — reinstalling pinned build"
178
- "$VENV/bin/python" -m pip install -q --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision
179
- fi
180
- "$VENV/bin/python" -c 'import torch;assert torch.cuda.is_available();print(f" torch {torch.__version__} | {torch.cuda.get_device_name(0)}")'
181
-
182
- # ----------------------------- 4. accelerate ---------------------------------
183
- mkdir -p /root/.cache/huggingface/accelerate
184
- cat > /root/.cache/huggingface/accelerate/default_config.yaml <<'YAML'
185
- compute_environment: LOCAL_MACHINE
186
- debug: false
187
- distributed_type: 'NO'
188
- downcast_bf16: 'no'
189
- enable_cpu_affinity: false
190
- gpu_ids: all
191
- machine_rank: 0
192
- main_training_function: main
193
- mixed_precision: bf16
194
- num_machines: 1
195
- num_processes: 1
196
- rdzv_backend: static
197
- same_network: true
198
- tpu_use_cluster: false
199
- tpu_use_sudo: false
200
- use_cpu: false
201
- YAML
202
-
203
- # ----------------------------- 5. join downloads -----------------------------
204
- log "waiting on downloads"
205
- wait "$DL_PID" || die "download job failed — see $DL_LOG
206
- 401/403 means a gated repo: accept the license, then
207
- export HF_TOKEN=hf_xxxx and re-run."
208
- tail -n 20 "$DL_LOG" | sed 's/^/ /'
209
-
210
- log "verifying safetensors headers"
211
- "$VENV/bin/python" - "$MODELS" <<'PY'
212
- import json, os, struct, sys
213
- d = sys.argv[1]; bad = []
214
- for fn in ("anima-base-v1.0.safetensors","qwen_3_06b_base.safetensors","qwen_image_vae.safetensors"):
215
- p = os.path.join(d, fn)
216
- try:
217
- with open(p,"rb") as f:
218
- n = struct.unpack("<Q", f.read(8))[0]
219
- assert 0 < n < 200_000_000, f"implausible header length {n}"
220
- h = json.loads(f.read(n))
221
- print(f" OK {fn:36s} {os.path.getsize(p)/1024**3:5.2f} GB {len(h)-('__metadata__' in h)} tensors")
222
- except Exception as e:
223
- bad.append(p); print(f" BAD {fn:36s} -> {type(e).__name__}: {e}")
224
- if bad:
225
- print("\n delete these and re-run (a gated download saves an HTML page as .safetensors):")
226
- for p in bad: print(" ", p)
227
- sys.exit(1)
228
- PY
229
-
230
- # ----------------------------- 6. dataset check ------------------------------
231
- IMG=$(find "$DS_DIR" -maxdepth 2 -type f \
232
- \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' -o -iname '*.bmp' \) | wc -l | tr -d ' ')
233
- CAP=$(find "$DS_DIR" -maxdepth 2 -type f -iname '*.txt' | wc -l | tr -d ' ')
234
- log "dataset: $IMG images / $CAP captions in $DS_DIR"
235
- [ "$IMG" -gt 0 ] || warn "no images yet — set HF_REPO_URL + DATASET_ZIP, or unzip into $DS_DIR yourself"
236
- [ "$IMG" -eq "$CAP" ] || warn "image/caption count mismatch — unpaired images train on an empty caption"
237
-
238
- # ----------------------------- 7. write trainer ------------------------------
239
- # CONFIG / provenance:
240
- # ENO (metadata stripped, recovered by tensor inspection)
241
- # -> self_attn + cross_attn + mlp, DiT only, bf16. This is the DEFAULT
242
- # target set of networks.lora_anima, so it needs no option at all.
243
- # 2n5 (SDXL LoCon, full ss_ metadata)
244
- # -> AdamW weight_decay 0.1, constant, warmup 0, max_grad_norm 1.0,
245
- # 1024 + bucket, all augmentation off, caption dropout 0
246
- # Your verified 51-image Anima run
247
- # -> dim 16 / alpha 32 / LR 1e-4 => effective LR (alpha/dim)*LR = 2.0e-4
248
- # 4,300 updates => movement 0.86 (2n5 measured: 0.84)
249
- # NOT recoverable from either file:
250
- # -> timestep_sampling / weighting_scheme / sigmoid_scale.
251
- # Values below are sd-scripts defaults, used for lack of evidence.
252
- # Keep them fixed across runs or cross-run comparison breaks.
253
- TRAINER="$CONFIG/train_anima_eno.sh"
254
- cat > "$TRAINER" <<'TRAINEOF'
255
- #!/usr/bin/env bash
256
- set -euo pipefail
257
- WORKSPACE="${WORKSPACE:-/workspace}"
258
- VENV="$WORKSPACE/venv-anima"; SD_DIR="$WORKSPACE/sd-scripts"; MODELS="$WORKSPACE/models"
259
- DATASET_NAME="${DATASET_NAME:-momostyle}"
260
- OUTPUT_NAME="${OUTPUT_NAME:-${DATASET_NAME}_eno}"
261
-
262
- NETWORK_DIM=16
263
- NETWORK_ALPHA=32 # scale = 2.0
264
- LR="${LR:-1e-4}" # effective 2.0e-4 (6e-5 -> 1.2e-4 | 2.5e-4 -> 5.0e-4)
265
- TARGET_UPDATES="${TARGET_UPDATES:-4300}"
266
- TRAIN_BATCH="${TRAIN_BATCH:-1}"
267
- GRAD_ACCUM="${GRAD_ACCUM:-1}"
268
- NUM_REPEATS="${NUM_REPEATS:-1}"
269
- EPOCHS="${EPOCHS:-auto}"
270
- SEED="${SEED:-42}"
271
- BLOCKS_TO_SWAP="${BLOCKS_TO_SWAP:-0}"
272
-
273
- DS_DIR="$WORKSPACE/dataset/$DATASET_NAME"
274
- TOML="$WORKSPACE/config/anima_ds_${DATASET_NAME}.toml"
275
- OUT_DIR="$WORKSPACE/output/$OUTPUT_NAME"
276
- die(){ printf '\n\033[1;31m[FAIL]\033[0m %s\n' "$*" >&2; exit 1; }
277
-
278
- [ -x "$VENV/bin/python" ] || die "venv missing — run go.sh first"
279
- [ -d "$DS_DIR" ] || die "dataset not found: $DS_DIR"
280
- mkdir -p "$OUT_DIR" "$WORKSPACE/logs"
281
-
282
- 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 ' ')
283
- [ "$IMG" -gt 0 ] || die "no images in $DS_DIR"
284
- EFF=$(( TRAIN_BATCH * GRAD_ACCUM ))
285
- VIEWS=$(( IMG * NUM_REPEATS ))
286
- UPE=$(( (VIEWS + EFF - 1) / EFF ))
287
- [ "$EPOCHS" = "auto" ] && EPOCHS=$(( (TARGET_UPDATES + UPE - 1) / UPE ))
288
- [ "$EPOCHS" -lt 1 ] && EPOCHS=1
289
- ACT=$(( EPOCHS * UPE ))
290
- SAVE=$(( EPOCHS / 18 )); [ "$SAVE" -lt 1 ] && SAVE=1
291
-
292
- "$VENV/bin/python" -c "
293
- lr=$LR; s=$NETWORK_ALPHA/$NETWORK_DIM; u=$ACT
294
- print(f'''
295
- scale {s:.2f}
296
- effective LR {s*lr:.3e}
297
- total movement {s*lr*u:.3f} (2n5 0.84 / verified run 0.86)''')"
298
- cat <<EOF
299
- images x repeats $IMG x $NUM_REPEATS = $VIEWS views/epoch
300
- effective batch $TRAIN_BATCH x $GRAD_ACCUM = $EFF
301
- epochs $EPOCHS -> $ACT updates (target $TARGET_UPDATES)
302
- save every $SAVE epoch(s) | output: $OUT_DIR
303
- EOF
304
- if [ "${YES:-0}" != "1" ]; then
305
- read -rp " Proceed? [y/N] " go || die "no tty — use YES=1"
306
- [[ "$go" =~ ^[Yy]$ ]] || exit 0
307
- fi
308
-
309
- cat > "$TOML" <<EOF
310
- [general]
311
- resolution = 1024
312
- enable_bucket = true
313
- min_bucket_reso = 256
314
- max_bucket_reso = 4096
315
- bucket_no_upscale = false
316
- # OFF on purpose: Anima conditions through Qwen3, which is token-order
317
- # sensitive. 2n5 says true, but that came from an SDXL/CLIP run.
318
- shuffle_caption = false
319
- keep_tokens = 0
320
- caption_dropout_rate = 0.0
321
- caption_tag_dropout_rate = 0.0
322
- flip_aug = false
323
- color_aug = false
324
-
325
- [[datasets]]
326
- [[datasets.subsets]]
327
- image_dir = "$DS_DIR"
328
- num_repeats = $NUM_REPEATS
329
- caption_extension = ".txt"
330
- EOF
331
-
332
- SWAP=(); [ "$BLOCKS_TO_SWAP" -gt 0 ] && SWAP=(--blocks_to_swap "$BLOCKS_TO_SWAP")
333
- cd "$SD_DIR"; source "$VENV/bin/activate"
334
- accelerate launch --num_cpu_threads_per_process 1 anima_train_network.py \
335
- --pretrained_model_name_or_path="$MODELS/anima-base-v1.0.safetensors" \
336
- --qwen3="$MODELS/qwen_3_06b_base.safetensors" \
337
- --vae="$MODELS/qwen_image_vae.safetensors" \
338
- --dataset_config="$TOML" \
339
- --output_dir="$OUT_DIR" --output_name="$OUTPUT_NAME" \
340
- --logging_dir="$WORKSPACE/logs" --log_prefix="$OUTPUT_NAME" \
341
- --save_model_as=safetensors --save_precision=bf16 --mixed_precision=bf16 --seed="$SEED" \
342
- --network_module=networks.lora_anima \
343
- --network_dim="$NETWORK_DIM" --network_alpha="$NETWORK_ALPHA" --network_train_unet_only \
344
- --learning_rate="$LR" \
345
- --optimizer_type=AdamW --optimizer_args "weight_decay=0.1" \
346
- --lr_scheduler=constant --lr_warmup_steps=0 --max_grad_norm=1.0 \
347
- --train_batch_size="$TRAIN_BATCH" --gradient_accumulation_steps="$GRAD_ACCUM" \
348
- --max_train_epochs="$EPOCHS" --save_every_n_epochs="$SAVE" \
349
- --timestep_sampling=sigmoid --sigmoid_scale=1.0 --weighting_scheme=uniform \
350
- --gradient_checkpointing \
351
- --cache_latents --cache_latents_to_disk \
352
- --cache_text_encoder_outputs --cache_text_encoder_outputs_to_disk \
353
- --qwen_image_vae_2d --persistent_data_loader_workers \
354
- "${SWAP[@]}" 2>&1 | tee "$WORKSPACE/logs/${OUTPUT_NAME}.log"
355
- TRAINEOF
356
- chmod +x "$TRAINER"
357
-
358
- # ----------------------------- 8. done ---------------------------------------
359
- cat <<EOF
360
-
361
- =============================================================================
362
- Ready. trainer: $TRAINER
363
-
364
- DATASET_NAME=$DATASET_NAME bash $TRAINER
365
-
366
- Background (survives closing the browser):
367
- YES=1 DATASET_NAME=$DATASET_NAME nohup bash $TRAINER > $LOGS/run.out 2>&1 &
368
- tail -f $LOGS/run.out
369
-
370
- Next session: re-run go.sh. Downloads, venv and latent cache are all on the
371
- Network Volume, so it finishes in about 30 seconds.
372
- =============================================================================
373
- EOF
374
-
375
- if [ "$TRAIN" = "1" ] && [ "$IMG" -gt 0 ]; then
376
- log "TRAIN=1 — launching"
377
- YES=1 DATASET_NAME="$DATASET_NAME" bash "$TRAINER"
378
- fi