File size: 8,397 Bytes
5a90f0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/bin/bash
# =============================================================================
# RunPod: download scriptwriter dataset from HF → LoRA train in tmux → upload
# =============================================================================
# Designed for your 2x A40 pod (~$0.98/hr). Run once on the pod:
#
#   export HF_TOKEN=hf_...
#   bash runpod_train_tmux.sh
#
# Optional overrides:
#   HF_DATASET_REPO   (default: datamatters24/scriptwriter-corpus-ia)
#   HF_MODEL_REPO     (default: datamatters24/scriptwriter-lora-ia)
#   BASE_MODEL        (default: meta-llama/Llama-3.2-3B-Instruct)
#   TMUX_SESSION      (default: scriptwriter-train)
#   WORKDIR           (default: /workspace/scriptwriter-trainer)
#
# Prerequisites on the pod:
#   - This repo present at WORKDIR (scripts/ + config/ at minimum)
#   - HF account has accepted the Llama 3.2 license for BASE_MODEL
#   - nvidia-smi works
# =============================================================================

set -euo pipefail

TMUX_SESSION="${TMUX_SESSION:-scriptwriter-train}"
WORKDIR="${WORKDIR:-/workspace/scriptwriter-trainer}"
HF_DATASET_REPO="${HF_DATASET_REPO:-datamatters24/scriptwriter-corpus-ia}"
HF_MODEL_REPO="${HF_MODEL_REPO:-datamatters24/scriptwriter-lora-ia}"
BASE_MODEL="${BASE_MODEL:-meta-llama/Llama-3.2-3B-Instruct}"
DATA_DIR="${DATA_DIR:-/workspace/data/processed}"
OUT_DIR="${OUTPUT_DIR:-/workspace/models/lora}"
LOG_DIR="${LOG_DIR:-/workspace/logs}"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
TRAIN_LOG="${LOG_DIR}/train_${TIMESTAMP}.log"

# Resolve repo root: prefer script location, then WORKDIR, then /workspace
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [[ -f "${SCRIPT_DIR}/train_runpod.py" ]]; then
  ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
elif [[ -f "${WORKDIR}/scripts/train_runpod.py" ]]; then
  ROOT="${WORKDIR}"
elif [[ -f /workspace/scripts/train_runpod.py ]]; then
  ROOT="/workspace"
else
  echo "ERROR: cannot find scripts/train_runpod.py"
  echo "Copy the scriptwriter-trainer repo to ${WORKDIR} (need scripts/ and config/),"
  echo "then re-run:  bash ${WORKDIR}/scripts/runpod_train_tmux.sh"
  exit 1
fi

cd "${ROOT}"
mkdir -p "${DATA_DIR}" "${OUT_DIR}" "${LOG_DIR}"

echo "========== Scriptwriter RunPod trainer =========="
echo "ROOT=${ROOT}"
echo "HF_DATASET_REPO=${HF_DATASET_REPO}"
echo "HF_MODEL_REPO=${HF_MODEL_REPO}"
echo "BASE_MODEL=${BASE_MODEL}"
echo "DATA_DIR=${DATA_DIR}"
echo "OUT_DIR=${OUT_DIR}"
echo "LOG=${TRAIN_LOG}"
echo

if [[ -z "${HF_TOKEN:-}" ]]; then
  echo "ERROR: HF_TOKEN is not set."
  echo "  export HF_TOKEN=hf_xxxxxxxx"
  exit 1
fi

if ! command -v nvidia-smi >/dev/null 2>&1; then
  echo "WARNING: nvidia-smi not found — training will be very slow/CPU."
else
  nvidia-smi -L || true
fi

echo "=== Installing Python deps (if needed) ==="
python3 -m pip install -q --upgrade pip
if [[ -f "${ROOT}/requirements-runpod.txt" ]]; then
  python3 -m pip install -q -r "${ROOT}/requirements-runpod.txt"
else
  python3 -m pip install -q \
    torch transformers datasets peft trl accelerate bitsandbytes \
    huggingface_hub pyyaml tqdm sentencepiece protobuf
fi
python3 -m pip install -q "huggingface_hub>=0.24.0"

export HF_TOKEN
export HUGGING_FACE_HUB_TOKEN="${HF_TOKEN}"
export HF_HOME="${HF_HOME:-/workspace/.cache/huggingface}"
export CONFIG_PATH="${CONFIG_PATH:-${ROOT}/config/training.yaml}"
export HF_DATASET_REPO HF_MODEL_REPO BASE_MODEL
export OUTPUT_DIR="${OUT_DIR}"
# train_runpod.py looks under ROOT/data/processed — symlink pod data there
mkdir -p "${ROOT}/data"
if [[ ! -e "${ROOT}/data/processed" ]]; then
  ln -sfn "${DATA_DIR}" "${ROOT}/data/processed"
elif [[ ! -L "${ROOT}/data/processed" && "${ROOT}/data/processed" != "${DATA_DIR}" ]]; then
  # Prefer downloading into DATA_DIR and also ensure ROOT sees train.jsonl
  mkdir -p "${ROOT}/data/processed"
fi

echo
echo "=== Downloading dataset: ${HF_DATASET_REPO} ==="
python3 - <<PY
import os
from pathlib import Path
from huggingface_hub import snapshot_download, login

login(token=os.environ["HF_TOKEN"], add_to_git_credential=False)
dest = Path(os.environ.get("DATA_DIR", "/workspace/data/processed"))
dest.mkdir(parents=True, exist_ok=True)
snapshot_download(
    repo_id=os.environ["HF_DATASET_REPO"],
    repo_type="dataset",
    local_dir=str(dest),
    token=os.environ["HF_TOKEN"],
)
print(f"Downloaded to {dest}")
for name in sorted(dest.iterdir()):
    if name.is_file():
        print(f"  {name.name:30s} {name.stat().st_size:10d} bytes")
PY

echo
echo "=== Ensuring train.jsonl / val.jsonl for train_runpod.py ==="
python3 - <<PY
from pathlib import Path
import shutil
import os

candidates = [
    Path(os.environ.get("DATA_DIR", "/workspace/data/processed")),
    Path("${ROOT}/data/processed"),
]
# Deduplicate while preserving order
seen = set()
dirs = []
for d in candidates:
    key = str(d.resolve()) if d.exists() else str(d)
    if key in seen:
        continue
    seen.add(key)
    dirs.append(d)

def ensure_split(data_dir: Path) -> None:
    data_dir.mkdir(parents=True, exist_ok=True)
    train = data_dir / "train.jsonl"
    if not train.exists():
        for alt in ("train-ia.jsonl", "train-local.jsonl", "checkpoint-ia.jsonl"):
            src = data_dir / alt
            if src.exists() and src.stat().st_size > 0:
                shutil.copyfile(src, train)
                print(f"Created {train} from {alt}")
                break
    val = data_dir / "val.jsonl"
    if not val.exists():
        for alt in ("val-ia.jsonl", "val-local.jsonl"):
            src = data_dir / alt
            if src.exists() and src.stat().st_size > 0:
                shutil.copyfile(src, val)
                print(f"Created {val} from {alt}")
                break
    if not train.exists():
        raise SystemExit(f"No train.jsonl (or train-ia/train-local) in {data_dir}")
    n = sum(1 for line in train.open() if line.strip())
    print(f"{data_dir}: train.jsonl -> {n} examples")

for d in dirs:
    ensure_split(d)

# Keep ROOT/data/processed in sync if it is a real directory separate from DATA_DIR
root_proc = Path("${ROOT}/data/processed")
data_dir = Path(os.environ.get("DATA_DIR", "/workspace/data/processed"))
if root_proc.resolve() != data_dir.resolve():
    for name in ("train.jsonl", "val.jsonl"):
        src = data_dir / name
        if src.exists():
            shutil.copyfile(src, root_proc / name)
            print(f"Copied {name} -> {root_proc / name}")
PY

WORKER="${LOG_DIR}/_train_worker_${TIMESTAMP}.sh"
cat > "${WORKER}" <<EOF
#!/bin/bash
set -euo pipefail
cd "${ROOT}"
export HF_TOKEN='${HF_TOKEN}'
export HUGGING_FACE_HUB_TOKEN='${HF_TOKEN}'
export HF_HOME='${HF_HOME}'
export CONFIG_PATH='${CONFIG_PATH}'
export BASE_MODEL='${BASE_MODEL}'
export OUTPUT_DIR='${OUT_DIR}'
export HF_DATASET_REPO='${HF_DATASET_REPO}'
export HF_MODEL_REPO='${HF_MODEL_REPO}'

exec > >(tee -a '${TRAIN_LOG}') 2>&1

echo "========== TRAIN START \$(date -Is) =========="
nvidia-smi || true
echo "train lines: \$(wc -l < '${ROOT}/data/processed/train.jsonl')"
python3 '${ROOT}/scripts/train_runpod.py'

echo
echo "========== UPLOAD ADAPTER \$(date -Is) =========="
python3 '${ROOT}/scripts/sync_hf.py' upload-model \\
  --repo '${HF_MODEL_REPO}' \\
  --folder '${OUT_DIR}'

echo
echo "========== DONE \$(date -Is) =========="
echo "Adapter: https://huggingface.co/${HF_MODEL_REPO}"
echo "STOP THE POD in the RunPod console to stop billing."
echo
read -r -p "Press enter to close tmux pane..." _
EOF
chmod +x "${WORKER}"

if tmux has-session -t "${TMUX_SESSION}" 2>/dev/null; then
  echo "tmux session '${TMUX_SESSION}' already exists."
  echo "  Attach: tmux attach -t ${TMUX_SESSION}"
  echo "  Kill:   tmux kill-session -t ${TMUX_SESSION}"
  exit 1
fi

tmux new-session -d -s "${TMUX_SESSION}" -n train "bash '${WORKER}'"
tmux new-window -t "${TMUX_SESSION}" -n monitor
tmux send-keys -t "${TMUX_SESSION}:monitor" \
  "watch -n 15 'echo === GPUs ===; nvidia-smi --query-gpu=index,name,memory.used,utilization.gpu --format=csv; echo; echo === log ===; tail -20 ${TRAIN_LOG} 2>/dev/null'" Enter
tmux select-window -t "${TMUX_SESSION}:train"

echo
echo "Started training in tmux '${TMUX_SESSION}'"
echo "  Attach:  tmux attach -t ${TMUX_SESSION}"
echo "  Detach:  Ctrl-b then d"
echo "  Log:     ${TRAIN_LOG}"
echo "  Model →  https://huggingface.co/${HF_MODEL_REPO}"
echo
echo "When finished (or if something fails): STOP THE POD."