File size: 31,708 Bytes
c99d198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
"""
Train a policy using SAC.
Env: MetaWorld
"""

import collections
import os
import os.path as osp
from typing import Optional

from absl import app
from absl import flags
from absl import logging
from ml_collections import config_dict
from ml_collections import config_flags
from torchkit import CheckpointManager
from torchkit import experiment
from torchkit import Logger
from tqdm.auto import tqdm
import torch
import torch.nn as nn
import torchvision.transforms as T
import torch.nn.functional as F
import numpy as np
import albumentations as A
import cv2
from PIL import Image

from sac import agent
from base_configs import validate_config
import utils
import matplotlib.pyplot as plt

from r3m import load_r3m

from flowdiffusion.inference_utils import get_video_model, pred_video
from datasets import RoboSuiteDataset

FLAGS = flags.FLAGS

flags.DEFINE_string("experiment_name", None, "Experiment name.")
flags.DEFINE_string("env_name", None, "The environment name.")
flags.DEFINE_integer("num_envs", 4, "Number of parallel envs for training.")
flags.DEFINE_integer("seed", 0, "RNG seed.")
flags.DEFINE_string("device", "cuda:0", "The compute device.")
flags.DEFINE_boolean("resume", False, "Resume experiment from last checkpoint.")
flags.DEFINE_boolean(
    "randomize_initial_state",
    False,
    "If True, each env reset randomizes object positions (and robot init noise). "
    "Set to False for static initial state (e.g. fixed cube positions in Stack).",
)

config_flags.DEFINE_config_file(
    "config",
    "base_configs/rl.py",
    "File path to the training hyperparameter configuration.",
)

def evaluate(
    policy, 
    env, 
    task_txts, 
    switch_to_vgen, 
    encoder, 
    video_model, 
    subgoal_r3m_embs,
    subgoal_embs, 
    scale_factors, 
    train_step, 
    device, 
    buffer,
    num_episodes,
    dist_txt_path,
    chunk_len,
    action_execute_dim,
    epsilon, 
):
    """Evaluate the policy and dump rollout videos to disk."""
    policy.eval()
    stats = collections.defaultdict(list)
    success = 0
    all_episodes_data = []
    
    for num_episode in range(num_episodes):
        observation, _ = env.reset()
        for _ in range(10):
            observation, _, _, _, _ = env.step([0.0] * 6 + [-1.0])
            continue
            
        done = False 
        subgoal_idx = 1
        cur_visual_state = observation

        # # Running video plan
        if switch_to_vgen:
            initial_frame = preprocess_for_reward_model(cur_visual_state)
            initial_frame = cv2.cvtColor(initial_frame, cv2.COLOR_BGR2RGB)  # (128, 128, 3)
            images = pred_video(video_model, initial_frame, task_txts) # (8, 3, 128, 128)
            images = images.unsqueeze(0).to(device) # pixel value range [0., 1.], (1, 8, 3, 128, 128)
            # subgoal_embs = buffer.model.infer(images, [task_txts] * 8).numpy().embs

            # Encode generated images with r3m
            subgoal_r3m_embs = encode_r3m_batch(images.squeeze(), encoder, device)

        # # Save images: shape (8, 3, 128, 128), values 0..255
        # imgs = (images.squeeze().cpu().numpy()*255).astype('uint8')                   # ensure uint8
        # imgs_hwc = np.transpose(imgs, (0, 2, 3, 1))      # (8, 128, 128, 3)
        # strip = np.concatenate(list(imgs_hwc), axis=1)   # (128, 8*128, 3)
        # Image.fromarray(strip).save(f"episode_{num_episode}.png")
        # # Video plan done

        subgoal_emb, normalized_subgoal_emb = retrieve_goal_with_idx(subgoal_idx, subgoal_embs)
        visual_feature = preprocess_for_r3m(cur_visual_state, encoder, device)
        observation = np.concatenate((visual_feature, subgoal_r3m_embs[subgoal_idx])) #normalized_subgoal_emb
        info = {'episode_steps': 0}
        episode_data = []

        while not done:
            action = policy.act(observation.astype(np.float32), sample=False)
            action = np.clip(action, -1, 1)
            action_chunk = action.reshape(chunk_len, -1)
            for act_idx in range(action_execute_dim):
                act = action_chunk[act_idx]
                next_observation, reward, terminated, truncated, info = env.step(act)
            
            next_visual_state = next_observation
            # ---- BEGIN progress measure between visual_state and next_visual_state. ----
            cur_obs_image = preprocess_for_reward_model(cur_visual_state) # Sent to buffer.
            next_obs_image = preprocess_for_reward_model(next_visual_state) # Sent to buffer.
            cur_next_obs_img_pair = [buffer._pixel_to_tensor(obs_img) for obs_img in [cur_obs_image, next_obs_image]]
            cur_next_obs_img_pair = torch.cat(cur_next_obs_img_pair, dim=1)
            cur_next_obs_emb_pair = buffer.model.infer(cur_next_obs_img_pair, [task_txts] * 2).numpy().embs # TODO automate env name 
            cur_next_obs_emb_pair = cur_next_obs_emb_pair.squeeze()

            image_reward = next_obs_image.copy()

            progress, d_t, d_tp1, hit = compute_progress_to_subgoal(
                emb=cur_next_obs_emb_pair, 
                subgoal_emb=subgoal_emb.numpy(),
                scale_factor=scale_factors[subgoal_idx-1], 
                segment_scale=1.0 / np.linalg.norm(subgoal_embs[subgoal_idx]-subgoal_embs[subgoal_idx-1], axis=-1), 
                epsilon=epsilon,
            )
            # Store progress and subgoal index
            episode_data.append((d_tp1, subgoal_idx))

            if hit and subgoal_idx < len(subgoal_embs)-1:
                subgoal_idx = min(subgoal_idx + 1, len(subgoal_embs) - 1)

            # ---- END progress measure. ----
            next_subgoal_emb, normalized_next_subgoal_emb = retrieve_goal_with_idx(subgoal_idx, subgoal_embs)
            next_visual_feature = preprocess_for_r3m(next_visual_state, encoder, device)
            next_observation = np.concatenate((next_visual_feature, subgoal_r3m_embs[subgoal_idx]))  # normalized_next_subgoal_emb
            
            observation = next_observation
            cur_visual_state = next_visual_state
            subgoal_emb = next_subgoal_emb
            
            done = terminated or truncated #truncated #
        
        print(f"Episode {num_episode} reached {subgoal_idx}.")
        success += info["episode"]["success"]

        all_episodes_data.append(episode_data)

        for k, v in info["episode"].items():
            stats[k].append(v)
        if "eval_score" in info:
            stats["eval_score"].append(info["eval_score"])

    plot_distance_log(all_episodes_data, dist_txt_path)

    stats["success_rate"].append(success/num_episodes)
    for k, v in stats.items():
        stats[k] = np.mean(v)
    return stats

def write_dists_to_file(dists, dist_txt_path):
    filename = osp.join(dist_txt_path, "dists_log.txt")
    
    new_line = ",".join(map(str, dists))
    
    # Load existing lines if the file exists
    if os.path.exists(filename):
        with open(filename, "r") as f:
            lines = f.read().splitlines()
    else:
        lines = []

    # Append new line and keep only the last 20
    lines.append(new_line)
    lines = lines[-20:]

    # Write back to the file
    with open(filename, "w") as f:
        f.write("\n".join(lines) + "\n")

def plot_distance_log(all_episodes_data, file_path):
    """
    Plots the progress for each episode in a separate subplot, with vertical lines
    to indicate subgoal changes.
    """
    image_path = os.path.join(file_path, "reward.png")

    num_episodes = len(all_episodes_data)
    if num_episodes == 0:
        print("No episode data to plot.")
        return

    # Determine grid size for subplots
    cols = min(3, num_episodes)
    rows = (num_episodes + cols - 1) // cols
    fig, axes = plt.subplots(rows, cols, figsize=(5 * cols, 4 * rows), squeeze=False)

    # Flatten the axes array for easier iteration
    axes = axes.flatten()

    for i, episode_data in enumerate(all_episodes_data):
        ax = axes[i]
        
        # Unzip the data into separate lists for progress and subgoal_idx
        progress_values = [d[0] for d in episode_data]
        subgoal_indices = [d[1] for d in episode_data]
        
        # Plot the progress values
        ax.plot(progress_values, label="Progress")
        ax.set_title(f"Episode {i+1}")
        ax.set_xlabel("Step in Episode")
        ax.set_ylabel("Distance to Subgoal")
        ax.grid(True, linestyle='--', alpha=0.6)

        # Plot vertical lines at each subgoal change
        # A change occurs when the current subgoal index is different from the next one.
        change_points = [j for j in range(len(subgoal_indices) - 1) if subgoal_indices[j] != subgoal_indices[j+1]]
        for j in change_points:
            ax.axvline(x=j+1, color='r', linestyle=':', linewidth=2, label=f'Subgoal {subgoal_indices[j+1]}')

        # Add a legend only for the first subplot to avoid clutter
        if i == 0:
            handles, labels = ax.get_legend_handles_labels()
            by_label = dict(zip(labels, handles))
            fig.legend(by_label.values(), by_label.keys(), loc='upper center', bbox_to_anchor=(0.5, 1.05), ncol=2)

    # Hide any unused subplots
    for i in range(num_episodes, len(axes)):
        fig.delaxes(axes[i])

    plt.tight_layout(rect=[0, 0, 1, 0.95])  # Adjust layout to make space for the main title
    plt.suptitle("Episode Progress and Subgoal Changes", fontsize=16)
    plt.savefig(image_path, dpi=300)
    plt.close()

## Can move this utility to utils.py.
def preprocess_for_reward_model(visual_obs):

    center_crop = A.CenterCrop(height=84, width=84, p=1.0)

    image = np.array(visual_obs)
    # image_reward = visual_obs#cv2.resize(visual_obs, (360, 360), interpolation=cv2.INTER_AREA)
    # crop_size = 150
    # h, w, _ = image_reward.shape
    # image_cropped = image_reward[
    #     (h-crop_size)//2:(h+crop_size)//2, 
    #     (w-crop_size)//2:(w+crop_size)//2
    # ]
    # image_cropped = center_crop(image=image)["image"]

    image_final = cv2.resize(image, (84, 84), interpolation=cv2.INTER_AREA)
    
    image_final = cv2.cvtColor(image_final, cv2.COLOR_BGR2RGB)
    # cv2.imwrite("processed_for_reward.png", image_final)

    return image_final

# ## Can move this utility to utils.py.
# def preprocess_for_video_model(visual_obs):
#     visual_obs = cv2.resize(visual_obs, (320, 240), interpolation=cv2.INTER_AREA)
#     center_crop = A.CenterCrop(height=128, width=128, p=1.0)

#     image = np.array(visual_obs)
#     image_cropped = center_crop(image=image)["image"]

#     image_final = cv2.resize(image_cropped, (128, 128), interpolation=cv2.INTER_AREA)

#     return image_final

## Can move this utility to utils.py.
@torch.no_grad()
def preprocess_for_r3m(image, model, device):
    """Resize image to 224x224 and convert to R3M input tensor."""

    image = np.array(image) # (84,84,3)

    transform = T.Compose([
        T.ToPILImage(),
        T.Resize(224),
        T.ToTensor()
    ])
    tensor_image = transform(image)
    
    # # Convert back to PIL for saving
    # image_to_save = T.ToPILImage()(tensor_image)
    # image_to_save.save('processed_for_observation.png')

    tensor_image = tensor_image.unsqueeze(0).to(device)
    r3m_feat = model(tensor_image * 255.0)
    n_r3m_feat = r3m_feat.squeeze().cpu().numpy() #n_r3m_feat
    return n_r3m_feat

@torch.no_grad()
def encode_r3m_batch(images, model, device):
    """
    Encode a batch of images with R3M.

    Args:
        images: torch.Tensor or np.ndarray of shape (N, 3, 128, 128), values in [0, 1].
        model:  R3M model (expects inputs scaled to [0, 255]).
        device: torch.device to run on.

    Returns:
        np.ndarray of shape (N, D) with R3M features.
    """
    if isinstance(images, np.ndarray):
        images = torch.from_numpy(images)

    assert images.ndim == 4 and images.shape[1] == 3 and images.shape[2:] == (128, 128), \
        f"Expected (N, 3, 128, 128), got {tuple(images.shape)}"

    images = images.to(device)
    try:
        images_224 = F.interpolate(images, size=(224, 224), mode="bilinear", align_corners=False, antialias=True)
    except TypeError:
        images_224 = F.interpolate(images, size=(224, 224), mode="bilinear", align_corners=False)

    feats = model(images_224 * 255.0)  # (N, D)
    return feats.detach().cpu().numpy()

def retrieve_goal_with_idx(
    idx, 
    subgoals, 
):
    assert idx <= len(subgoals) - 1
    subgoal = torch.tensor(subgoals[idx])
    subgoal_normalized = subgoal / (subgoal.norm(p=2) + 1e-8)

    return subgoal, subgoal_normalized

def encode_reward_image(self, image_reward, task="assembly", squeeze=True):
    """
    image_reward: HxWxC uint8 NumPy array (or anything _pixel_to_tensor supports)
    returns: (D,) if squeeze else (1,1,D)
    """
    x = self._pixel_to_tensor(image_reward)          # -> (1,1,C,H,W) on self.device
    with torch.no_grad():
        out = self.model.infer(x, [task]).numpy().embs  # typically (1,1,D)
    return out.squeeze((0,1)) if squeeze else out

def compute_progress_to_subgoal(
    emb, # shape (2, D): [curr_feat, next_feat]
    subgoal_emb, # shape (D,) or (1, D)
    scale_factor, 
    segment_scale, # e.g., 1.0 / ||g_i - g_{i-1}|| if you use segment normalization
    epsilon # optional: threshold to mark a subgoal hit
):
    g = subgoal_emb.reshape(1, -1)
    curr, nxt = emb[0], emb[1]

    d_t    = np.linalg.norm(curr - g, axis=-1)   # shape (1,)
    d_tp1  = np.linalg.norm(nxt  - g , axis=-1)   # shape (1,)

    # Optional segment normalization: multiply by 1/||g_i - g_{i-1}||
    if segment_scale is not None:
        d_t   = d_t   * segment_scale
        d_tp1 = d_tp1 * segment_scale
    progress = d_t - d_tp1   # positive means you moved closer to g_i

    # Optional subgoal hit flag
    hit = None
    if epsilon is not None:
        hit = (d_tp1 < epsilon)

    # If you're going to use this as a numeric reward, you can detach:
    # progress = progress.detach()

    return progress, d_t, d_tp1, hit

# @torch.no_grad()
# def encode_subgoals_from_paths(
#     paths, 
#     task_txt, 
#     reward_model, 
#     device, 
#     preprocessor_func, 
#     pixel_to_tensor_func 
# ):
#     """Loads images from paths, preprocesses, and encodes them into subgoal embeddings."""
    
#     image_tensors = []
    
#     for path in paths:
#         # Load raw image from path
#         raw_image = np.array(Image.open(path).convert('RGB')) 
        
#         # Apply reward model preprocessing (e.g., cropping/resizing)
#         processed_img = preprocessor_func(raw_image)
        
#         # Convert to model input tensor format: (1, 1, C, H, W) on device
#         image_tensors.append(pixel_to_tensor_func(processed_img))

#     # Concatenate all frame tensors for batched inference (1, N, C, H, W)
#     images_batch = torch.cat(image_tensors, dim=1)

#     # Infer embeddings: shape (N, D)
#     out = reward_model.infer(images_batch, [task_txt] * len(paths))
#     subgoal_embs = out.numpy().embs  # Shape: (num_keyframes, embedding_dim)

#     return subgoal_embs

@torch.no_grad()
def encode_goals_with_r3m(
    paths,  # The list of image file paths
    r3m_model, 
    device, 
):

    r3m_feature_tensors = []
    
    # R3M-specific preprocessing components (hardcoded from preprocess_for_r3m)
    r3m_transform = T.Compose([
        T.ToPILImage(),
        T.Resize(224),
        T.ToTensor()
    ])

    for path in paths:
        # 1. Load raw image from path
        raw_image = np.array(Image.open(path).convert('RGB'))
        
        # 2. Apply R3M-specific transforms (Tensor operations)
        tensor_image = r3m_transform(raw_image)
        
        # 3. Prepare for batching: (1, C, H, W)
        tensor_image = tensor_image.unsqueeze(0).to(device)
        
        r3m_feature_tensors.append(tensor_image)

    # Concatenate all frame tensors for batched inference (N, C, H, W)
    # R3M is an image encoder, so we concatenate along the batch dimension (dim=0)
    images_batch = torch.cat(r3m_feature_tensors, dim=0) 

    # R3M inference: R3M expects inputs scaled to 0-255
    r3m_feat = r3m_model(images_batch * 255.0)
    
    # Convert batch of features to final NumPy array (N, D)
    subgoal_embs_with_r3m = r3m_feat.cpu().numpy()

    return subgoal_embs_with_r3m


@experiment.pdb_fallback
def main(_):
    validate_config(FLAGS.config, mode='rl')

    config = FLAGS.config
    exp_dir = osp.join(
        config.save_dir,
        FLAGS.experiment_name,
        str(FLAGS.seed),
    )
    utils.setup_experiment(exp_dir, config, FLAGS.resume)

    # Setup device.
    if torch.cuda.is_available():
        device = torch.device(FLAGS.device)
    else:
        logging.info("No GPU device found. Falling back to CPU.")
        device = torch.device('cpu')
    logging.info("Using device: %s", device)

    # Setup RNG seeds.
    if FLAGS.seed is not None:
        logging.info("RL experiment seed: %d", FLAGS.seed)
        experiment.seed_rngs(FLAGS.seed)
        experiment.set_cudnn(config.cudnn_deterministic, config.cudnn_benchmark)
    else:
        logging.info("No RNG seed has been set for this RL experiment.")

    # Load train and eval environments.
    env = utils.make_env(
        env_name=FLAGS.env_name,
        seed=FLAGS.seed,
        save_dir = None,
        add_episode_monitor = True,
        action_repeat = config.action_repeat,
        frame_stack = config.frame_stack,
        randomize_initial_state=FLAGS.randomize_initial_state,
    )

    eval_env = utils.make_env(
        env_name=FLAGS.env_name,
        seed=FLAGS.seed + 10_000,
        save_dir = osp.join(exp_dir, "video", "eval"),
        add_episode_monitor = True,
        action_repeat=config.action_repeat,
        frame_stack=config.frame_stack,
        randomize_initial_state=FLAGS.randomize_initial_state,
    )

    # Action chunk
    chunk_len = 1
    action_execute_dim = 1

    # Load r3m for visual observations feature extraction. Update obs dim to match.
    r3m = load_r3m("resnet50")
    r3m.eval()
    for p in r3m.parameters():
        p.requires_grad = False
    r3m.to(device)

    video_model = get_video_model(ckpts_dir='./video_model_ckpts/mw', milestone=36)

    # dinov2_model = torch.hub.load('facebookresearch/dinov2', 'dinov2_vitb14')
    # dinov2_model = dinov2_model.to('cuda' if torch.cuda.is_available() else 'cpu')
    # dinov2_model.eval()

    # Set observation and action space values.
    config.sac.obs_dim = 2048+2048 #128 #+4*2 #env.observation_space.shape[0]
    config.sac.action_dim = env.action_space.shape[0]
    config.sac.action_range = [
        float(env.action_space.low.min()),
        float(env.action_space.high.max()),
    ]
    config.sac.chunk_len = chunk_len

    camera = "corner2"
    task_txts = FLAGS.env_name

    # Resave the config since the dynamic values have been updated at this point
    # and make it immutable for safety :)
    utils.dump_config(exp_dir, config)
    config = config_dict.FrozenConfigDict(config)

    # Create policy
    policy = agent.SAC(device, config.sac)
    
    # Create buffer and embs of subgoals
    buffer, subgoal_embs, scale_factors = utils.make_buffer(env, device, config)
    print(f"---- {len(subgoal_embs)} subgoal frames, {len(scale_factors)} scale factors. ----")
    avg_subgoal_embs = subgoal_embs.copy()

    # Create demo data for sampling subgoals 
    goal_sequence_set = RoboSuiteDataset(
        sample_per_seq=config.sample_per_seq, 
        path="./datasets/mimicgen", 
        task_txt=task_txts, 
        target_size=(84, 84),
        randomcrop=False,
        split='train',
    )

    # Create checkpoint manager
    checkpoint_dir = osp.join(exp_dir, "checkpoints")
    checkpoint_manager = CheckpointManager(
        checkpoint_dir,
        policy=policy,
        **policy.optim_dict(),
    )

    logger = Logger(osp.join(exp_dir, "tb"), FLAGS.resume)

    # Training, evaluation, and checkpointing. 
    try:
        i = -1
        start = checkpoint_manager.restore_or_initialize()
        switch_to_vgen, switch_to_random_seq = False, False

        observation, _ = env.reset()
        for _ in range(10):
            observation, _, _, _, _ = env.step([0.0] * 6 + [-1.0])
            continue
        
        done = False 
        subgoal_idx = 1
        print(observation.shape)
        cur_visual_state = observation #(84, 84, 3)

        # print(cur_visual_state.shape)
        # initial_frame = preprocess_for_reward_model(cur_visual_state)
        # initial_frame = cv2.cvtColor(initial_frame, cv2.COLOR_BGR2RGB) # (128, 128, 3)
        # images = pred_video(video_model, initial_frame, task_txts) # (8, 3, 128, 128)
        # images = images.unsqueeze(0).to(device) # pixel value range [0., 1.], (1, 8, 3, 128, 128)

        # # Save images: shape (8, 3, 128, 128), values 0..255
        # imgs = (images.squeeze().cpu().numpy()*255).astype('uint8')                   # ensure uint8
        # imgs_hwc = np.transpose(imgs, (0, 2, 3, 1))      # (8, 128, 128, 3)
        # strip = np.concatenate(list(imgs_hwc), axis=1)   # (128, 8*128, 3)
        # Image.fromarray(strip).save("strip.png")
        # assert False
        
        # # Encode generated video into subgoal features
        # video_subgoal_features = buffer.model.infer(images, [task_txts] * len(subgoal_embs)).numpy().embs
        # print(video_subgoal_features.shape, video_subgoal_features.min(1), video_subgoal_features.max(1))
        # print(subgoal_embs.shape, subgoal_embs.min(1), subgoal_embs.max(1))
        # assert False

        subgoal_paths, task_txts = goal_sequence_set.sample_goal_sequence_paths(num_keyframes=config.sample_per_seq)
        # subgoal_embs = encode_subgoals_from_paths(
        #     subgoal_paths, 
        #     task_txts, 
        #     buffer.model, 
        #     device, 
        #     preprocess_for_reward_model, 
        #     buffer._pixel_to_tensor # Assumes buffer has the _to_tensor utility
        # )

        subgoal_r3m_embs = encode_goals_with_r3m(
            subgoal_paths,
            r3m, 
            device, 
        )
        
        visual_feature = preprocess_for_r3m(cur_visual_state, r3m, device)

        subgoal_emb, normalized_subgoal_emb = retrieve_goal_with_idx(subgoal_idx, subgoal_embs)

        observation = np.concatenate((visual_feature, subgoal_r3m_embs[subgoal_idx])) # normalized_subgoal_emb
        # print(subgoal_emb.max(), subgoal_emb.min(), normalized_subgoal_emb.max(), normalized_subgoal_emb.min())

        for i in tqdm(range(start, config.num_train_steps // action_execute_dim), initial=start):
            # Random sample / policy inference.
            if i < config.num_seed_steps // action_execute_dim:
                action = np.array([env.action_space.sample() for _ in range(chunk_len)])
            else:
                policy.eval()
                action = policy.act(observation.astype(np.float32), sample=True)

            # Action chunk post-processing
            action_chunk = action.reshape(chunk_len, -1)
            action = action.flatten() # Format for replay buffer.

            for act_idx in range(action_execute_dim):
                act = action_chunk[act_idx]
                next_observation, reward, terminated, truncated, info = env.step(act)
            done = terminated or truncated #truncated #
            
            # Read next observations
            next_visual_state = next_observation

            # ---- BEGIN progress measure between visual_state and next_visual_state. ----
            cur_obs_image = preprocess_for_reward_model(cur_visual_state) # Sent to buffer.
            next_obs_image = preprocess_for_reward_model(next_visual_state) # Sent to buffer.
            cur_next_obs_img_pair = [buffer._pixel_to_tensor(obs_img) for obs_img in [cur_obs_image, next_obs_image]]
            cur_next_obs_img_pair = torch.cat(cur_next_obs_img_pair, dim=1)
            # print("Image pair:", cur_next_obs_img_pair.min(), cur_next_obs_img_pair.max(), cur_next_obs_img_pair.shape)
            cur_next_obs_emb_pair = buffer.model.infer(cur_next_obs_img_pair, [task_txts] * 2).numpy().embs # TODO automate env name 
            cur_next_obs_emb_pair = cur_next_obs_emb_pair.squeeze()

            image_reward = next_obs_image.copy()

            progress, d_t, d_tp1, hit = compute_progress_to_subgoal(
                emb=cur_next_obs_emb_pair, 
                subgoal_emb=subgoal_emb.numpy(),
                scale_factor=scale_factors[subgoal_idx-1], 
                segment_scale=1.0 / np.linalg.norm(subgoal_embs[subgoal_idx]-subgoal_embs[subgoal_idx-1], axis=-1), 
                epsilon=config.epsilon,
            )
            # ---- END progress measure. ----
            reward_sum = 0.0 
            reward_sum += -0.1 * d_tp1 #1.0 * progress - 0.5 * 
            if hit and subgoal_idx < len(subgoal_embs)-1:
                reward_sum += 7.5  #/10 #* subgoal_idx
                subgoal_idx = min(subgoal_idx + 1, len(subgoal_embs) - 1)

            # Sparse termination reward for action chunk.
            if done and hit and info["episode"]["success"] == True and subgoal_idx >= len(subgoal_embs) - 2:
                reward_sum += 15

            if done and info["episode"]["success"] == True and subgoal_idx < len(subgoal_embs) - 2:
                reward_sum -= 100
            
            next_visual_feature = preprocess_for_r3m(next_visual_state, r3m, device)

            next_subgoal_emb, normalized_next_subgoal_emb = retrieve_goal_with_idx(subgoal_idx, subgoal_embs)

            next_observation = np.concatenate((next_visual_feature, subgoal_r3m_embs[subgoal_idx]))# normalized_next_subgoal_emb

            # Add to Replay Buffer
            
            if not done or 'TimeLimit.truncated' in info:
                mask = 1.0
            else:
                mask = 0.0

            if not config.reward_wrapper.pretrained_path:
                buffer.insert(observation, action, reward, next_observation, mask)
            else:
                buffer.insert(
                    observation,
                    action,
                    reward_sum,#reward,
                    next_observation,
                    mask,
                    image_reward,
                    subgoal_emb,
                )
            observation = next_observation
            cur_visual_state = next_visual_state
            subgoal_emb = next_subgoal_emb
            

            if done:

                # Check episode just ended.
                # if subgoal_idx > 4:
                print(subgoal_idx)

                observation, _ = env.reset()
                for _ in range(10):
                    observation, _, _, _, _ = env.step([0.0] * 6 + [-1.0])
                    continue
                    
                done = False
                subgoal_idx = 1
                cur_visual_state = observation

                subgoal_paths, task_txts = goal_sequence_set.sample_goal_sequence_paths(num_keyframes=config.sample_per_seq)
                # subgoal_embs = encode_subgoals_from_paths(
                #     subgoal_paths, 
                #     task_txts, 
                #     buffer.model, 
                #     device, 
                #     preprocess_for_reward_model, 
                #     buffer._pixel_to_tensor
                # )

                subgoal_r3m_embs = encode_goals_with_r3m(
                    subgoal_paths,
                    r3m, 
                    device, 
                )

                # print("Demo images r3m feature:", subgoal_r3m_embs.shape, subgoal_r3m_embs.min(), subgoal_r3m_embs.max())

                # Finetuning on video generated goals
                if switch_to_vgen:
                    initial_frame = preprocess_for_reward_model(cur_visual_state)
                    initial_frame = cv2.cvtColor(initial_frame, cv2.COLOR_BGR2RGB)  # (128, 128, 3)
                    images = pred_video(video_model, initial_frame, task_txts) # (8, 3, 128, 128)
                    images = images.unsqueeze(0).to(device) # pixel value range [0., 1.], (1, 8, 3, 128, 128)
                    # subgoal_embs = buffer.model.infer(images, [task_txts] * 8).numpy().embs

                    # Encode generated images with r3m
                    subgoal_r3m_embs = encode_r3m_batch(images.squeeze(), r3m, device)
                    # print("Vgen images r3m feature:", subgoal_r3m_embs.shape, subgoal_r3m_embs.min(), subgoal_r3m_embs.max())

                    # imgs = (images.squeeze().cpu().numpy()*255).astype('uint8')
                    # imgs_hwc = np.transpose(imgs, (0, 2, 3, 1))      # (8, 128, 128, 3)
                    # strip = np.concatenate(list(imgs_hwc), axis=1)   # (128, 8*128, 3)
                    # Image.fromarray(strip).save("strip.png")

                    
                visual_feature = preprocess_for_r3m(cur_visual_state, r3m, device)
                subgoal_emb, normalized_subgoal_emb = retrieve_goal_with_idx(subgoal_idx, subgoal_embs)
                observation = np.concatenate((visual_feature, subgoal_r3m_embs[subgoal_idx])) #normalized_subgoal_emb

                for k, v in info["episode"].items():
                    logger.log_scalar(
                        v, info["total"]["timesteps"], 
                        k, 
                        "training"
                    )

            if i >= config.num_seed_steps // action_execute_dim:
                if len(buffer) >= config.sac.batch_size:
                    policy.train()
                    train_info = policy.update(buffer, i)
                else:
                    train_info = {}

                if (i + 1) % (config.log_frequency // action_execute_dim) == 0:
                    if train_info:
                        for k, v in train_info.items():
                            logger.log_scalar(
                                v, 
                                info["total"]["timesteps"], 
                                k, 
                                "training"
                            )
                    logger.flush()

            if (i + 1) % (config.eval_frequency) == 0:
                eval_stats = evaluate(
                    policy, 
                    eval_env, 
                    task_txts, 
                    switch_to_vgen,
                    r3m, 
                    video_model, 
                    subgoal_r3m_embs,
                    subgoal_embs, 
                    scale_factors, 
                    i, 
                    device, 
                    buffer, 
                    config.num_eval_episodes, 
                    exp_dir, 
                    chunk_len=chunk_len,
                    action_execute_dim=action_execute_dim,
                    epsilon=config.epsilon,
                )
                for k, v in eval_stats.items():
                    logger.log_scalar(
                        v,
                        info["total"]["timesteps"],
                        f"average_{k}s",
                        "evaluation",
                    )
                logger.flush()

                # Order of update matters.
                if (not switch_to_vgen) and eval_stats["success_rate"] > config.threshold_for_vgen:
                    switch_to_vgen = True

            if (i + 1) % config.checkpoint_frequency == 0:
                checkpoint_manager.save(i)
    
    except KeyboardInterrupt:
        env.close()
        del env
        print("Caught keyboard interrupt. Saving before quitting.")

    finally:
        env.close()
        del env
        checkpoint_manager.save(i)
        logger.close()

if __name__ == "__main__":
    app.run(main)