#!/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 - < 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}" < >(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."