Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

reinforce_baselines.py 8.0 KB

You have to be logged in to leave a comment. Sign In
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
  1. import torch
  2. import torch.nn.functional as F
  3. from torch.utils.data import Dataset
  4. from scipy.stats import ttest_rel
  5. import copy
  6. from train import rollout, get_inner_model
  7. class Baseline(object):
  8. def wrap_dataset(self, dataset):
  9. return dataset
  10. def unwrap_batch(self, batch):
  11. return batch, None
  12. def eval(self, x, c):
  13. raise NotImplementedError("Override this method")
  14. def get_learnable_parameters(self):
  15. return []
  16. def epoch_callback(self, model, epoch):
  17. pass
  18. def state_dict(self):
  19. return {}
  20. def load_state_dict(self, state_dict):
  21. pass
  22. class WarmupBaseline(Baseline):
  23. def __init__(self, baseline, n_epochs=1, warmup_exp_beta=0.8, ):
  24. super(Baseline, self).__init__()
  25. self.baseline = baseline
  26. assert n_epochs > 0, "n_epochs to warmup must be positive"
  27. self.warmup_baseline = ExponentialBaseline(warmup_exp_beta)
  28. self.alpha = 0
  29. self.n_epochs = n_epochs
  30. def wrap_dataset(self, dataset):
  31. if self.alpha > 0:
  32. return self.baseline.wrap_dataset(dataset)
  33. return self.warmup_baseline.wrap_dataset(dataset)
  34. def unwrap_batch(self, batch):
  35. if self.alpha > 0:
  36. return self.baseline.unwrap_batch(batch)
  37. return self.warmup_baseline.unwrap_batch(batch)
  38. def eval(self, x, c):
  39. if self.alpha == 1:
  40. return self.baseline.eval(x, c)
  41. if self.alpha == 0:
  42. return self.warmup_baseline.eval(x, c)
  43. v, l = self.baseline.eval(x, c)
  44. vw, lw = self.warmup_baseline.eval(x, c)
  45. # Return convex combination of baseline and of loss
  46. return self.alpha * v + (1 - self.alpha) * vw, self.alpha * l + (1 - self.alpha * lw)
  47. def epoch_callback(self, model, epoch):
  48. # Need to call epoch callback of inner model (also after first epoch if we have not used it)
  49. self.baseline.epoch_callback(model, epoch)
  50. self.alpha = (epoch + 1) / float(self.n_epochs)
  51. if epoch < self.n_epochs:
  52. print("Set warmup alpha = {}".format(self.alpha))
  53. def state_dict(self):
  54. # Checkpointing within warmup stage makes no sense, only save inner baseline
  55. return self.baseline.state_dict()
  56. def load_state_dict(self, state_dict):
  57. # Checkpointing within warmup stage makes no sense, only load inner baseline
  58. self.baseline.load_state_dict(state_dict)
  59. class NoBaseline(Baseline):
  60. def eval(self, x, c):
  61. return 0, 0 # No baseline, no loss
  62. class ExponentialBaseline(Baseline):
  63. def __init__(self, beta):
  64. super(Baseline, self).__init__()
  65. self.beta = beta
  66. self.v = None
  67. def eval(self, x, c):
  68. if self.v is None:
  69. v = c.mean()
  70. else:
  71. v = self.beta * self.v + (1. - self.beta) * c.mean()
  72. self.v = v.detach() # Detach since we never want to backprop
  73. return self.v, 0 # No loss
  74. def state_dict(self):
  75. return {
  76. 'v': self.v
  77. }
  78. def load_state_dict(self, state_dict):
  79. self.v = state_dict['v']
  80. class CriticBaseline(Baseline):
  81. def __init__(self, critic):
  82. super(Baseline, self).__init__()
  83. self.critic = critic
  84. def eval(self, x, c):
  85. v = self.critic(x)
  86. # Detach v since actor should not backprop through baseline, only for loss
  87. return v.detach(), F.mse_loss(v, c.detach())
  88. def get_learnable_parameters(self):
  89. return list(self.critic.parameters())
  90. def epoch_callback(self, model, epoch):
  91. pass
  92. def state_dict(self):
  93. return {
  94. 'critic': self.critic.state_dict()
  95. }
  96. def load_state_dict(self, state_dict):
  97. critic_state_dict = state_dict.get('critic', {})
  98. if not isinstance(critic_state_dict, dict): # backwards compatibility
  99. critic_state_dict = critic_state_dict.state_dict()
  100. self.critic.load_state_dict({**self.critic.state_dict(), **critic_state_dict})
  101. class RolloutBaseline(Baseline):
  102. def __init__(self, model, problem, opts, epoch=0):
  103. super(Baseline, self).__init__()
  104. self.problem = problem
  105. self.opts = opts
  106. self._update_model(model, epoch)
  107. def _update_model(self, model, epoch, dataset=None):
  108. self.model = copy.deepcopy(model)
  109. # Always generate baseline dataset when updating model to prevent overfitting to the baseline dataset
  110. if dataset is not None:
  111. if len(dataset) != self.opts.val_size:
  112. print("Warning: not using saved baseline dataset since val_size does not match")
  113. dataset = None
  114. elif (dataset[0] if self.problem.NAME == 'tsp' else dataset[0]['loc']).size(0) != self.opts.graph_size:
  115. print("Warning: not using saved baseline dataset since graph_size does not match")
  116. dataset = None
  117. if dataset is None:
  118. self.dataset = self.problem.make_dataset(
  119. size=self.opts.graph_size, num_samples=self.opts.val_size, distribution=self.opts.data_distribution)
  120. else:
  121. self.dataset = dataset
  122. print("Evaluating baseline model on evaluation dataset")
  123. self.bl_vals = rollout(self.model, self.dataset, self.opts).cpu().numpy()
  124. self.mean = self.bl_vals.mean()
  125. self.epoch = epoch
  126. def wrap_dataset(self, dataset):
  127. print("Evaluating baseline on dataset...")
  128. # Need to convert baseline to 2D to prevent converting to double, see
  129. # https://discuss.pytorch.org/t/dataloader-gives-double-instead-of-float/717/3
  130. return BaselineDataset(dataset, rollout(self.model, dataset, self.opts).view(-1, 1))
  131. def unwrap_batch(self, batch):
  132. return batch['data'], batch['baseline'].view(-1) # Flatten result to undo wrapping as 2D
  133. def eval(self, x, c):
  134. # Use volatile mode for efficient inference (single batch so we do not use rollout function)
  135. with torch.no_grad():
  136. v, _ = self.model(x)
  137. # There is no loss
  138. return v, 0
  139. def epoch_callback(self, model, epoch):
  140. """
  141. Challenges the current baseline with the model and replaces the baseline model if it is improved.
  142. :param model: The model to challenge the baseline by
  143. :param epoch: The current epoch
  144. """
  145. print("Evaluating candidate model on evaluation dataset")
  146. candidate_vals = rollout(model, self.dataset, self.opts).cpu().numpy()
  147. candidate_mean = candidate_vals.mean()
  148. print("Epoch {} candidate mean {}, baseline epoch {} mean {}, difference {}".format(
  149. epoch, candidate_mean, self.epoch, self.mean, candidate_mean - self.mean))
  150. if candidate_mean - self.mean < 0:
  151. # Calc p value
  152. t, p = ttest_rel(candidate_vals, self.bl_vals)
  153. p_val = p / 2 # one-sided
  154. assert t < 0, "T-statistic should be negative"
  155. print("p-value: {}".format(p_val))
  156. if p_val < self.opts.bl_alpha:
  157. print('Update baseline')
  158. self._update_model(model, epoch)
  159. def state_dict(self):
  160. return {
  161. 'model': self.model,
  162. 'dataset': self.dataset,
  163. 'epoch': self.epoch
  164. }
  165. def load_state_dict(self, state_dict):
  166. # We make it such that it works whether model was saved as data parallel or not
  167. load_model = copy.deepcopy(self.model)
  168. get_inner_model(load_model).load_state_dict(get_inner_model(state_dict['model']).state_dict())
  169. self._update_model(load_model, state_dict['epoch'], state_dict['dataset'])
  170. class BaselineDataset(Dataset):
  171. def __init__(self, dataset=None, baseline=None):
  172. super(BaselineDataset, self).__init__()
  173. self.dataset = dataset
  174. self.baseline = baseline
  175. assert (len(self.dataset) == len(self.baseline))
  176. def __getitem__(self, item):
  177. return {
  178. 'data': self.dataset[item],
  179. 'baseline': self.baseline[item]
  180. }
  181. def __len__(self):
  182. return len(self.dataset)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...