File size: 18,974 Bytes
fe72b43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
#!/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 <url> <dest>
    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("<Q", f.read(8))[0]
            assert 0 < n < 200_000_000, f"implausible header length {n}"
            h = json.loads(f.read(n))
        print(f"  OK  {fn:36s} {os.path.getsize(p)/1024**3:5.2f} GB  {len(h)-('__metadata__' in h)} tensors")
    except Exception as e:
        bad.append(p); print(f"  BAD {fn:36s} -> {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 <<EOF
  images x repeats   $IMG x $NUM_REPEATS = $VIEWS views/epoch
  effective batch    $TRAIN_BATCH x $GRAD_ACCUM = $EFF
  epochs             $EPOCHS -> $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" <<EOF
[general]
resolution = 1024
enable_bucket = true
min_bucket_reso = 256
max_bucket_reso = 4096
bucket_no_upscale = false
# OFF on purpose: Anima conditions through Qwen3, which is token-order
# sensitive. 2n5's metadata says true, but that came from an SDXL/CLIP run.
shuffle_caption = false
keep_tokens = 0
caption_dropout_rate = 0.0
caption_tag_dropout_rate = 0.0
flip_aug = false
color_aug = false

[[datasets]]
  [[datasets.subsets]]
  image_dir = "$DS_DIR"
  num_repeats = $NUM_REPEATS
  caption_extension = ".txt"
EOF

# ----------------------------- sample prompts --------------------------------
SAMPLE_ARGS=()
if [ "$SAMPLE_EVERY" -gt 0 ]; then
  OPT="--w $SAMPLE_W --h $SAMPLE_H --s $SAMPLE_STEPS --l $SAMPLE_CFG --d $SAMPLE_SEED"
  cat > "$PROMPTS" <<EOF
1girl, solo, upper body, looking at viewer, simple background $OPT
1girl, solo, cowboy shot, standing, looking at viewer $OPT
1girl, solo, full body, standing, looking at viewer, simple background $OPT
EOF
  SAMPLE_ARGS=(
    --sample_prompts="$PROMPTS"
    --sample_every_n_epochs="$SAMPLE_EVERY"
    --sample_sampler=euler
    --sample_at_first          # fail fast if sampling is incompatible with cached TE
  )
fi

SWAP=(); [ "$BLOCKS_TO_SWAP" -gt 0 ] && SWAP=(--blocks_to_swap "$BLOCKS_TO_SWAP")
cd "$SD_DIR"; source "$VENV/bin/activate"
accelerate launch --num_cpu_threads_per_process 1 anima_train_network.py \
  --pretrained_model_name_or_path="$MODELS/anima-base-v1.0.safetensors" \
  --qwen3="$MODELS/qwen_3_06b_base.safetensors" \
  --vae="$MODELS/qwen_image_vae.safetensors" \
  --dataset_config="$TOML" \
  --output_dir="$OUT_DIR" --output_name="$OUTPUT_NAME" \
  --logging_dir="$WORKSPACE/logs" --log_prefix="$OUTPUT_NAME" \
  --save_model_as=safetensors --save_precision=bf16 --mixed_precision=bf16 --seed="$SEED" \
  --network_module=networks.lora_anima \
  --network_dim="$NETWORK_DIM" --network_alpha="$NETWORK_ALPHA" --network_train_unet_only \
  --learning_rate="$LR" \
  --optimizer_type=AdamW --optimizer_args "weight_decay=0.1" \
  --lr_scheduler=constant --lr_warmup_steps=0 --max_grad_norm=1.0 \
  --train_batch_size="$TRAIN_BATCH" --gradient_accumulation_steps="$GRAD_ACCUM" \
  --max_train_epochs="$EPOCHS" --save_every_n_epochs="$SAVE" \
  --timestep_sampling=sigmoid --sigmoid_scale=1.0 --weighting_scheme=uniform \
  --gradient_checkpointing \
  --cache_latents --cache_latents_to_disk \
  --cache_text_encoder_outputs --cache_text_encoder_outputs_to_disk \
  --qwen_image_vae_2d --persistent_data_loader_workers \
  "${SAMPLE_ARGS[@]}" "${SWAP[@]}" 2>&1 | tee "$WORKSPACE/logs/${OUTPUT_NAME}.log"
TRAINEOF
chmod +x "$TRAINER"

# ----------------------------- 8. done ---------------------------------------
cat <<EOF

=============================================================================
 Ready.   trainer: $TRAINER

   DATASET_NAME=$DATASET_NAME bash $TRAINER

 Background (survives closing the browser):
   YES=1 DATASET_NAME=$DATASET_NAME nohup bash $TRAINER > $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