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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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
#!/usr/bin/env python3
import os
import random
import time
import json
from collections import deque
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import gymnasium as gym
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
import tyro
from torch.distributions.normal import Normal
from torch.utils.tensorboard import SummaryWriter

# Register ManiSkill custom envs in this repo.
import vagen.env.primitive_skill.maniskill.env  # noqa: F401


def layer_init(layer: nn.Module, std: float = np.sqrt(2), bias_const: float = 0.0) -> nn.Module:
    torch.nn.init.orthogonal_(layer.weight, std)
    torch.nn.init.constant_(layer.bias, bias_const)
    return layer


@dataclass
class Args:
    exp_name: str = "ppo_stack_threecube_vision"
    seed: int = 1
    cuda: bool = True
    torch_deterministic: bool = True

    track: bool = False
    wandb_project_name: str = "vagen-threecube"
    wandb_entity: Optional[str] = None

    total_timesteps: int = 30_000_000
    learning_rate: float = 1e-4
    num_envs: int = 16
    num_steps: int = 32
    gamma: float = 0.99
    gae_lambda: float = 0.95
    update_epochs: int = 2
    num_minibatches: int = 4
    clip_coef: float = 0.1
    clip_vloss: bool = True
    ent_coef: float = 0.0
    vf_coef: float = 0.5
    max_grad_norm: float = 0.5
    target_kl: Optional[float] = 0.03
    anneal_lr: bool = True
    norm_adv: bool = True

    image_size: int = 84
    include_proprio: bool = True
    proprio_dim: int = 10
    encoder_feature_dim: int = 512
    freeze_encoder_steps: int = 200_000

    sim_backend: str = "gpu"
    render_backend: str = "gpu"
    allow_backend_fallback: bool = True
    fallback_sim_backend: str = "cpu"
    fallback_render_backend: str = "cpu"
    force_cpu_sim_when_sync_vector: bool = True
    control_mode: str = "pd_ee_delta_pose"
    max_episode_steps: int = 3000
    success_reward: float = 10.0
    stage_reward: float = 2.0
    step_penalty: float = 0.01

    eval_interval: int = 500_000
    eval_episodes: int = 1000
    eval_deterministic: bool = True
    save_best_ckpt: bool = True
    log_window_size: int = 100
    converge_success_threshold: float = 0.80
    stop_training_on_converge: bool = True
    collect_after_converge: bool = True
    post_converge_target_trajs: int = 4000
    post_converge_max_eval_episodes: int = 20000
    logstd_min: float = -5.0
    logstd_max: float = 2.0
    max_abs_reward: float = 20.0
    skip_nonfinite_minibatch: bool = True

    save_trajectories: bool = True
    traj_root: str = "trajectories/threecube/raw"
    max_traj_per_eval: int = 2000

    batch_size: int = 0
    minibatch_size: int = 0
    num_iterations: int = 0


class ThreeCubeVisionWrapper(gym.Wrapper):
    """
    Uses env.render() as RGB observation and keeps optional low-dim proprio.
    """

    def __init__(self, env: gym.Env, image_size: int = 84, include_proprio: bool = True, proprio_dim: int = 10):
        super().__init__(env)
        self.image_size = int(image_size)
        self.include_proprio = bool(include_proprio)
        self.proprio_dim = int(proprio_dim)
        self.action_space = env.action_space
        self.observation_space = gym.spaces.Dict(
            {
                "image": gym.spaces.Box(0.0, 1.0, shape=(3, self.image_size, self.image_size), dtype=np.float32),
                "proprio": gym.spaces.Box(-np.inf, np.inf, shape=(self.proprio_dim,), dtype=np.float32),
            }
        )
        self._last_info: Dict[str, Any] = {}
        self._prev_stage_score = 0.0

    def _render_image(self) -> np.ndarray:
        frame = self.env.render()
        if frame is None:
            raise RuntimeError("env.render() returned None, cannot build visual observation.")

        arr = np.asarray(frame)
        # ManiSkill may return batched frames like (1, H, W, C) when num_envs=1.
        if arr.ndim == 4:
            if arr.shape[0] == 1:
                arr = arr[0]
            else:
                arr = arr[0]
        # Accept both HWC and CHW layouts.
        if arr.ndim == 3 and arr.shape[0] in (1, 3, 4) and arr.shape[-1] not in (1, 3, 4):
            arr = np.transpose(arr, (1, 2, 0))
        if arr.ndim != 3:
            raise RuntimeError(f"Unexpected render output shape: {arr.shape}")
        if arr.shape[-1] == 1:
            arr = np.repeat(arr, 3, axis=-1)
        elif arr.shape[-1] == 4:
            arr = arr[..., :3]

        arr = np.asarray(arr, dtype=np.uint8)
        img = Image.fromarray(arr).convert("RGB")
        img = img.resize((self.image_size, self.image_size))
        arr = np.asarray(img, dtype=np.float32) / 255.0
        return np.transpose(arr, (2, 0, 1))

    def _extract_proprio(self, info: Dict[str, Any]) -> np.ndarray:
        if not self.include_proprio:
            return np.zeros((self.proprio_dim,), dtype=np.float32)
        keys = [
            "gripper_position",
            "red_cube_position",
            "green_cube_position",
            "purple_cube_position",
        ]
        vals: List[float] = []
        for k in keys:
            if k not in info:
                continue
            v = np.asarray(info[k], dtype=np.float32).reshape(-1)
            vals.extend(v.tolist())
            if len(vals) >= self.proprio_dim:
                break
        if len(vals) < self.proprio_dim:
            vals.extend([0.0] * (self.proprio_dim - len(vals)))
        return np.asarray(vals[: self.proprio_dim], dtype=np.float32)

    def _obs_dict(self, info: Dict[str, Any]) -> Dict[str, np.ndarray]:
        return {"image": self._render_image(), "proprio": self._extract_proprio(info)}

    def _stage_score(self, info: Dict[str, Any]) -> float:
        score = 0.0
        for key in ("stage0_success", "stage1_success", "stage2_success"):
            if bool(info.get(key, False)):
                score += 1.0
        return score

    def reset(self, *, seed: Optional[int] = None, options: Optional[Dict[str, Any]] = None):
        _, info = self.env.reset(seed=seed, options=options)
        info = info or {}
        self._last_info = info
        self._prev_stage_score = self._stage_score(info)
        return self._obs_dict(info), info

    def step(self, action):
        _, reward, terminated, truncated, info = self.env.step(action)
        info = info or {}
        info["is_success"] = bool(info.get("success", False))

        stage_score = self._stage_score(info)
        stage_delta = max(0.0, stage_score - self._prev_stage_score)
        self._prev_stage_score = stage_score

        # Convert possible torch/numpy scalar to python scalar for gym wrappers compatibility.
        reward_scalar = float(np.asarray(reward).reshape(-1)[0])
        terminated_scalar = bool(np.asarray(terminated).reshape(-1)[0])
        truncated_scalar = bool(np.asarray(truncated).reshape(-1)[0])

        shaped_reward = reward_scalar
        shaped_reward += stage_delta
        shaped_reward -= 0.01
        if bool(info.get("success", False)):
            shaped_reward += 10.0

        self._last_info = info
        return self._obs_dict(info), shaped_reward, terminated_scalar, truncated_scalar, info


def make_env(args: Args, idx: int, run_name: str):
    def thunk():
        backend_candidates: List[Tuple[str, str]] = [(args.sim_backend, args.render_backend)]
        if args.allow_backend_fallback:
            fallback_pair = (args.fallback_sim_backend, args.fallback_render_backend)
            if fallback_pair not in backend_candidates:
                backend_candidates.append(fallback_pair)

        env = None
        last_err: Optional[Exception] = None
        for sim_backend, render_backend in backend_candidates:
            try:
                env = gym.make(
                    "StackThreeCube",
                    num_envs=1,
                    obs_mode="state",
                    control_mode=args.control_mode,
                    render_mode="rgb_array",
                    sim_backend=sim_backend,
                    render_backend=render_backend,
                    enable_shadow=True,
                )
                if (sim_backend, render_backend) != (args.sim_backend, args.render_backend):
                    print(
                        f"[env {idx}] backend fallback enabled: "
                        f"using sim_backend={sim_backend}, render_backend={render_backend}"
                    )
                break
            except RuntimeError as e:
                last_err = e
                msg = str(e).lower()
                is_cuda_init_err = ("cuda failed" in msg) or ("physxgpusystem" in msg)
                if is_cuda_init_err and args.allow_backend_fallback:
                    print(
                        f"[env {idx}] backend {sim_backend}/{render_backend} init failed: {e}. "
                        "Trying fallback backend..."
                    )
                    continue
                raise

        if env is None:
            raise RuntimeError(
                f"Failed to create StackThreeCube env with candidates={backend_candidates}. "
                f"Last error: {last_err}"
            )
        env = gym.wrappers.TimeLimit(env, max_episode_steps=int(args.max_episode_steps))
        env = ThreeCubeVisionWrapper(
            env,
            image_size=args.image_size,
            include_proprio=args.include_proprio,
            proprio_dim=args.proprio_dim,
        )
        env = gym.wrappers.RecordEpisodeStatistics(env)
        return env

    return thunk


class Agent(nn.Module):
    def __init__(
        self,
        action_dim: int,
        proprio_dim: int,
        encoder_feature_dim: int = 512,
        logstd_min: float = -5.0,
        logstd_max: float = 2.0,
    ):
        super().__init__()
        self.logstd_min = float(logstd_min)
        self.logstd_max = float(logstd_max)
        self.encoder = nn.Sequential(
            layer_init(nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3)),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
            layer_init(nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1)),
            nn.ReLU(),
            layer_init(nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1)),
            nn.ReLU(),
            layer_init(nn.Conv2d(256, 512, kernel_size=3, stride=2, padding=1)),
            nn.ReLU(),
            nn.AdaptiveAvgPool2d((1, 1)),
            nn.Flatten(),
            layer_init(nn.Linear(512, encoder_feature_dim)),
            nn.ReLU(),
        )
        fusion_dim = encoder_feature_dim + int(proprio_dim)
        self.actor_mean = nn.Sequential(
            layer_init(nn.Linear(fusion_dim, 256)),
            nn.Tanh(),
            layer_init(nn.Linear(256, action_dim), std=0.01),
        )
        self.actor_logstd = nn.Parameter(torch.zeros(1, action_dim))
        self.critic = nn.Sequential(
            layer_init(nn.Linear(fusion_dim, 256)),
            nn.Tanh(),
            layer_init(nn.Linear(256, 1), std=1.0),
        )

    def encode(self, image: torch.Tensor, proprio: torch.Tensor) -> torch.Tensor:
        z = self.encoder(image)
        return torch.cat([z, proprio], dim=-1)

    def get_value(self, image: torch.Tensor, proprio: torch.Tensor) -> torch.Tensor:
        h = self.encode(image, proprio)
        return self.critic(h)

    def get_action_and_value(
        self,
        image: torch.Tensor,
        proprio: torch.Tensor,
        action: Optional[torch.Tensor] = None,
    ):
        image = torch.nan_to_num(image, nan=0.0, posinf=1.0, neginf=0.0)
        proprio = torch.nan_to_num(proprio, nan=0.0, posinf=1e3, neginf=-1e3)
        h = self.encode(image, proprio)
        h = torch.nan_to_num(h, nan=0.0, posinf=1e3, neginf=-1e3)
        action_mean = self.actor_mean(h)
        action_mean = torch.nan_to_num(action_mean, nan=0.0, posinf=1.0, neginf=-1.0)
        action_logstd = self.actor_logstd.expand_as(action_mean)
        action_logstd = torch.clamp(action_logstd, self.logstd_min, self.logstd_max)
        action_std = torch.exp(action_logstd)
        probs = Normal(action_mean, action_std)
        if action is None:
            action = probs.sample()
        action = torch.clamp(action, -1.0, 1.0)
        return action, probs.log_prob(action).sum(1), probs.entropy().sum(1), self.critic(h)


def save_eval_trajectories(
    args: Args,
    run_name: str,
    global_step: int,
    records: List[Dict[str, Any]],
) -> int:
    out_dir = Path(args.traj_root) / f"{run_name}" / f"step_{int(global_step)}"
    out_dir.mkdir(parents=True, exist_ok=True)
    frames_dir = out_dir / "frames"
    frames_dir.mkdir(parents=True, exist_ok=True)

    count = 0
    traj_path = out_dir / "trajectories.jsonl"
    with traj_path.open("w", encoding="utf-8") as f:
        for rec in records[: int(args.max_traj_per_eval)]:
            if not rec.get("episode_success", False):
                continue
            episode_id = int(rec["episode_id"])
            frame_paths: List[str] = []
            for t, frame in enumerate(rec["frames"]):
                frame_path = frames_dir / f"ep_{episode_id:06d}_t_{t:05d}.png"
                Image.fromarray(frame).save(frame_path)
                frame_paths.append(str(frame_path))

            item = {
                "state_format": "png_path",
                "frames": frame_paths,
                "robot_state": rec["robot_state"],
                "actions": rec["actions"],
                "rewards": rec["rewards"],
                "success": rec["success_flags"],
                "episode_return": rec["episode_return"],
                "episode_success": rec["episode_success"],
                "episode_id": episode_id,
            }
            f.write(json.dumps(item) + "\n")
            count += 1

    metrics = {
        "global_step": int(global_step),
        "episodes": int(len(records)),
        "trajectory_saved_count": int(count),
        "success_rate": float(np.mean([1.0 if r.get("episode_success", False) else 0.0 for r in records])) if records else 0.0,
    }
    with (out_dir / "metrics.json").open("w", encoding="utf-8") as mf:
        json.dump(metrics, mf, ensure_ascii=False, indent=2)
    return count


def evaluate_policy(args: Args, agent: Agent, device: torch.device, run_name: str, global_step: int) -> Dict[str, float]:
    eval_env = make_env(args, idx=0, run_name=f"{run_name}_eval")()
    episodes = int(args.eval_episodes)
    returns: List[float] = []
    lengths: List[int] = []
    successes: List[float] = []
    records: List[Dict[str, Any]] = []

    for ep in range(episodes):
        obs, info = eval_env.reset(seed=args.seed + 10_000 + ep)
        done = False
        ep_ret = 0.0
        ep_len = 0
        ep_frames: List[np.ndarray] = []
        ep_actions: List[List[float]] = []
        ep_rewards: List[float] = []
        ep_success_flags: List[bool] = []
        ep_robot_state: List[List[float]] = []

        ep_frames.append(np.transpose((obs["image"] * 255.0).astype(np.uint8), (1, 2, 0)))
        ep_robot_state.append(obs["proprio"].astype(np.float32).tolist())

        while not done:
            img_t = torch.tensor(obs["image"], dtype=torch.float32, device=device).unsqueeze(0)
            prop_t = torch.tensor(obs["proprio"], dtype=torch.float32, device=device).unsqueeze(0)
            with torch.no_grad():
                if args.eval_deterministic:
                    h = agent.encode(img_t, prop_t)
                    action = agent.actor_mean(h)
                    action = torch.clamp(action, -1.0, 1.0)
                else:
                    action, _, _, _ = agent.get_action_and_value(img_t, prop_t)
            action_np = action.squeeze(0).cpu().numpy()
            next_obs, reward, term, trunc, info = eval_env.step(action_np)
            done = bool(term) or bool(trunc)
            ep_ret += float(reward)
            ep_len += 1

            ep_actions.append(action_np.astype(np.float32).tolist())
            ep_rewards.append(float(reward))
            ep_success_flags.append(bool(info.get("is_success", False)))
            ep_frames.append(np.transpose((next_obs["image"] * 255.0).astype(np.uint8), (1, 2, 0)))
            ep_robot_state.append(next_obs["proprio"].astype(np.float32).tolist())
            obs = next_obs

        ep_success = bool(any(ep_success_flags))
        returns.append(ep_ret)
        lengths.append(ep_len)
        successes.append(1.0 if ep_success else 0.0)
        records.append(
            {
                "episode_id": ep,
                "frames": ep_frames,
                "robot_state": ep_robot_state,
                "actions": ep_actions,
                "rewards": ep_rewards,
                "success_flags": ep_success_flags,
                "episode_return": float(ep_ret),
                "episode_success": ep_success,
            }
        )

    traj_count = 0
    if args.save_trajectories:
        traj_count = save_eval_trajectories(args, run_name, global_step, records)

    eval_env.close()
    return {
        "success_rate": float(np.mean(successes)) if successes else 0.0,
        "episode_length": float(np.mean(lengths)) if lengths else 0.0,
        "reward_mean": float(np.mean(returns)) if returns else 0.0,
        "trajectory_saved_count": float(traj_count),
    }


def collect_success_trajectories_after_converge(
    args: Args,
    agent: Agent,
    device: torch.device,
    run_name: str,
    global_step: int,
) -> int:
    target = int(args.post_converge_target_trajs)
    max_episodes = int(args.post_converge_max_eval_episodes)
    if target <= 0:
        return 0

    out_dir = Path(args.traj_root) / f"{run_name}" / f"step_{int(global_step)}_converged_collect"
    out_dir.mkdir(parents=True, exist_ok=True)
    frames_dir = out_dir / "frames"
    frames_dir.mkdir(parents=True, exist_ok=True)
    traj_path = out_dir / "trajectories.jsonl"
    metrics_path = out_dir / "metrics.json"

    eval_env = make_env(args, idx=0, run_name=f"{run_name}_collect")()
    saved_count = 0
    total_eval_episodes = 0
    returns: List[float] = []
    lengths: List[int] = []
    success_hist: List[float] = []

    with traj_path.open("w", encoding="utf-8") as f:
        while saved_count < target and total_eval_episodes < max_episodes:
            ep_id = total_eval_episodes
            obs, _ = eval_env.reset(seed=args.seed + 1_000_000 + ep_id)
            done = False
            ep_ret = 0.0
            ep_len = 0
            ep_frames: List[np.ndarray] = []
            ep_actions: List[List[float]] = []
            ep_rewards: List[float] = []
            ep_success_flags: List[bool] = []
            ep_robot_state: List[List[float]] = []

            ep_frames.append(np.transpose((obs["image"] * 255.0).astype(np.uint8), (1, 2, 0)))
            ep_robot_state.append(obs["proprio"].astype(np.float32).tolist())

            while not done:
                img_t = torch.tensor(obs["image"], dtype=torch.float32, device=device).unsqueeze(0)
                prop_t = torch.tensor(obs["proprio"], dtype=torch.float32, device=device).unsqueeze(0)
                with torch.no_grad():
                    if args.eval_deterministic:
                        h = agent.encode(img_t, prop_t)
                        action = torch.clamp(agent.actor_mean(h), -1.0, 1.0)
                    else:
                        action, _, _, _ = agent.get_action_and_value(img_t, prop_t)
                action_np = action.squeeze(0).cpu().numpy()
                next_obs, reward, term, trunc, info = eval_env.step(action_np)
                done = bool(term) or bool(trunc)
                ep_ret += float(reward)
                ep_len += 1

                ep_actions.append(action_np.astype(np.float32).tolist())
                ep_rewards.append(float(reward))
                ep_success_flags.append(bool(info.get("is_success", False)))
                ep_frames.append(np.transpose((next_obs["image"] * 255.0).astype(np.uint8), (1, 2, 0)))
                ep_robot_state.append(next_obs["proprio"].astype(np.float32).tolist())
                obs = next_obs

            ep_success = bool(any(ep_success_flags))
            total_eval_episodes += 1
            returns.append(ep_ret)
            lengths.append(ep_len)
            success_hist.append(1.0 if ep_success else 0.0)

            if ep_success:
                frame_paths: List[str] = []
                for t, frame in enumerate(ep_frames):
                    frame_path = frames_dir / f"ep_{saved_count:06d}_t_{t:05d}.png"
                    Image.fromarray(frame).save(frame_path)
                    frame_paths.append(str(frame_path))
                item = {
                    "state_format": "png_path",
                    "frames": frame_paths,
                    "robot_state": ep_robot_state,
                    "actions": ep_actions,
                    "rewards": ep_rewards,
                    "success": ep_success_flags,
                    "episode_return": float(ep_ret),
                    "episode_success": True,
                    "episode_id": int(saved_count),
                }
                f.write(json.dumps(item) + "\n")
                saved_count += 1
                if saved_count % 100 == 0:
                    print(f"[collect] saved {saved_count}/{target} successful trajectories")

    eval_env.close()
    metrics = {
        "global_step": int(global_step),
        "target_success_trajectories": target,
        "saved_success_trajectories": saved_count,
        "evaluated_episodes": total_eval_episodes,
        "success_rate_over_collection": float(np.mean(success_hist)) if success_hist else 0.0,
        "reward_mean_over_collection": float(np.mean(returns)) if returns else 0.0,
        "episode_length_over_collection": float(np.mean(lengths)) if lengths else 0.0,
    }
    with metrics_path.open("w", encoding="utf-8") as mf:
        json.dump(metrics, mf, ensure_ascii=False, indent=2)
    return saved_count


def set_encoder_trainable(agent: Agent, trainable: bool) -> None:
    for p in agent.encoder.parameters():
        p.requires_grad = bool(trainable)


if __name__ == "__main__":
    args = tyro.cli(Args)
    args.batch_size = int(args.num_envs * args.num_steps)
    args.minibatch_size = int(args.batch_size // args.num_minibatches)
    args.num_iterations = int(args.total_timesteps // args.batch_size)

    run_name = f"StackThreeCube__{args.exp_name}__{args.seed}__{int(time.time())}"
    writer = SummaryWriter(f"runs/{run_name}")
    writer.add_text("hyperparameters", json.dumps(vars(args), indent=2))
    print(f"[log] TensorBoard directory: runs/{run_name}")
    print(f"[log] Open with: tensorboard --logdir runs/{run_name} --port 6006")

    wandb = None
    if args.track:
        import wandb as _wandb

        wandb = _wandb
        wandb.init(
            project=args.wandb_project_name,
            entity=args.wandb_entity,
            sync_tensorboard=True,
            config=vars(args),
            name=run_name,
            monitor_gym=False,
            save_code=True,
        )

    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    torch.backends.cudnn.deterministic = args.torch_deterministic
    device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu")

    # ManiSkill GPU PhysX cannot be instantiated multiple times via Gym SyncVectorEnv.
    # This script uses SyncVectorEnv for PPO collection, so force CPU physics here for stability.
    if args.force_cpu_sim_when_sync_vector and args.num_envs > 1 and str(args.sim_backend).lower() == "gpu":
        print(
            "[setup] Detected SyncVectorEnv + sim_backend=gpu with num_envs>1. "
            "This combination is unstable for ManiSkill (CUDA failed). "
            "Switching sim_backend/render_backend to cpu/cpu automatically."
        )
        args.sim_backend = "cpu"
        args.render_backend = "cpu"

    envs = gym.vector.SyncVectorEnv([make_env(args, i, run_name, ) for i in range(args.num_envs)])
    assert isinstance(envs.single_action_space, gym.spaces.Box), "Continuous action space is required."

    action_dim = int(np.prod(envs.single_action_space.shape))
    agent = Agent(
        action_dim=action_dim,
        proprio_dim=int(envs.single_observation_space["proprio"].shape[0]),
        encoder_feature_dim=args.encoder_feature_dim,
        logstd_min=args.logstd_min,
        logstd_max=args.logstd_max,
    ).to(device)
    optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5)

    obs_image = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space["image"].shape, device=device)
    obs_prop = torch.zeros((args.num_steps, args.num_envs) + envs.single_observation_space["proprio"].shape, device=device)
    actions = torch.zeros((args.num_steps, args.num_envs) + envs.single_action_space.shape, device=device)
    logprobs = torch.zeros((args.num_steps, args.num_envs), device=device)
    rewards = torch.zeros((args.num_steps, args.num_envs), device=device)
    dones = torch.zeros((args.num_steps, args.num_envs), device=device)
    values = torch.zeros((args.num_steps, args.num_envs), device=device)

    global_step = 0
    start_time = time.time()
    next_obs, _ = envs.reset(seed=args.seed)
    next_image = torch.tensor(next_obs["image"], dtype=torch.float32, device=device)
    next_image = torch.nan_to_num(next_image, nan=0.0, posinf=1.0, neginf=0.0)
    next_prop = torch.tensor(next_obs["proprio"], dtype=torch.float32, device=device)
    next_prop = torch.nan_to_num(next_prop, nan=0.0, posinf=1e3, neginf=-1e3)
    next_done = torch.zeros(args.num_envs, dtype=torch.float32, device=device)

    best_stable_sr = -1.0
    eval_interval = max(1, int(args.eval_interval))
    recent_train_rewards: deque = deque(maxlen=int(args.log_window_size))
    recent_train_lengths: deque = deque(maxlen=int(args.log_window_size))
    recent_train_success: deque = deque(maxlen=int(args.log_window_size))
    stop_training = False

    for iteration in range(1, args.num_iterations + 1):
        if args.anneal_lr:
            frac = 1.0 - (iteration - 1.0) / args.num_iterations
            optimizer.param_groups[0]["lr"] = frac * args.learning_rate

        encoder_trainable = global_step >= int(args.freeze_encoder_steps)
        set_encoder_trainable(agent, encoder_trainable)

        for step in range(args.num_steps):
            global_step += args.num_envs
            obs_image[step] = next_image
            obs_prop[step] = next_prop
            dones[step] = next_done

            with torch.no_grad():
                action, logprob, _, value = agent.get_action_and_value(next_image, next_prop)
                values[step] = value.flatten()
            actions[step] = action
            logprobs[step] = logprob

            next_obs, reward, terminations, truncations, infos = envs.step(action.cpu().numpy())
            next_done_np = np.logical_or(terminations, truncations)
            reward_t = torch.tensor(reward, dtype=torch.float32, device=device).view(-1)
            reward_t = torch.clamp(torch.nan_to_num(reward_t, nan=0.0, posinf=args.max_abs_reward, neginf=-args.max_abs_reward), -args.max_abs_reward, args.max_abs_reward)
            rewards[step] = reward_t
            next_image = torch.tensor(next_obs["image"], dtype=torch.float32, device=device)
            next_image = torch.nan_to_num(next_image, nan=0.0, posinf=1.0, neginf=0.0)
            next_prop = torch.tensor(next_obs["proprio"], dtype=torch.float32, device=device)
            next_prop = torch.nan_to_num(next_prop, nan=0.0, posinf=1e3, neginf=-1e3)
            next_done = torch.tensor(next_done_np, dtype=torch.float32, device=device)

            if "final_info" in infos:
                final_infos = infos["final_info"]
                for info in final_infos:
                    if info and "episode" in info:
                        ep_r = float(info["episode"]["r"])
                        ep_l = float(info["episode"]["l"])
                        ep_s = 1.0 if bool(info.get("is_success", False)) else 0.0
                        recent_train_rewards.append(ep_r)
                        recent_train_lengths.append(ep_l)
                        recent_train_success.append(ep_s)
                        writer.add_scalar("train/reward_mean", ep_r, global_step)
                        writer.add_scalar("train/episode_length", ep_l, global_step)
                        writer.add_scalar("train/success_rate", ep_s, global_step)

        with torch.no_grad():
            next_value = agent.get_value(next_image, next_prop).reshape(1, -1)
            advantages = torch.zeros_like(rewards, device=device)
            lastgaelam = 0
            for t in reversed(range(args.num_steps)):
                if t == args.num_steps - 1:
                    nextnonterminal = 1.0 - next_done
                    nextvalues = next_value
                else:
                    nextnonterminal = 1.0 - dones[t + 1]
                    nextvalues = values[t + 1]
                delta = rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t]
                advantages[t] = lastgaelam = delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam
            returns = advantages + values

        b_img = obs_image.reshape((-1,) + envs.single_observation_space["image"].shape)
        b_prop = obs_prop.reshape((-1,) + envs.single_observation_space["proprio"].shape)
        b_img = torch.nan_to_num(b_img, nan=0.0, posinf=1.0, neginf=0.0)
        b_prop = torch.nan_to_num(b_prop, nan=0.0, posinf=1e3, neginf=-1e3)
        b_actions = actions.reshape((-1,) + envs.single_action_space.shape)
        b_logprobs = logprobs.reshape(-1)
        b_advantages = advantages.reshape(-1)
        b_returns = returns.reshape(-1)
        b_values = values.reshape(-1)

        b_inds = np.arange(args.batch_size)
        clipfracs: List[float] = []
        for epoch in range(args.update_epochs):
            np.random.shuffle(b_inds)
            for start in range(0, args.batch_size, args.minibatch_size):
                end = start + args.minibatch_size
                mb_inds = b_inds[start:end]

                _, newlogprob, entropy, newvalue = agent.get_action_and_value(
                    b_img[mb_inds], b_prop[mb_inds], b_actions[mb_inds]
                )
                logratio = newlogprob - b_logprobs[mb_inds]
                ratio = logratio.exp()

                with torch.no_grad():
                    old_approx_kl = (-logratio).mean()
                    approx_kl = ((ratio - 1) - logratio).mean()
                    clipfracs.append(((ratio - 1.0).abs() > args.clip_coef).float().mean().item())

                mb_adv = b_advantages[mb_inds]
                if args.norm_adv:
                    mb_adv = (mb_adv - mb_adv.mean()) / (mb_adv.std() + 1e-8)

                pg_loss1 = -mb_adv * ratio
                pg_loss2 = -mb_adv * torch.clamp(ratio, 1 - args.clip_coef, 1 + args.clip_coef)
                pg_loss = torch.max(pg_loss1, pg_loss2).mean()

                newvalue = newvalue.view(-1)
                if args.clip_vloss:
                    v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2
                    v_clipped = b_values[mb_inds] + torch.clamp(
                        newvalue - b_values[mb_inds], -args.clip_coef, args.clip_coef
                    )
                    v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2
                    v_loss = 0.5 * torch.max(v_loss_unclipped, v_loss_clipped).mean()
                else:
                    v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean()

                entropy_loss = entropy.mean()
                loss = pg_loss - args.ent_coef * entropy_loss + args.vf_coef * v_loss
                if args.skip_nonfinite_minibatch and (not torch.isfinite(loss)):
                    print("[warn] non-finite loss detected, skip minibatch")
                    optimizer.zero_grad(set_to_none=True)
                    continue

                optimizer.zero_grad()
                loss.backward()
                nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm)
                if args.skip_nonfinite_minibatch:
                    grad_ok = True
                    for p in agent.parameters():
                        if p.grad is not None and (not torch.isfinite(p.grad).all()):
                            grad_ok = False
                            break
                    if not grad_ok:
                        print("[warn] non-finite gradients detected, skip optimizer step")
                        optimizer.zero_grad(set_to_none=True)
                        continue
                optimizer.step()

            if args.target_kl is not None and approx_kl > args.target_kl:
                break

        sps = int(global_step / max(1e-6, time.time() - start_time))
        writer.add_scalar("losses/value_loss", v_loss.item(), global_step)
        writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step)
        writer.add_scalar("losses/entropy", entropy_loss.item(), global_step)
        writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step)
        writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step)
        writer.add_scalar("losses/clipfrac", float(np.mean(clipfracs)) if clipfracs else 0.0, global_step)
        writer.add_scalar("charts/fps", sps, global_step)
        writer.add_scalar("charts/encoder_trainable", 1.0 if encoder_trainable else 0.0, global_step)
        train_reward_avg = float(np.mean(recent_train_rewards)) if recent_train_rewards else float("nan")
        train_len_avg = float(np.mean(recent_train_lengths)) if recent_train_lengths else float("nan")
        train_sr_avg = float(np.mean(recent_train_success)) if recent_train_success else float("nan")
        steps_to_eval = int(max(0, eval_interval - (global_step % eval_interval)))
        print(
            "step={} fps={} encoder_trainable={} "
            "train_reward@{}={:.3f} train_len@{}={:.1f} train_sr@{}={:.3f} "
            "loss_pi={:.4f} loss_v={:.4f} kl={:.6f} next_eval_in={}".format(
                global_step,
                sps,
                encoder_trainable,
                len(recent_train_rewards),
                train_reward_avg,
                len(recent_train_lengths),
                train_len_avg,
                len(recent_train_success),
                train_sr_avg,
                float(pg_loss.item()),
                float(v_loss.item()),
                float(approx_kl.item()),
                steps_to_eval,
            )
        )
        if wandb is not None:
            wandb.log(
                {
                    "global_step": int(global_step),
                    "train/reward_mean_window": train_reward_avg,
                    "train/episode_length_window": train_len_avg,
                    "train/success_rate_window": train_sr_avg,
                    "losses/policy_loss": float(pg_loss.item()),
                    "losses/value_loss": float(v_loss.item()),
                    "losses/entropy": float(entropy_loss.item()),
                    "losses/approx_kl": float(approx_kl.item()),
                    "losses/clipfrac": float(np.mean(clipfracs)) if clipfracs else 0.0,
                    "charts/fps": sps,
                    "charts/encoder_trainable": 1.0 if encoder_trainable else 0.0,
                },
                step=global_step,
            )

        if global_step % eval_interval == 0:
            metrics = evaluate_policy(args, agent, device, run_name, global_step)
            writer.add_scalar("eval/success_rate", metrics["success_rate"], global_step)
            writer.add_scalar("eval/episode_length", metrics["episode_length"], global_step)
            writer.add_scalar("eval/reward_mean", metrics["reward_mean"], global_step)
            writer.add_scalar("eval/trajectory_saved_count", metrics["trajectory_saved_count"], global_step)
            writer.add_scalar("eval/fps", sps, global_step)
            print(
                "[eval] step={} success_rate={:.4f} episode_length={:.2f} "
                "reward_mean={:.4f} trajectory_saved_count={}".format(
                    global_step,
                    float(metrics["success_rate"]),
                    float(metrics["episode_length"]),
                    float(metrics["reward_mean"]),
                    int(metrics["trajectory_saved_count"]),
                )
            )

            if wandb is not None:
                wandb.log(
                    {
                        "global_step": int(global_step),
                        "eval/success_rate": metrics["success_rate"],
                        "eval/episode_length": metrics["episode_length"],
                        "eval/reward_mean": metrics["reward_mean"],
                        "eval/trajectory_saved_count": metrics["trajectory_saved_count"],
                        "eval/fps": sps,
                    },
                    step=global_step,
                )

            if metrics["success_rate"] > best_stable_sr:
                best_stable_sr = metrics["success_rate"]
                if args.save_best_ckpt:
                    ckpt_dir = Path("runs") / run_name / "checkpoints"
                    ckpt_dir.mkdir(parents=True, exist_ok=True)
                    ckpt_path = ckpt_dir / f"best_sr_{best_stable_sr:.4f}_step_{global_step}.pt"
                    torch.save(
                        {
                            "model": agent.state_dict(),
                            "optimizer": optimizer.state_dict(),
                            "global_step": global_step,
                            "success_rate": best_stable_sr,
                            "args": vars(args),
                        },
                        ckpt_path,
                    )
                    print(f"Saved best checkpoint to {ckpt_path}")

            if args.stop_training_on_converge and metrics["success_rate"] >= float(args.converge_success_threshold):
                print(
                    f"[converged] eval success_rate={metrics['success_rate']:.4f} >= "
                    f"threshold={args.converge_success_threshold:.4f}. Stop training."
                )
                if args.collect_after_converge:
                    collected = collect_success_trajectories_after_converge(args, agent, device, run_name, global_step)
                    print(f"[collect] finished, saved {collected} successful trajectories")
                    writer.add_scalar("collect/saved_success_trajectories", float(collected), global_step)
                    if wandb is not None:
                        wandb.log(
                            {
                                "global_step": int(global_step),
                                "collect/saved_success_trajectories": float(collected),
                            },
                            step=global_step,
                        )
                stop_training = True
                break

    if stop_training:
        print("[train] stopped after convergence-triggered collection.")

    envs.close()
    writer.close()