bglick13 commited on
Commit
d6296d9
·
1 Parent(s): 0fac8a0

Update pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +30 -19
pipeline.py CHANGED
@@ -1,31 +1,37 @@
1
  import torch
2
- from diffusers import DiffusionPipeline
3
- import tqdm
4
 
 
 
5
  from diffusers.models.unet_1d import UNet1DModel
6
  from diffusers.utils.dummy_pt_objects import DDPMScheduler
7
 
8
 
9
  class ValueGuidedDiffuserPipeline(DiffusionPipeline):
10
- def __init__(self, value_function: UNet1DModel, unet: UNet1DModel, scheduler: DDPMScheduler, env):
 
 
 
 
 
 
11
  super().__init__()
12
  self.value_function = value_function
13
  self.unet = unet
14
  self.scheduler = scheduler
15
  self.env = env
16
  self.data = env.get_dataset()
 
17
  for key in self.data.keys():
18
  try:
19
  self.means[key] = self.data[key].mean()
20
- except AxisError:
21
  pass
22
  self.stds = dict()
23
  for key in self.data.keys():
24
  try:
25
  self.stds[key] = self.data[key].std()
26
- except AxisError:
27
  pass
28
- self.device = self.unet.device
29
  self.state_dim = env.observation_space.shape[0]
30
  self.action_dim = env.action_space.shape[0]
31
 
@@ -36,12 +42,11 @@ class ValueGuidedDiffuserPipeline(DiffusionPipeline):
36
  return x_in * self.stds[key] + self.means[key]
37
 
38
  def to_torch(self, x_in):
39
-
40
  if type(x_in) is dict:
41
  return {k: self.to_torch(v) for k, v in x_in.items()}
42
  elif torch.is_tensor(x_in):
43
- return x_in.to(self.device)
44
- return torch.tensor(x_in, device=self.device)
45
 
46
  def reset_x0(self, x_in, cond, act_dim):
47
  for key, val in cond.items():
@@ -53,12 +58,11 @@ class ValueGuidedDiffuserPipeline(DiffusionPipeline):
53
  y = None
54
  for i in tqdm.tqdm(self.scheduler.timesteps):
55
  # create batch of timesteps to pass into model
56
- timesteps = torch.full((batch_size,), i, device=self.device, dtype=torch.long)
57
- # 3. call the sample function
58
  for _ in range(n_guide_steps):
59
  with torch.enable_grad():
60
  x.requires_grad_()
61
- y = self.value_function(x, timesteps).sample
62
  grad = torch.autograd.grad([y.sum()], [x])[0]
63
 
64
  posterior_variance = self.scheduler._get_variance(i)
@@ -68,30 +72,37 @@ class ValueGuidedDiffuserPipeline(DiffusionPipeline):
68
  x = x.detach()
69
  x = x + scale * grad
70
  x = self.reset_x0(x, conditions, self.action_dim)
71
- # with torch.no_grad():
72
  prev_x = self.unet(x.permute(0, 2, 1), timesteps).sample.permute(0, 2, 1)
73
  x = self.scheduler.step(prev_x, i, x, predict_epsilon=False)["prev_sample"]
74
 
75
- # 4. apply conditions to the trajectory
76
  x = self.reset_x0(x, conditions, self.action_dim)
77
- x = self.to_torch(x, device=self.device)
78
- # y = network(x, timesteps).sample
79
  return x, y
80
 
81
- def __call__(self, obs, batch_size=64, planning_horizon=20, n_guide_steps=2, scale=0.1):
 
82
  obs = self.normalize(obs, "observations")
83
  obs = obs[None].repeat(batch_size, axis=0)
 
84
  conditions = {0: self.to_torch(obs)}
85
  shape = (batch_size, planning_horizon, self.state_dim + self.action_dim)
86
- x1 = torch.randn(shape, device=self.device)
 
 
87
  x = self.reset_x0(x1, conditions, self.action_dim)
88
  x = self.to_torch(x)
 
 
89
  x, y = self.run_diffusion(x, conditions, n_guide_steps, scale)
 
 
90
  sorted_idx = y.argsort(0, descending=True).squeeze()
91
  sorted_values = x[sorted_idx]
92
  actions = sorted_values[:, :, : self.action_dim]
93
  actions = actions.detach().cpu().numpy()
94
  denorm_actions = self.de_normalize(actions, key="actions")
95
- # denorm_actions = denorm_actions[np.random.randint(config['n_samples']), 0]
 
96
  denorm_actions = denorm_actions[0, 0]
97
  return denorm_actions
 
1
  import torch
 
 
2
 
3
+ import tqdm
4
+ from diffusers import DiffusionPipeline
5
  from diffusers.models.unet_1d import UNet1DModel
6
  from diffusers.utils.dummy_pt_objects import DDPMScheduler
7
 
8
 
9
  class ValueGuidedDiffuserPipeline(DiffusionPipeline):
10
+ def __init__(
11
+ self,
12
+ value_function: UNet1DModel,
13
+ unet: UNet1DModel,
14
+ scheduler: DDPMScheduler,
15
+ env,
16
+ ):
17
  super().__init__()
18
  self.value_function = value_function
19
  self.unet = unet
20
  self.scheduler = scheduler
21
  self.env = env
22
  self.data = env.get_dataset()
23
+ self.means = dict()
24
  for key in self.data.keys():
25
  try:
26
  self.means[key] = self.data[key].mean()
27
+ except:
28
  pass
29
  self.stds = dict()
30
  for key in self.data.keys():
31
  try:
32
  self.stds[key] = self.data[key].std()
33
+ except:
34
  pass
 
35
  self.state_dim = env.observation_space.shape[0]
36
  self.action_dim = env.action_space.shape[0]
37
 
 
42
  return x_in * self.stds[key] + self.means[key]
43
 
44
  def to_torch(self, x_in):
 
45
  if type(x_in) is dict:
46
  return {k: self.to_torch(v) for k, v in x_in.items()}
47
  elif torch.is_tensor(x_in):
48
+ return x_in.to(self.unet.device)
49
+ return torch.tensor(x_in, device=self.unet.device)
50
 
51
  def reset_x0(self, x_in, cond, act_dim):
52
  for key, val in cond.items():
 
58
  y = None
59
  for i in tqdm.tqdm(self.scheduler.timesteps):
60
  # create batch of timesteps to pass into model
61
+ timesteps = torch.full((batch_size,), i, device=self.unet.device, dtype=torch.long)
 
62
  for _ in range(n_guide_steps):
63
  with torch.enable_grad():
64
  x.requires_grad_()
65
+ y = self.value_function(x.permute(0, 2, 1), timesteps).sample
66
  grad = torch.autograd.grad([y.sum()], [x])[0]
67
 
68
  posterior_variance = self.scheduler._get_variance(i)
 
72
  x = x.detach()
73
  x = x + scale * grad
74
  x = self.reset_x0(x, conditions, self.action_dim)
 
75
  prev_x = self.unet(x.permute(0, 2, 1), timesteps).sample.permute(0, 2, 1)
76
  x = self.scheduler.step(prev_x, i, x, predict_epsilon=False)["prev_sample"]
77
 
78
+ # apply conditions to the trajectory
79
  x = self.reset_x0(x, conditions, self.action_dim)
80
+ x = self.to_torch(x)
 
81
  return x, y
82
 
83
+ def __call__(self, obs, batch_size=64, planning_horizon=32, n_guide_steps=2, scale=0.1):
84
+ # normalize the observations and create batch dimension
85
  obs = self.normalize(obs, "observations")
86
  obs = obs[None].repeat(batch_size, axis=0)
87
+
88
  conditions = {0: self.to_torch(obs)}
89
  shape = (batch_size, planning_horizon, self.state_dim + self.action_dim)
90
+
91
+ # generate initial noise and apply our conditions (to make the trajectories start at current state)
92
+ x1 = torch.randn(shape, device=self.unet.device)
93
  x = self.reset_x0(x1, conditions, self.action_dim)
94
  x = self.to_torch(x)
95
+
96
+ # run the diffusion process
97
  x, y = self.run_diffusion(x, conditions, n_guide_steps, scale)
98
+
99
+ # sort output trajectories by value
100
  sorted_idx = y.argsort(0, descending=True).squeeze()
101
  sorted_values = x[sorted_idx]
102
  actions = sorted_values[:, :, : self.action_dim]
103
  actions = actions.detach().cpu().numpy()
104
  denorm_actions = self.de_normalize(actions, key="actions")
105
+
106
+ # select the action with the highest value
107
  denorm_actions = denorm_actions[0, 0]
108
  return denorm_actions