File size: 5,766 Bytes
cfa2024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""VLR data, step 2 on db: same latents as vlr_fetch_encode.py, but from the local images of the db HDD.

Waits until the shared GPU has >= --min-free MiB free, polled every 2 s (never stops other jobs); an OOM caused
by another job makes it wait and retry. Images are decoded / squashed to 384 (PIL bilinear, as QAP) by a process pool.
Output: /mnt/10TB_HDD/nuReasoning/vlr/cache/<split>/<kf_id>.npz with front (8, 576, 1024) and side (7, 3, 576, 1024)
float16, and cam_ok (8,) bool = the camera's image folder existed (else its frames are black). Resumable. Run (db): python vlr_encode_local.py --splits val test train
"""
import argparse
import json
import os
import pickle
import subprocess
import sys
import time
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

import numpy as np
import torch
from PIL import Image

sys.path.insert(0, '/home/db/ThuongBui/localization/vljepa_testmatch/src')
from vljepa_mc.vision import build_vjepa_encoder  # noqa: E402
from gpu_take import take_gpu  # noqa: E402

ROOT = Path('/mnt/10TB_HDD/nuReasoning/vlr')
REPO = '/home/db/ThuongBui/localization/third_party/vjepa2'
CKPT = '/home/db/ThuongBui/localization/checkpoints/vjepa2_1_vitl_dist_vitG_384.pt'
CAMERAS = ['front', 'front_left', 'front_right', 'left', 'right', 'back', 'back_left', 'back_right']
MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1, 1)
STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1, 1)


def free_mib():
    o = subprocess.run(['nvidia-smi', '--query-gpu=memory.total,memory.used', '--format=csv,noheader,nounits'],
                       capture_output=True, text=True).stdout.split(',')
    return int(o[0]) - int(o[1])


def wait_gpu(need):
    """poll every 2 s (the chain's gpu_hold.py keeps the GPU between stages and releases it just before this)."""
    n = 0
    while True:
        a = free_mib()
        if a >= need:
            print(time.strftime('%H:%M:%S'), f'GPU free {a} MiB -> run', flush=True)
            return
        if n % 300 == 0:
            print(time.strftime('%H:%M:%S'), f'GPU busy ({a} MiB free), waiting', flush=True)
        n += 1; time.sleep(2)


def _nearest(path):
    """the image itself, else the closest-in-time image of the same camera folder (None if the folder is empty)."""
    p = Path(path)
    if p.is_file():
        return p, False
    try:
        names = sorted(n for n in os.listdir(p.parent) if n.endswith('.jpg'))
    except FileNotFoundError:
        return None, True
    if not names:
        return None, True
    ts = int(p.stem.rsplit('_', 1)[1])
    best = min(names, key=lambda n: abs(int(n[:-4].rsplit('_', 1)[1]) - ts))
    return p.parent / best, True


def load_kf(r):
    miss = []

    def sq(path):
        q, substituted = _nearest(path)
        if substituted:
            miss.append(path)
        if q is None:
            return np.zeros((384, 384, 3), np.uint8)
        return np.asarray(Image.open(q).convert('RGB').resize((384, 384), Image.Resampling.BILINEAR))
    front = np.stack([sq(p) for p in r['video']['front']])
    side = np.stack([np.stack([sq(p) for p in r['video'][c]]) for c in CAMERAS[1:]])
    cam_ok = np.array([os.path.isdir(os.path.dirname(r['video'][c][-1])) for c in CAMERAS])
    return r['kf_id'], front, side, miss, cam_ok


def encode(enc, vids, dev):
    x = torch.from_numpy(vids).permute(0, 4, 1, 2, 3).float().div_(255)
    x = ((x - MEAN) / STD).to(device=dev, dtype=torch.bfloat16)
    with torch.no_grad(), torch.autocast('cuda', dtype=torch.bfloat16):
        out = enc(x)
    out = out[-1] if isinstance(out, (tuple, list)) else out
    return out.float().cpu().numpy().astype(np.float16)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--splits', nargs='+', default=['val', 'test', 'train'])
    ap.add_argument('--min-free', type=int, default=10000)
    ap.add_argument('--procs', type=int, default=10)
    a = ap.parse_args()
    enc = build_vjepa_encoder(REPO, CKPT)            # load on CPU first, then take the GPU and move at once
    take_gpu(a.min_free)
    dev = torch.device('cuda')
    enc = enc.to(device=dev, dtype=torch.bfloat16)
    with ProcessPoolExecutor(a.procs) as pool:
        for split in a.splits:
            out = ROOT / 'cache' / split; out.mkdir(parents=True, exist_ok=True)
            recs = [r for r in pickle.load(open(ROOT / 'data' / f'{split}.pkl', 'rb')) if not (out / f"{r['kf_id']}.npz").is_file()]
            print(f'{split}: {len(recs)} keyframes to encode', flush=True)
            t0 = time.time()
            missing = {}
            for i, (kf_id, front, side, miss, cam_ok) in enumerate(pool.map(load_kf, recs, chunksize=2)):
                if miss:
                    missing[kf_id] = miss
                while True:
                    try:
                        f = encode(enc, front[None], dev)[0]
                        s = np.concatenate([encode(enc, side[j:j + 4], dev) for j in range(0, 7, 4)])
                        break
                    except torch.OutOfMemoryError:
                        torch.cuda.empty_cache(); print('OOM (shared GPU) -> wait', flush=True); wait_gpu(a.min_free)
                tmp = out / f'{kf_id}.tmp.npz'
                np.savez(tmp, front=f.reshape(8, 576, 1024), side=s.reshape(7, 3, 576, 1024), cam_ok=cam_ok)
                tmp.replace(out / f'{kf_id}.npz')
                if (i + 1) % 100 == 0 or i + 1 == len(recs):
                    (ROOT / f'missing_frames_{split}.json').write_text(json.dumps(missing))
                    r = (i + 1) / (time.time() - t0)
                    print(f'{split} {i + 1}/{len(recs)} {r:.2f} kf/s eta {(len(recs) - i - 1) / r / 60:.0f} min', flush=True)
    print('ENCODE_DONE', flush=True)


if __name__ == '__main__':
    main()