File size: 6,973 Bytes
f9c42e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sys
import os
import time
import json
import asyncio
import pickle

import click
import numpy as np
import torch
import dill
import hydra
import omegaconf
import traceback
from omegaconf import open_dict

from unified_video_action.policy.base_image_policy import BaseImagePolicy
from unified_video_action.workspace.base_workspace import BaseWorkspace
from unified_video_action.common.pytorch_util import dict_apply
from umi.real_world.real_inference_util import get_real_obs_resolution

import torch.nn.functional as F
import websockets

language_latents = pickle.load(open("prepared_data/language_latents.pkl", "rb"))


def echo_exception():
    exc_type, exc_value, exc_traceback = sys.exc_info()
    tb_lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
    return "".join(tb_lines)


def smooth_action(act_out, window_size=3, pad_size=1):
    kernel = torch.ones(1, 1, window_size) / window_size
    kernel = kernel.to(act_out.device)

    act_out_padded = F.pad(act_out, (0, 0, pad_size, pad_size), mode="replicate")

    batch_size, timesteps, action_dim = act_out_padded.shape
    act_out_padded = act_out_padded.permute(0, 2, 1)
    act_out_padded = act_out_padded.reshape(-1, 1, timesteps)

    smoothed_act_out = F.conv1d(act_out_padded, kernel, padding=0)

    smoothed_act_out = smoothed_act_out.reshape(batch_size, action_dim, timesteps - 2 * pad_size)
    smoothed_act_out = smoothed_act_out.permute(0, 2, 1)

    return smoothed_act_out


class PolicyInferenceNode:
    def __init__(self, ckpt_path: str, ip: str, port: int, device: str, output_dir: str):
        self.ckpt_path = ckpt_path
        if not self.ckpt_path.endswith(".ckpt"):
            self.ckpt_path = os.path.join(self.ckpt_path, "checkpoints", "latest.ckpt")
        payload = torch.load(open(self.ckpt_path, "rb"), map_location="cpu", pickle_module=dill)
        self.cfg = payload["cfg"]

        with open_dict(self.cfg):
            if "autoregressive_model_params" in self.cfg.model.policy:
                self.cfg.model.policy.autoregressive_model_params.num_sampling_steps = "100"
                print("-----------------------------------------------")
                print(
                    "num_sampling_steps",
                    self.cfg.model.policy.autoregressive_model_params.num_sampling_steps,
                )
                print("-----------------------------------------------")

        cfg_path = self.ckpt_path.replace(".ckpt", ".yaml")
        with open(cfg_path, "w") as f:
            f.write(omegaconf.OmegaConf.to_yaml(self.cfg))
            print(f"Exported config to {cfg_path}")
        print(
            f"Loading configure: {self.cfg.task.name}, workspace: {self.cfg.model._target_}, policy: {self.cfg.model.policy._target_}"
        )

        self.obs_res = get_real_obs_resolution(self.cfg.task.shape_meta)

        cls = hydra.utils.get_class(self.cfg.model._target_)
        self.workspace = cls(self.cfg, output_dir=output_dir)
        self.workspace: BaseWorkspace
        self.workspace.load_payload(payload, exclude_keys=None, include_keys=None)

        self.policy: BaseImagePolicy = self.workspace.model

        if self.cfg.training.use_ema:
            self.policy = self.workspace.ema_model
            print("Using EMA model")

        self.device = torch.device(device)
        self.policy.eval().to(self.device)
        self.policy.reset()
        self.ip = ip
        self.port = port

    def _prepare_language_goal(self, task_name: str):
        if self.cfg.task.dataset.language_emb_model is None:
            return None

        key = None
        if task_name is None:
            return None
        for candidate in ["cup", "towel", "mouse"]:
            if candidate in task_name:
                key = candidate
                break
        if key is None:
            return None
        language_goal = language_latents.get(key)
        if language_goal is None:
            return None
        language_goal = torch.tensor(language_goal).to(self.device).unsqueeze(0)
        return language_goal

    def predict_action(self, obs_dict_np: dict, past_action_list=None):
        if past_action_list is None:
            past_action_list = []

        task_name = obs_dict_np.pop("task_name", None)
        language_goal = self._prepare_language_goal(task_name)

        with torch.no_grad():
            obs_dict = dict_apply(
                obs_dict_np, lambda x: torch.from_numpy(x).unsqueeze(0).to(self.device)
            )

            if self.cfg.name == "uva":
                result = self.policy.predict_action(obs_dict=obs_dict, language_goal=language_goal)
                past_action_list.append(np.array(result["action"][0].cpu()))
                if len(past_action_list) > 2:
                    past_action_list.pop(0)
                action = smooth_action(result["action_pred"].detach().to("cpu")).numpy()[0]
            else:
                result = self.policy.predict_action(obs_dict, language_goal=language_goal)
                action = result["action_pred"][0].detach().to("cpu").numpy()

            del result
            del obs_dict

        return action, past_action_list

    async def _handle_connection(self, websocket):
        past_action_list = []
        async for message in websocket:
            try:
                request = json.loads(message)
                payload = request.get("body", request.get("data", request))
                if isinstance(payload, str):
                    payload = json.loads(payload)
                if not isinstance(payload, dict):
                    raise ValueError("Parsed payload is not a dict")

                start_time = time.monotonic()
                action, past_action_list = self.predict_action(payload, past_action_list)
                elapsed = time.monotonic() - start_time

                response = {
                    "status": "ok",
                    "action": action.tolist(),
                    "inference_time": elapsed,
                }
            except Exception:
                err_str = echo_exception()
                response = {"status": "error", "error": err_str}

            await websocket.send(json.dumps(response))

    async def run_node(self):
        print(f"PolicyInferenceNode WebSocket listening on {self.ip}:{self.port}")
        async with websockets.serve(self._handle_connection, self.ip, self.port):
            await asyncio.Future()  # run forever


@click.command()
@click.option("--input", "-i", required=True, help="Path to checkpoint")
@click.option("--ip", default="0.0.0.0")
@click.option("--port", default=8766, help="Port to listen on")
@click.option("--device", default="cuda", help="Device to run on")
@click.option("--output_dir", required=True)
def main(input, ip, port, device, output_dir):
    node = PolicyInferenceNode(input, ip, port, device, output_dir)
    asyncio.run(node.run_node())


if __name__ == "__main__":
    main()