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

Upload go.sh

Browse files
Files changed (1) hide show
  1. go.sh +433 -0
go.sh ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # `uv venv` creates the environment WITHOUT pip, so the pip fallback paths below
153
+ # would die with "No module named pip". Seed it explicitly.
154
+ if ! "$VENV/bin/python" -c 'import pip' 2>/dev/null; then
155
+ "${PIP[@]}" pip 2>/dev/null || "$VENV/bin/python" -m ensurepip 2>/dev/null || true
156
+ fi
157
+ "${PIP[@]}" -U pip wheel setuptools 2>/dev/null || true
158
+
159
+ CUR="$("$VENV/bin/python" -c 'import torch;print(torch.__version__)' 2>/dev/null || echo none)"
160
+ case "$CUR" in
161
+ ${TORCH_VER}*cu128*) log " torch $CUR ok" ;;
162
+ *)
163
+ log " installing torch ${TORCH_VER}+cu128 (found $CUR)"
164
+ # torchaudio is not used by sd-scripts — skipped on purpose
165
+ "${PIP[@]}" --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision \
166
+ || { warn "uv failed, falling back to pip"
167
+ PIP=("$VENV/bin/python" -m pip install -q)
168
+ "${PIP[@]}" --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision; }
169
+ ;;
170
+ esac
171
+
172
+ log " sd-scripts requirements"
173
+ # The last line of sd-scripts' requirements.txt is `-e .` — an editable install
174
+ # of the repo itself. It resolves against the CURRENT directory, so this must
175
+ # run from inside $SD_DIR or it fails with "not a Python project".
176
+ ( cd "$SD_DIR" && "${PIP[@]}" -r requirements.txt ) \
177
+ || { warn "uv failed on requirements, falling back to pip"
178
+ PIP=("$VENV/bin/python" -m pip install -q)
179
+ ( cd "$SD_DIR" && "${PIP[@]}" -r requirements.txt ); }
180
+ "${PIP[@]}" bitsandbytes accelerate safetensors
181
+
182
+ POST="$("$VENV/bin/python" -c 'import torch;print(torch.__version__)')"
183
+ if [[ "$POST" != ${TORCH_VER}*cu128* ]]; then
184
+ warn " requirements replaced torch with $POST — reinstalling pinned build"
185
+ "$VENV/bin/python" -m pip install -q --index-url "$TORCH_INDEX" "torch==${TORCH_VER}" torchvision
186
+ fi
187
+ "$VENV/bin/python" -c 'import torch;assert torch.cuda.is_available();print(f" torch {torch.__version__} | {torch.cuda.get_device_name(0)}")'
188
+
189
+ # ----------------------------- 4. accelerate ---------------------------------
190
+ mkdir -p /root/.cache/huggingface/accelerate
191
+ cat > /root/.cache/huggingface/accelerate/default_config.yaml <<'YAML'
192
+ compute_environment: LOCAL_MACHINE
193
+ debug: false
194
+ distributed_type: 'NO'
195
+ downcast_bf16: 'no'
196
+ enable_cpu_affinity: false
197
+ gpu_ids: all
198
+ machine_rank: 0
199
+ main_training_function: main
200
+ mixed_precision: bf16
201
+ num_machines: 1
202
+ num_processes: 1
203
+ rdzv_backend: static
204
+ same_network: true
205
+ tpu_use_cluster: false
206
+ tpu_use_sudo: false
207
+ use_cpu: false
208
+ YAML
209
+
210
+ # ----------------------------- 5. join downloads -----------------------------
211
+ log "waiting on downloads"
212
+ wait "$DL_PID" || die "download job failed — see $DL_LOG
213
+ 401/403 means a gated repo: accept the license, then
214
+ export HF_TOKEN=hf_xxxx and re-run."
215
+ tail -n 20 "$DL_LOG" | sed 's/^/ /'
216
+
217
+ log "verifying safetensors headers"
218
+ "$VENV/bin/python" - "$MODELS" <<'PY'
219
+ import json, os, struct, sys
220
+ d = sys.argv[1]; bad = []
221
+ for fn in ("anima-base-v1.0.safetensors","qwen_3_06b_base.safetensors","qwen_image_vae.safetensors"):
222
+ p = os.path.join(d, fn)
223
+ try:
224
+ with open(p,"rb") as f:
225
+ n = struct.unpack("<Q", f.read(8))[0]
226
+ assert 0 < n < 200_000_000, f"implausible header length {n}"
227
+ h = json.loads(f.read(n))
228
+ print(f" OK {fn:36s} {os.path.getsize(p)/1024**3:5.2f} GB {len(h)-('__metadata__' in h)} tensors")
229
+ except Exception as e:
230
+ bad.append(p); print(f" BAD {fn:36s} -> {type(e).__name__}: {e}")
231
+ if bad:
232
+ print("\n delete these and re-run (a gated download saves an HTML page as .safetensors):")
233
+ for p in bad: print(" ", p)
234
+ sys.exit(1)
235
+ PY
236
+
237
+ # ----------------------------- 6. dataset check ------------------------------
238
+ IMG=$(find "$DS_DIR" -maxdepth 2 -type f \
239
+ \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' -o -iname '*.bmp' \) | wc -l | tr -d ' ')
240
+ CAP=$(find "$DS_DIR" -maxdepth 2 -type f -iname '*.txt' | wc -l | tr -d ' ')
241
+ log "dataset: $IMG images / $CAP captions in $DS_DIR"
242
+ [ "$IMG" -gt 0 ] || warn "no images yet — set HF_REPO_URL + DATASET_ZIP, or unzip into $DS_DIR yourself"
243
+ [ "$IMG" -eq "$CAP" ] || warn "image/caption count mismatch — unpaired images train on an empty caption"
244
+
245
+ # ----------------------------- 7. write trainer ------------------------------
246
+ # CONFIG / provenance:
247
+ # ENO (metadata stripped, recovered by tensor inspection)
248
+ # -> self_attn + cross_attn + mlp, DiT only, bf16. This is the DEFAULT
249
+ # target set of networks.lora_anima, so it needs no option at all.
250
+ # 2n5 (SDXL LoCon, full ss_ metadata)
251
+ # -> AdamW weight_decay 0.1, constant, warmup 0, max_grad_norm 1.0,
252
+ # 1024 + bucket, all augmentation off, caption dropout 0
253
+ # Your verified 51-image Anima run
254
+ # -> dim 16 / alpha 32 / LR 1e-4 => effective LR (alpha/dim)*LR = 2.0e-4
255
+ # 4,300 updates => movement 0.86 (2n5 measured: 0.84)
256
+ # NOT recoverable from either file:
257
+ # -> timestep_sampling / weighting_scheme / sigmoid_scale.
258
+ # Values below are sd-scripts defaults, used for lack of evidence.
259
+ # Keep them fixed across runs or cross-run comparison breaks.
260
+ TRAINER="$CONFIG/train_anima_eno.sh"
261
+ cat > "$TRAINER" <<'TRAINEOF'
262
+ #!/usr/bin/env bash
263
+ # =============================================================================
264
+ # Anima LoRA trainer — ENO/2n5 reference reproduction
265
+ #
266
+ # Provenance:
267
+ # ENO (metadata stripped, recovered by tensor inspection)
268
+ # -> self_attn + cross_attn + mlp, DiT only, bf16. This is the DEFAULT
269
+ # target set of networks.lora_anima, so it needs no option at all.
270
+ # 2n5 (SDXL LoCon, full ss_ metadata)
271
+ # -> AdamW weight_decay 0.1, constant, warmup 0, max_grad_norm 1.0,
272
+ # 1024 + bucket, all augmentation off, caption dropout 0
273
+ # Verified 51-image Anima run
274
+ # -> dim 16 / alpha 32 / LR 1e-4 => effective LR (alpha/dim)*LR = 2.0e-4
275
+ # 4,300 updates => movement 0.86 (2n5 measured: 0.84)
276
+ # NOT recoverable from either file:
277
+ # -> timestep_sampling / weighting_scheme / sigmoid_scale.
278
+ # Defaults below are used for lack of evidence. Keep them fixed
279
+ # across runs or cross-run comparison breaks.
280
+ # =============================================================================
281
+ set -euo pipefail
282
+ WORKSPACE="${WORKSPACE:-/workspace}"
283
+ VENV="$WORKSPACE/venv-anima"; SD_DIR="$WORKSPACE/sd-scripts"; MODELS="$WORKSPACE/models"
284
+
285
+ DATASET_NAME="${DATASET_NAME:-momofuki}" # folder under /workspace/dataset/
286
+ OUTPUT_NAME="${OUTPUT_NAME:-momostyle}" # LoRA filename
287
+
288
+ NETWORK_DIM=16
289
+ NETWORK_ALPHA=32 # scale = 2.0
290
+ LR="${LR:-1e-4}" # effective 2.0e-4 (6e-5 -> 1.2e-4 | 2.5e-4 -> 5.0e-4)
291
+ TARGET_UPDATES="${TARGET_UPDATES:-4300}"
292
+ TRAIN_BATCH="${TRAIN_BATCH:-1}"
293
+ GRAD_ACCUM="${GRAD_ACCUM:-1}"
294
+ NUM_REPEATS="${NUM_REPEATS:-1}"
295
+ EPOCHS="${EPOCHS:-auto}"
296
+ SEED="${SEED:-42}"
297
+ BLOCKS_TO_SWAP="${BLOCKS_TO_SWAP:-0}"
298
+
299
+ # --- sampling ----------------------------------------------------------------
300
+ SAMPLE_EVERY="${SAMPLE_EVERY:-1}" # epochs between sample sets; 0 = disable
301
+ SAMPLE_W="${SAMPLE_W:-896}"
302
+ SAMPLE_H="${SAMPLE_H:-1152}"
303
+ SAMPLE_STEPS="${SAMPLE_STEPS:-30}"
304
+ SAMPLE_CFG="${SAMPLE_CFG:-5}"
305
+ SAMPLE_SEED="${SAMPLE_SEED:-42}" # fixed, so epochs are comparable
306
+
307
+ DS_DIR="$WORKSPACE/dataset/$DATASET_NAME"
308
+ TOML="$WORKSPACE/config/anima_ds_${DATASET_NAME}.toml"
309
+ PROMPTS="$WORKSPACE/config/sample_prompts_${OUTPUT_NAME}.txt"
310
+ OUT_DIR="$WORKSPACE/output/$OUTPUT_NAME"
311
+ die(){ printf '\n\033[1;31m[FAIL]\033[0m %s\n' "$*" >&2; exit 1; }
312
+
313
+ [ -x "$VENV/bin/python" ] || die "venv missing — run go.sh first"
314
+ [ -d "$DS_DIR" ] || die "dataset not found: $DS_DIR"
315
+ mkdir -p "$OUT_DIR" "$WORKSPACE/logs" "$WORKSPACE/config"
316
+
317
+ 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 ' ')
318
+ [ "$IMG" -gt 0 ] || die "no images in $DS_DIR"
319
+ EFF=$(( TRAIN_BATCH * GRAD_ACCUM ))
320
+ VIEWS=$(( IMG * NUM_REPEATS ))
321
+ UPE=$(( (VIEWS + EFF - 1) / EFF ))
322
+ [ "$EPOCHS" = "auto" ] && EPOCHS=$(( (TARGET_UPDATES + UPE - 1) / UPE ))
323
+ [ "$EPOCHS" -lt 1 ] && EPOCHS=1
324
+ ACT=$(( EPOCHS * UPE ))
325
+ SAVE=$(( EPOCHS / 18 )); [ "$SAVE" -lt 1 ] && SAVE=1
326
+
327
+ "$VENV/bin/python" -c "
328
+ lr=$LR; s=$NETWORK_ALPHA/$NETWORK_DIM; u=$ACT
329
+ print(f'''
330
+ scale {s:.2f}
331
+ effective LR {s*lr:.3e}
332
+ total movement {s*lr*u:.3f} (2n5 0.84 / verified run 0.86)''')"
333
+ cat <<EOF
334
+ images x repeats $IMG x $NUM_REPEATS = $VIEWS views/epoch
335
+ effective batch $TRAIN_BATCH x $GRAD_ACCUM = $EFF
336
+ epochs $EPOCHS -> $ACT updates (target $TARGET_UPDATES)
337
+ save every $SAVE epoch(s)
338
+ sample every $SAMPLE_EVERY epoch(s) ${SAMPLE_W}x${SAMPLE_H}, 3 prompts, seed $SAMPLE_SEED
339
+ output $OUT_DIR/$OUTPUT_NAME-*.safetensors
340
+ EOF
341
+ if [ "${YES:-0}" != "1" ]; then
342
+ read -rp " Proceed? [y/N] " go || die "no tty — use YES=1"
343
+ [[ "$go" =~ ^[Yy]$ ]] || exit 0
344
+ fi
345
+
346
+ # ----------------------------- dataset toml ----------------------------------
347
+ cat > "$TOML" <<EOF
348
+ [general]
349
+ resolution = 1024
350
+ enable_bucket = true
351
+ min_bucket_reso = 256
352
+ max_bucket_reso = 4096
353
+ bucket_no_upscale = false
354
+ # OFF on purpose: Anima conditions through Qwen3, which is token-order
355
+ # sensitive. 2n5's metadata says true, but that came from an SDXL/CLIP run.
356
+ shuffle_caption = false
357
+ keep_tokens = 0
358
+ caption_dropout_rate = 0.0
359
+ caption_tag_dropout_rate = 0.0
360
+ flip_aug = false
361
+ color_aug = false
362
+
363
+ [[datasets]]
364
+ [[datasets.subsets]]
365
+ image_dir = "$DS_DIR"
366
+ num_repeats = $NUM_REPEATS
367
+ caption_extension = ".txt"
368
+ EOF
369
+
370
+ # ----------------------------- sample prompts --------------------------------
371
+ SAMPLE_ARGS=()
372
+ if [ "$SAMPLE_EVERY" -gt 0 ]; then
373
+ OPT="--w $SAMPLE_W --h $SAMPLE_H --s $SAMPLE_STEPS --l $SAMPLE_CFG --d $SAMPLE_SEED"
374
+ cat > "$PROMPTS" <<EOF
375
+ 1girl, solo, upper body, looking at viewer, simple background $OPT
376
+ 1girl, solo, cowboy shot, standing, looking at viewer $OPT
377
+ 1girl, solo, full body, standing, looking at viewer, simple background $OPT
378
+ EOF
379
+ SAMPLE_ARGS=(
380
+ --sample_prompts="$PROMPTS"
381
+ --sample_every_n_epochs="$SAMPLE_EVERY"
382
+ --sample_sampler=euler
383
+ --sample_at_first # fail fast if sampling is incompatible with cached TE
384
+ )
385
+ fi
386
+
387
+ SWAP=(); [ "$BLOCKS_TO_SWAP" -gt 0 ] && SWAP=(--blocks_to_swap "$BLOCKS_TO_SWAP")
388
+ cd "$SD_DIR"; source "$VENV/bin/activate"
389
+ accelerate launch --num_cpu_threads_per_process 1 anima_train_network.py \
390
+ --pretrained_model_name_or_path="$MODELS/anima-base-v1.0.safetensors" \
391
+ --qwen3="$MODELS/qwen_3_06b_base.safetensors" \
392
+ --vae="$MODELS/qwen_image_vae.safetensors" \
393
+ --dataset_config="$TOML" \
394
+ --output_dir="$OUT_DIR" --output_name="$OUTPUT_NAME" \
395
+ --logging_dir="$WORKSPACE/logs" --log_prefix="$OUTPUT_NAME" \
396
+ --save_model_as=safetensors --save_precision=bf16 --mixed_precision=bf16 --seed="$SEED" \
397
+ --network_module=networks.lora_anima \
398
+ --network_dim="$NETWORK_DIM" --network_alpha="$NETWORK_ALPHA" --network_train_unet_only \
399
+ --learning_rate="$LR" \
400
+ --optimizer_type=AdamW --optimizer_args "weight_decay=0.1" \
401
+ --lr_scheduler=constant --lr_warmup_steps=0 --max_grad_norm=1.0 \
402
+ --train_batch_size="$TRAIN_BATCH" --gradient_accumulation_steps="$GRAD_ACCUM" \
403
+ --max_train_epochs="$EPOCHS" --save_every_n_epochs="$SAVE" \
404
+ --timestep_sampling=sigmoid --sigmoid_scale=1.0 --weighting_scheme=uniform \
405
+ --gradient_checkpointing \
406
+ --cache_latents --cache_latents_to_disk \
407
+ --cache_text_encoder_outputs --cache_text_encoder_outputs_to_disk \
408
+ --qwen_image_vae_2d --persistent_data_loader_workers \
409
+ "${SAMPLE_ARGS[@]}" "${SWAP[@]}" 2>&1 | tee "$WORKSPACE/logs/${OUTPUT_NAME}.log"
410
+ TRAINEOF
411
+ chmod +x "$TRAINER"
412
+
413
+ # ----------------------------- 8. done ---------------------------------------
414
+ cat <<EOF
415
+
416
+ =============================================================================
417
+ Ready. trainer: $TRAINER
418
+
419
+ DATASET_NAME=$DATASET_NAME bash $TRAINER
420
+
421
+ Background (survives closing the browser):
422
+ YES=1 DATASET_NAME=$DATASET_NAME nohup bash $TRAINER > $LOGS/run.out 2>&1 &
423
+ tail -f $LOGS/run.out
424
+
425
+ Next session: re-run go.sh. Downloads, venv and latent cache are all on the
426
+ Network Volume, so it finishes in about 30 seconds.
427
+ =============================================================================
428
+ EOF
429
+
430
+ if [ "$TRAIN" = "1" ] && [ "$IMG" -gt 0 ]; then
431
+ log "TRAIN=1 — launching"
432
+ YES=1 DATASET_NAME="$DATASET_NAME" bash "$TRAINER"
433
+ fi