forked from lucidrains/robotic-transformer-pytorch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
237 lines (221 loc) · 7.1 KB
/
main.py
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
import argparse
import os
from typing import Dict
import gymnasium as gym
import numpy as np
import torch
import wandb
from sentence_transformers import SentenceTransformer
from torch.optim import Adam
from data import create_dataset
from rt1_pytorch.rt1_policy import RT1Policy
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--datasets",
type=list,
default=["fractal20220817_data"],
)
parser.add_argument(
"--train-split",
type=str,
default="train[:-1000]",
help="use e.g. train[:100] for the first 100 episodes",
)
parser.add_argument(
"--eval-split",
type=str,
default="train[-1000:]",
help="use e.g. eval[:100] for the first 100 episodes",
)
parser.add_argument(
"--epochs",
type=int,
default=1,
help="number of training epochs",
)
parser.add_argument(
"--lr",
type=float,
default=1e-4,
help="learning rate",
)
parser.add_argument(
"--train-batch-size",
type=int,
default=8,
help="train batch size",
)
parser.add_argument(
"--eval-batch-size",
type=int,
default=8,
help="eval batch size",
)
parser.add_argument(
"--trajectory-length",
type=int,
default=6,
help="number of frames per trajectory",
)
parser.add_argument(
"--sentence-transformer",
type=str,
default=None,
help="SentenceTransformer to use; default is None for original USE embeddings",
)
parser.add_argument(
"--device",
type=str,
default="cuda",
help="device to use for training",
)
parser.add_argument(
"--eval-freq",
type=int,
default=None,
help="eval frequency in number of batches; defaults to None",
)
parser.add_argument(
"--checkpoint-freq",
type=int,
default=None,
help="checkpoint frequency in number of batches; defaults to None",
)
parser.add_argument(
"--checkpoint-dir",
type=str,
default="checkpoints/rt1",
help="directory to save checkpoints",
)
parser.add_argument(
"--load-checkpoint",
type=str,
default=None,
help="checkpoint to load from; defaults to None",
)
parser.add_argument(
"--wandb",
action="store_true",
help="use wandb for logging",
default=False,
)
return parser.parse_args()
def main():
args = parse_args()
os.makedirs(args.checkpoint_dir, exist_ok=True)
if args.wandb:
wandb.init(project="rt1-pytorch", config=vars(args))
os.makedirs(args.checkpoint_dir, exist_ok=True)
print("Loading dataset...")
train_dataset = create_dataset(
datasets=args.datasets,
split=args.train_split,
trajectory_length=args.trajectory_length,
batch_size=args.train_batch_size,
num_epochs=args.epochs,
)
eval_dataset = create_dataset(
datasets=args.datasets,
split=args.eval_split,
trajectory_length=args.trajectory_length,
batch_size=args.eval_batch_size,
num_epochs=args.epochs,
)
observation_space = gym.spaces.Dict(
image=gym.spaces.Box(low=0, high=255, shape=(128, 128, 3)),
context=gym.spaces.Box(low=0.0, high=1.0, shape=(512,), dtype=np.float32),
)
action_space = gym.spaces.Dict(
world_vector=gym.spaces.Box(low=-1.0, high=1.0, shape=(3,), dtype=np.float32),
base_displacement_vertical_rotation=gym.spaces.Box(
low=-np.pi / 2.0, high=np.pi / 2.0, shape=(1,), dtype=np.float32
),
gripper_closedness_action=gym.spaces.Box(
low=-1.0, high=1.0, shape=(1,), dtype=np.float32
),
terminate_episode=gym.spaces.Discrete(3),
base_displacement_vector=gym.spaces.Box(
low=-1.0,
high=1.0,
shape=(2,),
dtype=np.float32,
),
rotation_delta=gym.spaces.Box(
low=-np.pi / 2.0, high=np.pi / 2.0, shape=(3,), dtype=np.float32
),
)
print("Building policy...")
policy = RT1Policy(
observation_space=observation_space,
action_space=action_space,
device=args.device,
checkpoint_path=args.load_checkpoint,
)
policy.model.train()
optimizer = Adam(policy.model.parameters(), lr=args.lr)
text_embedding_model = (
SentenceTransformer(args.sentence_transformer)
if args.sentence_transformer
else None
)
# Total number of params
total_params = sum(p.numel() for p in policy.model.parameters())
# Transformer params
transformer_params = sum(p.numel() for p in policy.model.transformer.parameters())
# FiLM-EfficientNet and TokenLearner params
tokenizer_params = sum(p.numel() for p in policy.model.image_tokenizer.parameters())
print(f"Total params: {total_params}")
print(f"Transformer params: {transformer_params}")
print(f"FiLM-EfficientNet+TokenLearner params: {tokenizer_params}")
def get_text_embedding(observation: Dict):
if text_embedding_model is not None:
return text_embedding_model.encode(observation["instruction"])
else:
return observation["embedding"]
print("Training...")
num_batches = 0
for batch in train_dataset:
policy.model.train()
num_batches += 1
observations = {
"image": batch["observation"]["image"],
"context": get_text_embedding(batch["observation"]),
}
actions = batch["action"]
loss = policy.loss(observations, actions)
if args.wandb:
wandb.log({"loss": loss.item()}, step=num_batches * args.train_batch_size)
else:
print(f"Train loss Batch {num_batches}: {loss.item()}")
optimizer.zero_grad()
loss.backward()
optimizer.step()
if args.eval_freq and num_batches % args.eval_freq == 0:
print("Evaluating...")
policy.model.eval()
batch = next(eval_dataset)
observations = {
"image": batch["observation"]["image"],
"context": get_text_embedding(batch["observation"]),
}
actions = batch["action"]
eval_loss = policy.loss(observations, actions)
eval_loss = eval_loss.item()
if args.wandb:
wandb.log(
{"eval_loss": eval_loss},
step=num_batches * args.train_batch_size,
)
else:
print(f"Eval loss Batch {num_batches}: {eval_loss}")
if args.checkpoint_freq and num_batches % args.checkpoint_freq == 0:
checkpoint_path = (
f"{args.checkpoint_dir}/checkpoint_"
+ f"{num_batches * args.batch_size}"
+ f"_loss_{loss.item():.3f}.pt"
)
torch.save(policy.model.state_dict(), checkpoint_path)
print(f"Saved checkpoint to {checkpoint_path}")
if __name__ == "__main__":
main()