custom_torch_ppg.py 22.1 KB
Newer Older
Dipam Chakraborty's avatar
Dipam Chakraborty committed
1
2
3
4
5
6
7
8
9
10
11
from ray.rllib.policy.torch_policy import TorchPolicy
import numpy as np
from ray.rllib.utils.torch_ops import convert_to_non_torch_type, convert_to_torch_tensor
from ray.rllib.utils import try_import_torch
from ray.rllib.models import ModelCatalog
from ray.rllib.utils.annotations import override
from collections import deque
from .utils import *
import time

torch, nn = try_import_torch()
12
import torch.distributions as td
Dipam Chakraborty's avatar
Dipam Chakraborty committed
13
from torch.cuda.amp import autocast, GradScaler
Dipam Chakraborty's avatar
Dipam Chakraborty committed
14
15
16
17
18
19
20
21
22
23
24

class CustomTorchPolicy(TorchPolicy):
    """Example of a random policy
    If you are using tensorflow/pytorch to build custom policies,
    you might find `build_tf_policy` and `build_torch_policy` to
    be useful.
    Adopted from examples from https://docs.ray.io/en/master/rllib-concepts.html
    """

    def __init__(self, observation_space, action_space, config):
        self.config = config
25
26
        self.acion_space = action_space
        self.observation_space = observation_space
Dipam Chakraborty's avatar
Dipam Chakraborty committed
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

        self.device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
        dist_class, logit_dim = ModelCatalog.get_action_dist(
            action_space, self.config["model"], framework="torch")
        self.model = ModelCatalog.get_model_v2(
                        obs_space=observation_space,
                        action_space=action_space,
                        num_outputs=logit_dim,
                        model_config=self.config["model"],
                        framework="torch",
                        device=self.device,
                     )

        TorchPolicy.__init__(
            self,
            observation_space=observation_space,
            action_space=action_space,
            config=config,
            model=self.model,
            loss=None,
            action_distribution_class=dist_class,
        )
49
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
50
        self.framework = "torch"
51
52
53
54

        
    def init_training(self):
        """ Init once only for the policy - Surely there should be a bette way to do this """
Dipam Chakraborty's avatar
Dipam Chakraborty committed
55
56
57
58
59
        aux_params = set(self.model.aux_vf.parameters())
        value_params = set(self.model.value_fc.parameters())
        network_params = set(self.model.parameters())
        aux_optim_params = list(network_params - value_params)
        ppo_optim_params = list(network_params - aux_params - value_params)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
60
61
62
63
        if not self.config['single_optimizer']:
            self.optimizer = torch.optim.Adam(ppo_optim_params, lr=self.config['lr'])
        else:
            self.optimizer = torch.optim.Adam(network_params, lr=self.config['lr'])
Dipam Chakraborty's avatar
Dipam Chakraborty committed
64
65
        self.aux_optimizer = torch.optim.Adam(aux_optim_params, lr=self.config['aux_lr'])
        self.value_optimizer = torch.optim.Adam(value_params, lr=self.config['value_lr'])
Dipam Chakraborty's avatar
Dipam Chakraborty committed
66
67
68
69
70
71
72
73
74
75
76
        self.max_reward = self.config['env_config']['return_max']
        self.rewnorm = RewardNormalizer(cliprew=self.max_reward) ## TODO: Might need to go to custom state
        self.reward_deque = deque(maxlen=100)
        self.best_reward = -np.inf
        self.best_weights = None
        self.time_elapsed = 0
        self.batch_end_time = time.time()
        self.timesteps_total = 0
        self.best_rew_tsteps = 0
        
        nw = self.config['num_workers'] if self.config['num_workers'] > 0 else 1
Dipam Chakraborty's avatar
Dipam Chakraborty committed
77
78
79
80
        nenvs = nw * self.config['num_envs_per_worker']
        nsteps = self.config['rollout_fragment_length']
        n_pi = self.config['n_pi']
        self.nbatch = nenvs * nsteps
Dipam Chakraborty's avatar
Dipam Chakraborty committed
81
82
83
84
85
86
87
        self.actual_batch_size = self.nbatch // self.config['updates_per_batch']
        self.accumulate_train_batches = int(np.ceil( self.actual_batch_size / self.config['max_minibatch_size'] ))
        self.mem_limited_batch_size = self.actual_batch_size // self.accumulate_train_batches
        if self.nbatch % self.actual_batch_size != 0 or self.nbatch % self.mem_limited_batch_size != 0:
            print("#################################################")
            print("WARNING: MEMORY LIMITED BATCHING NOT SET PROPERLY")
            print("#################################################")
Dipam Chakraborty's avatar
Dipam Chakraborty committed
88
        replay_shape = (n_pi, nsteps, nenvs)
89
        self.retune_selector = RetuneSelector(nenvs, self.observation_space, self.action_space, replay_shape,
Dipam Chakraborty's avatar
Dipam Chakraborty committed
90
91
                                              skips = self.config['skips'], 
                                              n_pi = n_pi,
Dipam Chakraborty's avatar
Dipam Chakraborty committed
92
93
                                              num_retunes = self.config['num_retunes'],
                                              flat_buffer = self.config['flattened_buffer'])
94
        self.save_success = 0
Dipam Chakraborty's avatar
Dipam Chakraborty committed
95
96
        self.target_timesteps = 8_000_000
        self.buffer_time = 20 # TODO: Could try to do a median or mean time step check instead
Dipam Chakraborty's avatar
Dipam Chakraborty committed
97
        self.max_time = self.config['max_time']
Dipam Chakraborty's avatar
Dipam Chakraborty committed
98
99
100
101
        self.maxrewep_lenbuf = deque(maxlen=100)
        self.gamma = self.config['gamma']
        self.adaptive_discount_tuner = AdaptiveDiscountTuner(self.gamma, momentum=0.98, eplenmult=3)
        
102
103
        self.lr = self.config['lr']
        self.ent_coef = self.config['entropy_coeff']
Dipam Chakraborty's avatar
Dipam Chakraborty committed
104
105
        
        self.last_dones = np.zeros((nw * self.config['num_envs_per_worker'],))
106
        self.make_distr = dist_build(self.action_space)
107
        self.retunes_completed = 0
Dipam Chakraborty's avatar
Dipam Chakraborty committed
108
        self.amp_scaler = GradScaler()
Dipam Chakraborty's avatar
Dipam Chakraborty committed
109
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
110
111
        self.update_lr()
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
112
113
    def to_tensor(self, arr):
        return torch.from_numpy(arr).to(self.device)
114
115
116
117
    
    @override(TorchPolicy)
    def extra_action_out(self, input_dict, state_batches, model, action_dist):
        return {'values': model._value.tolist()}
Dipam Chakraborty's avatar
Dipam Chakraborty committed
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
        
    @override(TorchPolicy)
    def learn_on_batch(self, samples):
        """Fused compute gradients and apply gradients call.
        Either this or the combination of compute/apply grads must be
        implemented by subclasses.
        Returns:
            grad_info: dictionary of extra metadata from compute_gradients().
        Examples:
            >>> batch = ev.sample()
            >>> ev.learn_on_batch(samples)
        Reference: https://github.com/ray-project/ray/blob/master/rllib/policy/policy.py#L279-L316
        """
        ## Config data values
        nbatch = self.nbatch
        nbatch_train = self.mem_limited_batch_size 
        gamma, lam = self.gamma, self.config['lambda']
        nsteps = self.config['rollout_fragment_length']
        nenvs = nbatch//nsteps
        ts = (nenvs, nsteps)
        mb_dones = unroll(samples['dones'], ts)
        
        ## Reward Normalization - No reward norm works well for many envs
        if self.config['standardize_rewards']:
            mb_origrewards = unroll(samples['rewards'], ts)
            mb_rewards =  np.zeros_like(mb_origrewards)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
144
            mb_rewards[0] = self.rewnorm.normalize(mb_origrewards[0], self.last_dones, self.config["reset_returns"])
Dipam Chakraborty's avatar
Dipam Chakraborty committed
145
            for ii in range(1, nsteps):
Dipam Chakraborty's avatar
Dipam Chakraborty committed
146
                mb_rewards[ii] = self.rewnorm.normalize(mb_origrewards[ii], mb_dones[ii-1], self.config["reset_returns"])
Dipam Chakraborty's avatar
Dipam Chakraborty committed
147
148
149
            self.last_dones = mb_dones[-1]
        else:
            mb_rewards = unroll(samples['rewards'], ts)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
150
       
151
        # Weird hack that helps in many envs (Yes keep it after reward normalization)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
152
153
154
        rew_scale = self.config["scale_reward"]
        if rew_scale != 1.0:
            mb_rewards *= rew_scale
Dipam Chakraborty's avatar
Dipam Chakraborty committed
155
156
157
158
159
160
161
162
163
164
165
        
        should_skip_train_step = self.best_reward_model_select(samples)
        if should_skip_train_step:
            self.update_batch_time()
            return {} # Not doing last optimization step - This is intentional due to noisy gradients
          
        obs = samples['obs']

        ## Value prediction
        next_obs = unroll(samples['new_obs'], ts)[-1]
        last_values, _ = self.model.vf_pi(next_obs, ret_numpy=True, no_grad=True, to_torch=True)
166
        values = samples['values']
Dipam Chakraborty's avatar
Dipam Chakraborty committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
        
        ## GAE
        mb_values = unroll(values, ts)
        mb_returns = np.zeros_like(mb_rewards)
        mb_advs = np.zeros_like(mb_rewards)
        lastgaelam = 0
        for t in reversed(range(nsteps)):
            if t == nsteps - 1:
                nextvalues = last_values
            else:
                nextvalues = mb_values[t+1]
            nextnonterminal = 1.0 - mb_dones[t]
            delta = mb_rewards[t] + gamma * nextvalues * nextnonterminal - mb_values[t]
            mb_advs[t] = lastgaelam = delta + gamma * lam * nextnonterminal * lastgaelam
        mb_returns = mb_advs + mb_values
        
        ## Data from config
        cliprange, vfcliprange = self.config['clip_param'], self.config['vf_clip_param']
        max_grad_norm = self.config['grad_clip']
        ent_coef, vf_coef = self.ent_coef, self.config['vf_loss_coeff']
        
188
        logp_actions = samples['action_logp'] ## np.isclose seems to be True always, otherwise compute again if needed
Dipam Chakraborty's avatar
Dipam Chakraborty committed
189
190
191
192
        noptepochs = self.config['num_sgd_iter']
        actions = samples['actions']
        returns = roll(mb_returns)
        
193
194
195
        advs = returns - values
        normalized_advs = (advs - np.mean(advs)) / (np.std(advs) + 1e-8) 
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
196
197
198
199
200
201
202
203
        ## Train multiple epochs
        optim_count = 0
        inds = np.arange(nbatch)
        for _ in range(noptepochs):
            np.random.shuffle(inds)
            for start in range(0, nbatch, nbatch_train):
                end = start + nbatch_train
                mbinds = inds[start:end]
204
                slices = (self.to_tensor(arr[mbinds]) for arr in (obs, returns, actions, values, logp_actions, normalized_advs))
Dipam Chakraborty's avatar
Dipam Chakraborty committed
205
206
207
                optim_count += 1
                apply_grad = (optim_count % self.accumulate_train_batches) == 0
                self._batch_train(apply_grad, self.accumulate_train_batches,
Dipam Chakraborty's avatar
Dipam Chakraborty committed
208
                                  cliprange, vfcliprange, max_grad_norm, ent_coef, vf_coef, *slices)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
209
                
Dipam Chakraborty's avatar
Dipam Chakraborty committed
210
        ## Distill with aux head
Dipam Chakraborty's avatar
Dipam Chakraborty committed
211
        should_retune = self.retune_selector.update(unroll(obs, ts), mb_returns)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
212
213
214
        if should_retune:
            self.aux_train()
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
215
216
217
218
219
220
221
222
223
224
225
226
        self.update_gamma(samples)
        self.update_lr()
        self.update_ent_coef()
            
        self.update_batch_time()
        return {}
    
    def update_batch_time(self):
        self.time_elapsed += time.time() - self.batch_end_time
        self.batch_end_time = time.time()
        
    def _batch_train(self, apply_grad, num_accumulate, 
Dipam Chakraborty's avatar
Dipam Chakraborty committed
227
                     cliprange, vfcliprange, max_grad_norm,
Dipam Chakraborty's avatar
Dipam Chakraborty committed
228
                     ent_coef, vf_coef,
229
                     obs, returns, actions, values, logp_actions_old, advs):
Dipam Chakraborty's avatar
Dipam Chakraborty committed
230
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
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
        if not self.config['pi_phase_mixed_precision']:
            loss, vf_loss = self._calc_pi_vf_loss(apply_grad, num_accumulate, 
                                                 cliprange, vfcliprange, max_grad_norm,
                                                 ent_coef, vf_coef,
                                                 obs, returns, actions, values, logp_actions_old, advs)

            loss.backward()
            vf_loss.backward()
            if apply_grad:
                self.optimizer.step()
                self.optimizer.zero_grad()
                if not self.config['single_optimizer']:
                    self.value_optimizer.step()
                    self.value_optimizer.zero_grad()
        else:
            with autocast():
                loss, vf_loss = self._calc_pi_vf_loss(apply_grad, num_accumulate, 
                                                 cliprange, vfcliprange, max_grad_norm,
                                                 ent_coef, vf_coef,
                                                 obs, returns, actions, values, logp_actions_old, advs)
                
            self.amp_scaler.scale(loss).backward(retain_graph=True)
            self.amp_scaler.scale(vf_loss).backward()
            
            if apply_grad:
                self.amp_scaler.step(self.optimizer)
                if not self.config['single_optimizer']:
                    self.amp_scaler.step(self.value_optimizer)
                self.amp_scaler.update()
                
                self.optimizer.zero_grad()
                if not self.config['single_optimizer']:
                    self.value_optimizer.zero_grad()



    
    def _calc_pi_vf_loss(self, apply_grad, num_accumulate, 
                         cliprange, vfcliprange, max_grad_norm,
                         ent_coef, vf_coef,
                         obs, returns, actions, values, logp_actions_old, advs):
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
273
        vpred, pi_logits = self.model.vf_pi(obs, ret_numpy=False, no_grad=False, to_torch=False)
274
        pd = self.make_distr(pi_logits)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
275
        logp_actions = pd.log_prob(actions[...,None]).squeeze(1)
276
        entropy = torch.mean(pd.entropy())
Dipam Chakraborty's avatar
Dipam Chakraborty committed
277

Dipam Chakraborty's avatar
Dipam Chakraborty committed
278
        vf_loss = .5 * torch.mean(torch.pow((vpred - returns), 2)) * vf_coef
Dipam Chakraborty's avatar
Dipam Chakraborty committed
279

280
        ratio = torch.exp(logp_actions - logp_actions_old)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
281
282
283
284
        pg_losses1 = -advs * ratio
        pg_losses2 = -advs * torch.clamp(ratio, 1-cliprange, 1+cliprange)
        pg_loss = torch.mean(torch.max(pg_losses1, pg_losses2))

Dipam Chakraborty's avatar
Dipam Chakraborty committed
285
        loss = pg_loss - entropy * ent_coef
Dipam Chakraborty's avatar
Dipam Chakraborty committed
286
287
        
        loss = loss / num_accumulate
Dipam Chakraborty's avatar
Dipam Chakraborty committed
288
        vf_loss = vf_loss / num_accumulate
Dipam Chakraborty's avatar
Dipam Chakraborty committed
289
290
        return loss, vf_loss
    
Dipam Chakraborty's avatar
Dipam Chakraborty committed
291
    def aux_train(self):
Dipam Chakraborty's avatar
Dipam Chakraborty committed
292
293
        nbatch_train = self.mem_limited_batch_size 
        retune_epochs = self.config['retune_epochs']
Dipam Chakraborty's avatar
Dipam Chakraborty committed
294
        replay_shape = self.retune_selector.vtarg_replay.shape
Dipam Chakraborty's avatar
Dipam Chakraborty committed
295
        replay_pi = np.empty((*replay_shape, self.retune_selector.ac_space.n), dtype=np.float32)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
296

Dipam Chakraborty's avatar
Dipam Chakraborty committed
297
298
        for nnpi in range(self.retune_selector.n_pi):
            for ne in range(self.retune_selector.nenvs):
Dipam Chakraborty's avatar
Dipam Chakraborty committed
299
                _, replay_pi[nnpi, :, ne] = self.model.vf_pi(self.retune_selector.exp_replay[nnpi, :, ne], 
Dipam Chakraborty's avatar
Dipam Chakraborty committed
300
                                                             ret_numpy=True, no_grad=True, to_torch=True)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
301
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
302
        # Tune vf and pi heads to older predictions with (augmented?) observations
Dipam Chakraborty's avatar
Dipam Chakraborty committed
303
304
        num_accumulate = self.config['aux_num_accumulates']
        num_rollouts = self.config['aux_mbsize']
Dipam Chakraborty's avatar
Dipam Chakraborty committed
305
        for ep in range(retune_epochs):
Dipam Chakraborty's avatar
Dipam Chakraborty committed
306
            counter = 0
Dipam Chakraborty's avatar
Dipam Chakraborty committed
307
            for slices in self.retune_selector.make_minibatches(replay_pi, num_rollouts):
Dipam Chakraborty's avatar
Dipam Chakraborty committed
308
                counter += 1
Dipam Chakraborty's avatar
Dipam Chakraborty committed
309
                apply_grad = (counter % num_accumulate) == 0
Dipam Chakraborty's avatar
Dipam Chakraborty committed
310
                self.tune_policy(slices[0], self.to_tensor(slices[1]), self.to_tensor(slices[2]), 
Dipam Chakraborty's avatar
Dipam Chakraborty committed
311
                                 apply_grad, num_accumulate)
312
        self.retunes_completed += 1
Dipam Chakraborty's avatar
Dipam Chakraborty committed
313
314
        self.retune_selector.retune_done()
 
Dipam Chakraborty's avatar
Dipam Chakraborty committed
315
    def tune_policy(self, obs, target_vf, target_pi, apply_grad, num_accumulate):
Dipam Chakraborty's avatar
Dipam Chakraborty committed
316
317
        if self.config['augment_buffer']:
            obs_aug = np.empty(obs.shape, obs.dtype)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
318
            aug_idx = np.random.randint(self.config['augment_randint_num'], size=len(obs))
Dipam Chakraborty's avatar
Dipam Chakraborty committed
319
320
321
322
323
324
            obs_aug[aug_idx == 0] = pad_and_random_crop(obs[aug_idx == 0], 64, 10)
            obs_aug[aug_idx == 1] = random_cutout_color(obs[aug_idx == 1], 10, 30)
            obs_aug[aug_idx >= 2] = obs[aug_idx >= 2]
            obs_in = self.to_tensor(obs_aug)
        else:
            obs_in = self.to_tensor(obs)
325
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
326
        if not self.config['aux_phase_mixed_precision']:
Dipam Chakraborty's avatar
Dipam Chakraborty committed
327
            loss, vf_loss = self._aux_calc_loss(obs_in, target_vf, target_pi, num_accumulate)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
328
329
            loss.backward()
            vf_loss.backward()
Dipam Chakraborty's avatar
Dipam Chakraborty committed
330
331
332
333
334
335
336
            
            if apply_grad:
                if not self.config['single_optimizer']:
                    self.aux_optimizer.step()
                    self.value_optimizer.step()
                else:
                    self.optimizer.step()
Dipam Chakraborty's avatar
Dipam Chakraborty committed
337
                
Dipam Chakraborty's avatar
Dipam Chakraborty committed
338
339
340
            
        else:
            with autocast():
Dipam Chakraborty's avatar
Dipam Chakraborty committed
341
                loss, vf_loss = self._aux_calc_loss(obs_in, target_vf, target_pi, num_accumulate)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
342
343
344
            
            self.amp_scaler.scale(loss).backward(retain_graph=True)
            self.amp_scaler.scale(vf_loss).backward()
Dipam Chakraborty's avatar
Dipam Chakraborty committed
345
346
347
348
349
350
351
            
            if apply_grad:
                if not self.config['single_optimizer']:
                    self.amp_scaler.step(self.aux_optimizer)
                    self.amp_scaler.step(self.value_optimizer)
                else:
                    self.amp_scaler.step(self.optimizer)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
352

Dipam Chakraborty's avatar
Dipam Chakraborty committed
353
354
355
                self.amp_scaler.update()
         
        if apply_grad:
Dipam Chakraborty's avatar
Dipam Chakraborty committed
356
            if not self.config['single_optimizer']:
Dipam Chakraborty's avatar
Dipam Chakraborty committed
357
358
                self.aux_optimizer.zero_grad()
                self.value_optimizer.zero_grad()
Dipam Chakraborty's avatar
Dipam Chakraborty committed
359
            else:
Dipam Chakraborty's avatar
Dipam Chakraborty committed
360
                self.optimizer.zero_grad()
Dipam Chakraborty's avatar
Dipam Chakraborty committed
361
            
Dipam Chakraborty's avatar
Dipam Chakraborty committed
362
    def _aux_calc_loss(self, obs_in, target_vf, target_pi, num_accumulate):
Dipam Chakraborty's avatar
Dipam Chakraborty committed
363
        vpred, pi_logits = self.model.vf_pi(obs_in, ret_numpy=False, no_grad=False, to_torch=False)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
364
365
        aux_vpred = self.model.aux_value_function()
        aux_loss = .5 * torch.mean(torch.pow(aux_vpred - target_vf, 2))
Dipam Chakraborty's avatar
Dipam Chakraborty committed
366

367
368
369
        target_pd = self.make_distr(target_pi)
        pd = self.make_distr(pi_logits)
        pi_loss = td.kl_divergence(target_pd, pd).mean()
Dipam Chakraborty's avatar
Dipam Chakraborty committed
370

Dipam Chakraborty's avatar
Dipam Chakraborty committed
371
372
        loss = pi_loss + aux_loss
        vf_loss = .5 * torch.mean(torch.pow(vpred - target_vf, 2))
Dipam Chakraborty's avatar
Dipam Chakraborty committed
373
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
374
375
376
        loss = loss / num_accumulate
        vf_loss = vf_loss / num_accumulate
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
377
        return loss, vf_loss
Dipam Chakraborty's avatar
Dipam Chakraborty committed
378
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
379
    def best_reward_model_select(self, samples):
380
        self.timesteps_total += len(samples['dones'])
Dipam Chakraborty's avatar
Dipam Chakraborty committed
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
        
        ## Best reward model selection
        eprews = [info['episode']['r'] for info in samples['infos'] if 'episode' in info]
        self.reward_deque.extend(eprews)
        mean_reward = safe_mean(eprews) if len(eprews) >= 100 else safe_mean(self.reward_deque)
        if self.best_reward < mean_reward:
            self.best_reward = mean_reward
            self.best_weights = self.get_weights()["current_weights"]
            self.best_rew_tsteps = self.timesteps_total
           
        if self.timesteps_total > self.target_timesteps or (self.time_elapsed + self.buffer_time) > self.max_time:
            if self.best_weights is not None:
                self.set_model_weights(self.best_weights)
                return True
            
        return False
    
    def update_lr(self):
        if self.config['lr_schedule'] == 'linear':
            self.lr = linear_schedule(initial_val=self.config['lr'],
                                      final_val=self.config['final_lr'],
                                      current_steps=self.timesteps_total,
                                      total_steps=self.target_timesteps)
            
        elif self.config['lr_schedule'] == 'exponential':
            self.lr = 0.997 * self.lr 
Dipam Chakraborty's avatar
Dipam Chakraborty committed
407
408
409
410
411
412
413
414
        
        for g in self.optimizer.param_groups:
            g['lr'] = self.lr
        if self.config['same_lr_everywhere']:
            for g in self.value_optimizer.param_groups:
                g['lr'] = self.lr
            for g in self.aux_optimizer.param_groups:
                g['lr'] = self.lr
Dipam Chakraborty's avatar
Dipam Chakraborty committed
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

    
    def update_ent_coef(self):
        if self.config['entropy_schedule']:
            self.ent_coef = linear_schedule(initial_val=self.config['entropy_coeff'], 
                                            final_val=self.config['final_entropy_coeff'], 
                                            current_steps=self.timesteps_total, 
                                            total_steps=self.target_timesteps)
    
    def update_gamma(self, samples):
        if self.config['adaptive_gamma']:
            epinfobuf = [info['episode'] for info in samples['infos'] if 'episode' in info]
            self.maxrewep_lenbuf.extend([epinfo['l'] for epinfo in epinfobuf if epinfo['r'] >= self.max_reward])
            sorted_nth = lambda buf, n: np.nan if len(buf) < 100 else sorted(self.maxrewep_lenbuf.copy())[n]
            target_horizon = sorted_nth(self.maxrewep_lenbuf, 80)
            self.gamma = self.adaptive_discount_tuner.update(target_horizon)

        
    def get_custom_state_vars(self):
        return {
            "time_elapsed": self.time_elapsed,
            "timesteps_total": self.timesteps_total,
            "best_weights": self.best_weights,
            "reward_deque": self.reward_deque,
            "batch_end_time": self.batch_end_time,
            "gamma": self.gamma,
            "maxrewep_lenbuf": self.maxrewep_lenbuf,
            "lr": self.lr,
            "ent_coef": self.ent_coef,
            "rewnorm": self.rewnorm,
            "best_rew_tsteps": self.best_rew_tsteps,
            "best_reward": self.best_reward,
            "last_dones": self.last_dones,
448
            "retunes_completed": self.retunes_completed,
Dipam Chakraborty's avatar
Dipam Chakraborty committed
449
450
451
452
453
454
455
456
457
458
        }
    
    def set_custom_state_vars(self, custom_state_vars):
        self.time_elapsed = custom_state_vars["time_elapsed"]
        self.timesteps_total = custom_state_vars["timesteps_total"]
        self.best_weights = custom_state_vars["best_weights"]
        self.reward_deque = custom_state_vars["reward_deque"]
        self.batch_end_time = custom_state_vars["batch_end_time"]
        self.gamma = self.adaptive_discount_tuner.gamma = custom_state_vars["gamma"]
        self.maxrewep_lenbuf = custom_state_vars["maxrewep_lenbuf"]
459
        self.lr = custom_state_vars["lr"]
Dipam Chakraborty's avatar
Dipam Chakraborty committed
460
461
462
463
464
        self.ent_coef = custom_state_vars["ent_coef"]
        self.rewnorm = custom_state_vars["rewnorm"]
        self.best_rew_tsteps = custom_state_vars["best_rew_tsteps"]
        self.best_reward = custom_state_vars["best_reward"]
        self.last_dones = custom_state_vars["last_dones"]
465
        self.retunes_completed = custom_state_vars["retunes_completed"]
Dipam Chakraborty's avatar
Dipam Chakraborty committed
466
467
468
469
470
471
472
473
474
475
476
477
478
479
    
    @override(TorchPolicy)
    def get_weights(self):
        weights = {}
        weights["current_weights"] = {
            k: v.cpu().detach().numpy()
            for k, v in self.model.state_dict().items()
        }
        return weights
    
    @override(TorchPolicy)
    def set_weights(self, weights):
        self.set_model_weights(weights["current_weights"])
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
480
    def set_optimizer_state(self, optimizer_state, aux_optimizer_state, value_optimizer_state, amp_scaler_state):
Dipam Chakraborty's avatar
Dipam Chakraborty committed
481
482
483
        optimizer_state = convert_to_torch_tensor(optimizer_state, device=self.device)
        self.optimizer.load_state_dict(optimizer_state)
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
484
485
486
        aux_optimizer_state = convert_to_torch_tensor(aux_optimizer_state, device=self.device)
        self.aux_optimizer.load_state_dict(aux_optimizer_state)
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
487
488
        value_optimizer_state = convert_to_torch_tensor(value_optimizer_state, device=self.device)
        self.value_optimizer.load_state_dict(value_optimizer_state)
Dipam Chakraborty's avatar
Dipam Chakraborty committed
489
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
490
491
492
        amp_scaler_state = convert_to_torch_tensor(amp_scaler_state, device=self.device)
        self.amp_scaler.load_state_dict(amp_scaler_state)
        
Dipam Chakraborty's avatar
Dipam Chakraborty committed
493
494
495
    def set_model_weights(self, model_weights):
        model_weights = convert_to_torch_tensor(model_weights, device=self.device)
        self.model.load_state_dict(model_weights)