File size: 12,304 Bytes
a4cfa9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#!/usr/bin/env python3
"""Evaluate a released WorldDiT checkpoint on LIBERO."""

from __future__ import annotations

import argparse
import copy
import contextlib
import json
import math
import os
import random
import subprocess
import sys
from collections import deque
from pathlib import Path

import clip
import numpy as np
import torch
from PIL import Image
from scipy.spatial.transform import Rotation
from torch.nn.parallel import DistributedDataParallel as DDP
from tqdm.auto import tqdm

from inference import ACTION_HORIZON, CONTEXT_STEPS, SUITES, load_model


def rank():
    return int(os.environ.get("RANK", "0"))


def world_size():
    return int(os.environ.get("WORLD_SIZE", "1"))


def launch(gpus: int):
    if not 1 <= gpus <= torch.cuda.device_count():
        raise ValueError(f"--gpus must be between 1 and {torch.cuda.device_count()}")
    command = [
        sys.executable,
        "-m",
        "torch.distributed.run",
        "--standalone",
        f"--nproc_per_node={gpus}",
        str(Path(__file__).resolve()),
        *sys.argv[1:],
    ]
    environment = os.environ.copy()
    environment.setdefault("OMP_NUM_THREADS", "1")
    return subprocess.run(command, check=False, env=environment).returncode


def configure_libero(libero_root: Path, output: Path):
    package = libero_root / "libero" / "libero"
    required = (package / "bddl_files", package / "init_files", package / "assets")
    if any(not path.is_dir() for path in required):
        raise FileNotFoundError(f"invalid LIBERO checkout: {libero_root}")
    config_dir = output / "libero_config"
    if rank() == 0:
        output.mkdir(parents=True, exist_ok=False)
        config_dir.mkdir()
        paths = {
            "assets": str(package / "assets"),
            "bddl_files": str(package / "bddl_files"),
            "benchmark_root": str(package),
            "datasets": str(package.parent / "datasets"),
            "init_states": str(package / "init_files"),
        }
        (config_dir / "config.yaml").write_text(json.dumps(paths), encoding="utf-8")
    torch.distributed.barrier()
    os.environ["LIBERO_CONFIG_PATH"] = str(config_dir)
    sys.path.insert(0, str(libero_root))


def orientation(quaternion):
    quaternion = np.asarray(quaternion, dtype=np.float64).copy()
    quaternion[3] = np.clip(quaternion[3], -1.0, 1.0)
    denominator = np.sqrt(1.0 - quaternion[3] ** 2)
    axisangle = (
        np.zeros(3)
        if math.isclose(denominator, 0.0)
        else quaternion[:3] * 2.0 * math.acos(quaternion[3]) / denominator
    )
    return Rotation.from_euler("xyz", axisangle).as_euler("xyz")


def finish_action(action: torch.Tensor):
    action = action.detach().cpu().numpy().copy()
    action[-1] = 1.0 if action[-1] > 0.5 else -1.0
    return action


class PolicyRunner:
    def __init__(
        self, model, temperature: float, execution_horizon: int, max_steps: int
    ):
        self.model = model
        self.processor = getattr(model, "module", model).image_processor
        self.temperature = temperature
        self.execution_horizon = execution_horizon
        self.max_steps = max_steps

    def reset(self):
        self.primary = deque(maxlen=CONTEXT_STEPS)
        self.wrist = deque(maxlen=CONTEXT_STEPS)
        self.state = deque(maxlen=CONTEXT_STEPS)
        self.pending = deque()
        self.predictions = torch.zeros(
            self.max_steps, self.max_steps + ACTION_HORIZON, 7, device="cuda"
        )
        self.valid = torch.zeros(
            self.max_steps,
            self.max_steps + ACTION_HORIZON,
            dtype=torch.bool,
            device="cuda",
        )

    def observe(self, observation):
        primary = Image.fromarray(observation["agentview_image"][::-1])
        wrist = Image.fromarray(observation["robot0_eye_in_hand_image"])
        self.primary.append(self.processor(primary).unsqueeze(0).unsqueeze(0))
        self.wrist.append(self.processor(wrist).unsqueeze(0).unsqueeze(0))
        state = np.concatenate(
            (
                observation["robot0_eef_pos"],
                orientation(observation["robot0_eef_quat"]),
                observation["robot0_gripper_qpos"],
            )
        )
        self.state.append(torch.from_numpy(state).float().view(1, 1, -1))

    def prefill(self, observations):
        for observation in observations[-CONTEXT_STEPS:-1]:
            self.observe(observation)

    def ensemble(self, chunk: torch.Tensor, timestep: int):
        self.predictions[timestep, timestep : timestep + ACTION_HORIZON] = chunk
        self.valid[timestep, timestep : timestep + ACTION_HORIZON] = True
        selected = []
        for target in range(timestep, timestep + self.execution_horizon):
            mask = self.valid[: timestep + 1, target]
            actions = self.predictions[: timestep + 1, target][mask]
            weights = np.exp(-self.temperature * np.arange(len(actions)))
            weights = torch.as_tensor(weights / weights.sum(), device="cuda").unsqueeze(
                1
            )
            selected.append(finish_action((actions * weights).sum(0)))
        self.pending.extend(selected[1:])
        return selected[0]

    @torch.inference_mode()
    def act(self, observation, instruction: str, timestep: int):
        self.observe(observation)
        if self.pending:
            return self.pending.popleft()
        if len(self.primary) != CONTEXT_STEPS:
            raise RuntimeError("evaluation requires three real context observations")
        primary = torch.cat(tuple(self.primary), dim=1).cuda()
        wrist = torch.cat(tuple(self.wrist), dim=1).cuda()
        state = torch.cat(tuple(self.state), dim=1).cuda()
        text = (
            clip.tokenize([instruction] * CONTEXT_STEPS, truncate=True)
            .view(1, CONTEXT_STEPS, -1)
            .cuda()
        )
        chunk = self.model(primary, wrist, state, text)[0, -1]
        return self.ensemble(chunk, timestep)


def evaluate(args, model):
    with (
        open(os.devnull, "w") as quiet,
        contextlib.redirect_stdout(quiet),
        contextlib.redirect_stderr(quiet),
    ):
        from libero.libero import benchmark
        from libero.libero.envs import OffScreenRenderEnv

        suite = benchmark.get_benchmark_dict()[args.suite]()
    runner = PolicyRunner(
        model, args.temperature, args.execution_horizon, args.max_steps
    )
    total = args.tasks * args.episodes
    assigned = list(range(total))[rank() :: world_size()]
    local_results = []
    progress = tqdm(
        assigned,
        desc=f"GPU {rank()}",
        position=rank(),
        dynamic_ncols=True,
        leave=True,
    )
    for evaluation_id in progress:
        task_id, episode_index = divmod(evaluation_id, args.episodes)
        episode_id = args.episode_offset + episode_index
        task = suite.get_task(task_id)
        bddl = (
            args.libero_path
            / "libero"
            / "libero"
            / "bddl_files"
            / task.problem_folder
            / task.bddl_file
        )
        environment = OffScreenRenderEnv(
            bddl_file_name=str(bddl),
            camera_heights=128,
            camera_widths=128,
            render_gpu_device_id=int(os.environ["LOCAL_RANK"]),
        )
        try:
            environment.reset()
            environment.seed(66)
            initial_states = torch.load(
                args.libero_path
                / "libero"
                / "libero"
                / "init_files"
                / task.problem_folder
                / task.init_states_file,
                weights_only=False,
            )
            if episode_id >= len(initial_states):
                raise IndexError(
                    f"episode {episode_id} is unavailable for task {task_id}"
                )
            observation = environment.set_init_state(initial_states[episode_id])
            warmup = []
            for _ in range(5):
                observation, _, _, _ = environment.step(np.zeros(7))
                warmup.append(copy.deepcopy(observation))
            runner.reset()
            runner.prefill(warmup)
            observation = warmup[-1]
            success = 0
            for steps in range(1, args.max_steps + 1):
                action = runner.act(observation, task.language, steps - 1)
                observation, _, done, _ = environment.step(action)
                if done:
                    success = 1
                    break
            local_results.append((evaluation_id, task_id, episode_id, success, steps))
            progress.set_postfix(successes=sum(item[3] for item in local_results))
        finally:
            environment.close()

    gathered = [None] * world_size() if rank() == 0 else None
    torch.distributed.gather_object(local_results, gathered, dst=0)
    if rank() != 0:
        return
    results = sorted((item for group in gathered for item in group), key=lambda x: x[0])
    per_task = []
    print()
    for task_id in range(args.tasks):
        values = [item[3] for item in results if item[1] == task_id]
        rate = float(np.mean(values))
        per_task.append(rate)
        print(f"Task {task_id}: {sum(values)}/{len(values)} ({rate:.1%})")
    successes = sum(item[3] for item in results)
    print(f"Overall: {successes}/{len(results)} ({successes / len(results):.1%})")
    report = {
        "suite": args.suite,
        "gpus": world_size(),
        "episodes": len(results),
        "successes": successes,
        "success_rate": successes / len(results),
        "per_task_success_rate": per_task,
        "results": [
            {"task": item[1], "episode": item[2], "success": item[3], "steps": item[4]}
            for item in results
        ],
    }
    (args.output_dir / "results.json").write_text(
        json.dumps(report, indent=2) + "\n", encoding="utf-8"
    )


def parser():
    value = argparse.ArgumentParser(description=__doc__)
    value.add_argument("--suite", required=True, choices=SUITES)
    value.add_argument("--gpus", type=int, default=1)
    value.add_argument(
        "--model-root", type=Path, default=Path(__file__).resolve().parent
    )
    value.add_argument(
        "--libero-path", type=Path, default=Path("~/LIBERO").expanduser()
    )
    value.add_argument("--output-dir", type=Path, required=True)
    value.add_argument("--tasks", type=int, default=10)
    value.add_argument("--episodes", type=int, default=50)
    value.add_argument("--episode-offset", type=int, default=0)
    value.add_argument("--max-steps", type=int, default=600)
    value.add_argument("--execution-horizon", type=int, choices=(1, 3), default=3)
    value.add_argument("--temperature", type=float, default=0.01)
    return value


def main():
    args = parser().parse_args()
    if "RANK" not in os.environ:
        return launch(args.gpus)
    if args.gpus != world_size():
        raise ValueError(
            f"--gpus={args.gpus} but torchrun started {world_size()} workers"
        )
    args.model_root = args.model_root.expanduser().resolve()
    args.libero_path = args.libero_path.expanduser().resolve()
    args.output_dir = args.output_dir.expanduser().resolve()
    os.environ.update(MUJOCO_GL="egl", PYOPENGL_PLATFORM="egl")
    os.environ.setdefault("NCCL_IB_DISABLE", "1")
    os.environ.setdefault("NCCL_P2P_DISABLE", "1")
    os.environ.setdefault("NCCL_CUMEM_ENABLE", "0")
    os.environ.setdefault("TORCH_NCCL_BLOCKING_WAIT", "1")
    torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))
    torch.distributed.init_process_group(
        backend="nccl", device_id=torch.device("cuda", int(os.environ["LOCAL_RANK"]))
    )
    try:
        configure_libero(args.libero_path, args.output_dir)
        model = load_model(args.model_root, args.suite, torch.device("cuda"))
        seed = 66 + rank()
        random.seed(seed)
        np.random.seed(seed)
        torch.manual_seed(seed)
        model = DDP(
            model,
            device_ids=[int(os.environ["LOCAL_RANK"])],
            find_unused_parameters=True,
        )
        model.eval()
        evaluate(args, model)
        torch.distributed.barrier()
    finally:
        torch.distributed.destroy_process_group()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())