Datasets:
File size: 3,453 Bytes
1e6582e 10d623c 1e6582e 10d623c 1e6582e 10d623c 1e6582e 10d623c 1e6582e | 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 | """Fine-tune RF-DETR-Medium on the UI-controls dataset, on Modal.
Upload once:
uvx modal volume create ui-detector-oner
uvx modal volume put ui-detector-oner data/coco /coco
uvx modal volume put ui-detector-oner ~/dev/personal/intent-lens/models/ui-detr-1.pth /init/ui-detr-1.pth
Run:
uvx modal run --detach modal_train.py --run coco1280 --init coco --resolution 1280 --epochs 60
uvx modal run --detach modal_train.py --run uidetr1280 --init uidetr --resolution 1280 --epochs 60
Fetch:
uvx modal volume get ui-detector-oner /runs/<run>/checkpoint_best_total.pth weights/<run>.pth
"""
import modal
app = modal.App("ui-detector-train-oner")
vol = modal.Volume.from_name("ui-detector-oner", create_if_missing=True)
image = (modal.Image.debian_slim(python_version="3.11")
.apt_install("libgl1", "libglib2.0-0")
.pip_install("rfdetr[train]==1.12.1"))
@app.function(image=image, gpu=["H100", "A100-80GB"], volumes={"/vol": vol}, timeout=5 * 3600, cpu=8, memory=32768)
def train(run: str, init: str, resolution: int, epochs: int, batch: int, accum: int, lr: float, dataset: str = "coco"):
import json, os, shutil, threading, time
import torch
from rfdetr import RFDETRMedium
print("GPU:", torch.cuda.get_device_name(0), "| run", run, "| init", init, "| res", resolution, "| epochs", epochs, "| batch", batch, "x", accum)
# work on local disk (fast), copy results back to the volume as we go
data = "/tmp/coco"
shutil.copytree(f"/vol/{dataset}", data)
for s in ("train", "valid", "test"):
c = json.load(open(f"{data}/{s}/_annotations.coco.json"))
print(s, "images", len(c["images"]), "labels", len(c["annotations"]))
out, keep = f"/tmp/out/{run}", f"/vol/runs/{run}"
os.makedirs(out, exist_ok=True)
os.makedirs(keep, exist_ok=True)
stop = threading.Event()
def sync():
for f in os.listdir(out):
if f.endswith((".pth", ".json", ".txt", ".csv")) and "checkpoint_" in f or f.endswith((".json", ".txt", ".csv")):
try:
shutil.copy2(os.path.join(out, f), os.path.join(keep, f))
except Exception as e:
print("sync error", f, e)
vol.commit()
def loop():
while not stop.wait(600):
sync()
threading.Thread(target=loop, daemon=True).start()
kwargs = dict(resolution=resolution)
if init == "uidetr":
kwargs["pretrain_weights"] = "/vol/init/ui-detr-1.pth"
model = RFDETRMedium(**kwargs)
t0 = time.time()
model.train(dataset_dir=data, epochs=epochs, batch_size=batch, grad_accum_steps=accum, lr=lr, output_dir=out,
aug_config={}, # no flips: undo/redo and back/forward are mirror images of each other
early_stopping=True, early_stopping_patience=20, checkpoint_interval=5, num_workers=8,
tensorboard=False, run_test=True, class_names=[k["name"] for k in json.load(open(f"{data}/train/_annotations.coco.json"))["categories"]])
stop.set()
print("training seconds:", round(time.time() - t0))
print("files:", sorted(os.listdir(out)))
sync()
return sorted(os.listdir(keep))
@app.local_entrypoint()
def main(run: str, init: str = "coco", resolution: int = 1280, epochs: int = 60, batch: int = 4, accum: int = 4, lr: float = 5e-5, dataset: str = "coco"):
print(train.remote(run, init, resolution, epochs, batch, accum, lr, dataset))
|