sparsewm-stage3-eval / notes /RENDER_DATASET.md
GGOSinon's picture
Upload folder using huggingface_hub
7ecdca3 verified
|
Raw History Blame Contribute Delete
13 kB

Rendering the CLEVR-10 dataset on another machine

Instructions for a Claude agent to reproduce the clevr_gen10_1M dataset (Blender-rendered CLEVR, 10 objects, 320Γ—240) that the SparseWM project trains on. Self-contained: you do not need access to the machine that produced the original.


0. What you are producing

The pipeline renders CLEVR scenes with Blender and post-processes each batch into three aligned .npy files per chunk of 5,000 scenes. The full set is 200 chunks Γ— 5,000 = 1,000,000 scenes.

Output directory (call it $OUT) ends up with, for each chunk KKKK = 0000…0199:

file shape / dtype meaning
states_chunk{KKKK}.npy (5000, 10, 7) float32 per-object GT state (see below)
images320_chunk{KKKK}.npy (5000, 240, 320, 3) uint8 native Blender render
images192_chunk{KKKK}.npy (5000, 128, 192, 3) uint8 LANCZOS-resized (what training streams)

State layout (per object, matches SparseWM/CLAUDE.md): [presence, shape, color, size, material, posX, posY]

  • presence: 1.0 if the slot holds an object, else 0.0. Up to 10 objects; extra slots are zero.
  • shape: 0=cube, 1=sphere, 2=cylinder
  • color: 0..7 = gray, red, blue, green, brown, purple, cyan, yellow
  • size: 0=large, 1=small
  • material: 0=rubber, 1=metal
  • posX, posY: Blender 3D x/y mapped [-3,3] β†’ [0.2,0.8] (clamped). Not pixel coords.

You can render fewer chunks if you don't need the full 1M β€” the format is identical; just render a contiguous range of chunk indices. The downstream loader (SparseWM/scripts/async_chunk_loader.py) globs whatever *_chunk*.npy files exist and holds one chunk out as validation.


1. Prerequisites

  • Linux x86_64 with glibc β‰₯ 2.19 (required by the prebuilt Blender 2.79b binary below). On macOS/ARM you must instead download the matching Blender 2.79b build for your OS β€” the render scripts are 2.79-specific and will not run on Blender β‰₯ 2.8.
  • Blender 2.79b (see Β§2). CLEVR's scripts break on newer Blender.
  • A separate Python 3 (your normal env, NOT Blender's bundled Python) with numpy and Pillow. This runs the post-processing step. Any recent numpy/Pillow is fine.
  • GPU (optional but ~10Γ— faster). CUDA GPU β†’ render with --use_gpu 1. No GPU β†’ --use_gpu 0 (CPU CYCLES; correct output, just slow). At --render_num_samples 128, GPU is ~seconds/image, CPU is ~minutes/image.
  • Disk: full 1M is ~300 GB (images320 dominates at ~1.5 GB/chunk). One chunk β‰ˆ 1.85 GB. Render to node-local/fast scratch, not a network filesystem, then move the .npy out.

2. Get the code + Blender

The generator is a lightly patched fork of facebookresearch/clevr-dataset-gen. Two things are not in the upstream repo and must be added: a --seed/resume patch to render_images.py, and a new postprocess_chunk.py. Both are given inline below so this doc is self-contained.

git clone https://github.com/facebookresearch/clevr-dataset-gen.git
cd clevr-dataset-gen

# Blender 2.79b (Linux x86_64 glibc219). ~145 MB.
mkdir -p blender_dl && cd blender_dl
wget https://download.blender.org/release/Blender2.79/blender-2.79b-linux-glibc219-x86_64.tar.bz2
tar xjf blender-2.79b-linux-glibc219-x86_64.tar.bz2
cd ..
# sanity: prints "Blender 2.79 (sub 0)"
./blender_dl/blender-2.79b-linux-glibc219-x86_64/blender --background --version

Shortcut if you do have SSH access to the source machine: skip cloning/patching entirely and just copy the ready-to-run tree (includes the Blender binary and both custom files): rsync -a <srchost>:/global/home/users/kwanyoungpark/projects/clevr-dataset-gen/ ./clevr-dataset-gen/ Then jump to Β§4.

2a. Patch image_generation/render_images.py

Two edits: add a --seed argument, seed RNG in main(), and make rendering resume-safe.

Add after the --num_images argument (near the other parser.add_argument lines):

parser.add_argument('--seed', default=-1, type=int,
    help="Random seed for reproducible/unique chunks (>=0 seeds random; -1 = time-based)")

At the top of def main(args): (before num_digits = 6):

  if args.seed >= 0:
    random.seed(args.seed)

Inside the per-image loop in main, right after all_scene_paths.append(scene_path):

    if os.path.isfile(img_path) and os.path.isfile(scene_path):   # resume-safe: skip already-rendered
      continue

2b. Create image_generation/postprocess_chunk.py

This converts one chunk's temp {scenes/*.json, images/*.png} into the three .npy arrays and deletes the temp. Copy verbatim:

"""Post-process one generated chunk: temp {scenes/*.json, images/*.png} -> aligned npy arrays, then delete temp.
Outputs states_chunkKKKK.npy (N,10,7), images320_chunkKKKK.npy (N,240,320,3 uint8), images192_chunkKKKK.npy (N,128,192,3 uint8)."""
import json, glob, os, sys, shutil, numpy as np
from PIL import Image

tmp, K, out = sys.argv[1], int(sys.argv[2]), sys.argv[3]
COLORS = ['gray', 'red', 'blue', 'green', 'brown', 'purple', 'cyan', 'yellow']
SHAPES = ['cube', 'sphere', 'cylinder']; SIZES = ['large', 'small']; MATS = ['rubber', 'metal']
ci = {c: i for i, c in enumerate(COLORS)}; si = {s: i for i, s in enumerate(SHAPES)}
zi = {z: i for i, z in enumerate(SIZES)}; mi = {m: i for i, m in enumerate(MATS)}
MAXO = 10

scenes = sorted(glob.glob(f"{tmp}/scenes/*.json"))
images = sorted(glob.glob(f"{tmp}/images/*.png"))
assert len(scenes) == len(images) and len(scenes) > 0, f"mismatch/empty: {len(scenes)} scenes vs {len(images)} imgs"
n = len(scenes)
states = np.zeros((n, MAXO, 7), dtype=np.float32)
im320 = np.zeros((n, 240, 320, 3), dtype=np.uint8)
im192 = np.zeros((n, 128, 192, 3), dtype=np.uint8)
def m01(v): return 0.2 + (min(3.0, max(-3.0, v)) + 3.0) / 6.0 * 0.6   # 3d [-3,3] -> [0.2,0.8]
for i, (sp, ip) in enumerate(zip(scenes, images)):
    sc = json.load(open(sp))
    for j, o in enumerate(sc['objects'][:MAXO]):
        x, y = o['3d_coords'][0], o['3d_coords'][1]
        states[i, j] = [1.0, si[o['shape']], ci[o['color']], zi[o['size']], mi[o['material']], m01(x), m01(y)]
    im = Image.open(ip).convert('RGB')                          # 320x240
    im320[i] = np.asarray(im, np.uint8)
    im192[i] = np.asarray(im.resize((192, 128), Image.LANCZOS), np.uint8)
os.makedirs(out, exist_ok=True)
kk = f"{K:04d}"
# write to .tmp then rename (atomic -> resume never sees a half-written chunk)
for nm, arr in [(f"states_chunk{kk}", states), (f"images320_chunk{kk}", im320), (f"images192_chunk{kk}", im192)]:
    np.save(f"{out}/{nm}.npy.tmp", arr); os.replace(f"{out}/{nm}.npy.tmp.npy", f"{out}/{nm}.npy")
shutil.rmtree(tmp, ignore_errors=True)
print(f"CHUNK {K} DONE: {n} imgs -> {out}/*_chunk{kk}.npy", flush=True)

3. Smoke test (do this FIRST β€” ~1–2 min on GPU)

Render 8 images and confirm the arrays come out right before committing to a long run.

cd image_generation
BL=../blender_dl/blender-2.79b-linux-glibc219-x86_64/blender
PY=python3                      # your numpy+Pillow python (NOT blender's)
OUT=/path/to/scratch/clevr_gen10_smoke; rm -rf "$OUT"; mkdir -p "$OUT"
TMP=/tmp/gensmoke_$$; rm -rf "$TMP"; mkdir -p "$TMP/images" "$TMP/scenes"

$BL --background --python render_images.py -- \
  --num_images 8 --start_idx 0 --seed 0 --min_objects 3 --max_objects 10 \
  --use_gpu 1 --width 320 --height 240 --render_num_samples 128 \
  --output_image_dir "$TMP/images" --output_scene_dir "$TMP/scenes" --output_scene_file "$TMP/scenes.json"

$PY postprocess_chunk.py "$TMP" 0 "$OUT"
$PY -c "import numpy as np; s=np.load('$OUT/states_chunk0000.npy'); \
  print('states', s.shape, 'objs/scene', [int((s[i,:,0]>0.5).sum()) for i in range(len(s))])"

Expect: states (8, 10, 7) and each scene reporting 3–10 present objects. If you see that, the pipeline works. (No GPU? use --use_gpu 0; it will just be much slower.)


4. Render one full chunk (5,000 scenes)

This is the unit of work. K is the chunk index (0…199 for the full 1M).

cd image_generation
BL=../blender_dl/blender-2.79b-linux-glibc219-x86_64/blender
PY=python3
OUT=/path/to/scratch/clevr_gen10_1M; mkdir -p "$OUT"

K=0
KK=$(printf %04d $K)
# resume: skip a chunk that's already fully written
if [ -f "$OUT/states_chunk${KK}.npy" ] && [ -f "$OUT/images192_chunk${KK}.npy" ]; then
  echo "chunk $K already done"; exit 0
fi
TMP=/tmp/gen1M_$$_$K; rm -rf "$TMP"; mkdir -p "$TMP/images" "$TMP/scenes"
$BL --background --python render_images.py -- \
  --num_images 5000 --start_idx 0 --seed $K --min_objects 3 --max_objects 10 --use_gpu 1 \
  --width 320 --height 240 --render_num_samples 128 \
  --output_image_dir "$TMP/images" --output_scene_dir "$TMP/scenes" --output_scene_file "$TMP/scenes.json"
$PY postprocess_chunk.py "$TMP" $K "$OUT"

--seed $K is what makes each chunk a different 5,000 scenes β€” same seed β‡’ identical scenes. Use the chunk index as the seed so chunks never collide and the whole set is reproducible.


5. Scale up

Plain shell loop (single machine, sequential)

for K in $(seq 0 199); do
  KK=$(printf %04d $K)
  [ -f "$OUT/states_chunk${KK}.npy" ] && [ -f "$OUT/images192_chunk${KK}.npy" ] && continue
  TMP=/tmp/gen1M_$$_$K; rm -rf "$TMP"; mkdir -p "$TMP/images" "$TMP/scenes"
  $BL --background --python render_images.py -- \
    --num_images 5000 --start_idx 0 --seed $K --min_objects 3 --max_objects 10 --use_gpu 1 \
    --width 320 --height 240 --render_num_samples 128 \
    --output_image_dir "$TMP/images" --output_scene_dir "$TMP/scenes" --output_scene_file "$TMP/scenes.json"
  $PY postprocess_chunk.py "$TMP" $K "$OUT"
done

Run several of these in parallel over disjoint K ranges if you have multiple GPUs. Because each chunk is independent and the loop skips completed chunks, you can kill/restart freely.

SLURM array (how the original 1M was made)

40-task array, 5 chunks per task (K = task*5 + c), 24h/task, --requeue, output to node-local /tmp. The reference sbatch is on the source machine at ~/projects/clevr-dataset-gen/gen_1M_10obj.sbatch β€” adapt its #SBATCH header (account, partition, qos, gres) to your cluster. Its body is exactly the Β§4 command wrapped in the Β§5 loop.


6. Verify the output

$PY - <<'PY'
import glob, numpy as np, os
OUT=os.environ.get("OUT","/path/to/scratch/clevr_gen10_1M")
ch=sorted(glob.glob(f"{OUT}/states_chunk*.npy"))
print("chunks:", len(ch))
s=np.load(ch[0]); im=np.load(ch[0].replace("states","images192"))
assert s.shape[1:]==(10,7) and im.shape[1:]==(128,192,3), (s.shape, im.shape)
pres=(s[...,0]>0.5).sum(1)
print("states", s.shape, "images192", im.shape, "dtype", im.dtype)
print("objs/scene min/max:", int(pres.min()), int(pres.max()))   # expect 3..10
print("shape vals:", np.unique(s[...,1][s[...,0]>0]))             # {0,1,2}
print("color vals:", np.unique(s[...,2][s[...,0]>0]))             # 0..7
print("posX range:", float(s[...,5][s[...,0]>0].min()), float(s[...,5][s[...,0]>0].max()))  # ~[0.2,0.8]
PY

Once verified, this directory is a drop-in --chunk-dir for SparseWM/scripts/enc_vqa_maskproj.py / enc_supervised_gt_clevr.py (--chunk-img-prefix images192). To share it, upload as a WebDataset with SparseWM/scripts/clevr_to_webdataset.py (the 1M set already lives at HF GGOSinon/clevr-1M-128x192).


7. Gotchas (these bite)

  • Two different Pythons. Blender runs render_images.py with its own bundled interpreter (has bpy, no numpy you control). postprocess_chunk.py runs with your system Python (needs numpy + Pillow). Don't try to import bpy outside Blender or import numpy inside the render.
  • Render to local disk. Writing 5,000 PNGs to a network FS is painfully slow and can stall. Render into node-local /tmp/..., post-process to .npy, then the .npy (only ~1.85 GB/chunk) goes to shared storage. postprocess_chunk.py deletes the temp PNGs automatically.
  • --use_gpu 1 needs a working CUDA setup visible to Blender 2.79's CYCLES (set CUDA_HOME, PATH, LD_LIBRARY_PATH for your CUDA install before launching Blender). If GPU init fails Blender may silently fall back to CPU or error β€” check the first image's render time.
  • --render_num_samples 128 is a deliberate speed/quality tradeoff (upstream default is 512). Keep 128 to match the existing dataset; raise it only if you want cleaner images (much slower).
  • Blender must be 2.79b. 2.8+ removed user_preferences / changed the CYCLES API and the CLEVR scripts will crash.
  • Resumability relies on the atomic .npy.tmp β†’ rename in post-processing and the skip-if-exists checks. Never point two workers at the same chunk index simultaneously.
  • Determinism: seed = chunk index. Same Blender build + same seed β‡’ identical scenes; different Blender versions can produce slightly different renders even at the same seed.