TD3 class

A collection of functions that define the Twin Delayed Deep Deterministic Policy Gradient agent (TD3), ref: https://arxiv.org/pdf/1802.09477.pdf

Source code in qdax/baselines/td3.py
 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
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
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
407
408
409
410
411
412
413
414
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
448
449
450
451
452
453
454
class TD3:
    """
    A collection of functions that define the Twin Delayed Deep Deterministic Policy
    Gradient agent (TD3), ref: https://arxiv.org/pdf/1802.09477.pdf
    """

    def __init__(self, config: TD3Config, action_size: int):
        self._config = config

        (
            self._policy,
            self._critic,
        ) = make_td3_networks(
            action_size=action_size,
            critic_hidden_layer_sizes=self._config.critic_hidden_layer_size,
            policy_hidden_layer_sizes=self._config.policy_hidden_layer_size,
        )

    def init(
        self, key: RNGKey, action_size: int, observation_size: int
    ) -> TD3TrainingState:
        """Initialise the training state of the TD3 algorithm, through creation
        of optimizer states and params.

        Args:
            key: a random key used for random operations.
            action_size: the size of the action array needed to interact with the
                environment.
            observation_size: the size of the observation array retrieved from the
                environment.

        Returns:
            the initial training state.
        """

        # Initialize critics and policy params
        fake_obs = jnp.zeros(shape=(observation_size,))
        fake_action = jnp.zeros(shape=(action_size,))
        key, subkey_1, subkey_2 = jax.random.split(key, num=3)
        critic_params = self._critic.init(subkey_1, obs=fake_obs, actions=fake_action)
        policy_params = self._policy.init(subkey_2, fake_obs)

        # Initialize target networks
        target_critic_params = jax.tree.map(
            lambda x: jnp.asarray(x.copy()), critic_params
        )
        target_policy_params = jax.tree.map(
            lambda x: jnp.asarray(x.copy()), policy_params
        )

        # Create and initialize optimizers
        critic_optimizer_state = optax.adam(learning_rate=1.0).init(critic_params)
        policy_optimizer_state = optax.adam(learning_rate=1.0).init(policy_params)

        # Initial training state
        training_state = TD3TrainingState(
            policy_optimizer_state=policy_optimizer_state,
            policy_params=policy_params,
            critic_optimizer_state=critic_optimizer_state,
            critic_params=critic_params,
            target_policy_params=target_policy_params,
            target_critic_params=target_critic_params,
            key=key,
            steps=jnp.array(0),
        )

        return training_state

    def select_action(
        self,
        obs: Observation,
        policy_params: Params,
        key: RNGKey,
        expl_noise: float,
        deterministic: bool = False,
    ) -> Action:
        """Selects an action according to TD3 policy. The action can be deterministic
        or stochastic by adding exploration noise.

        Args:
            obs: agent observation(s)
            policy_params: parameters of the agent's policy
            key: jax random key
            expl_noise: exploration noise
            deterministic: whether to select action in a deterministic way.
                Defaults to False.

        Returns:
            an action and an updated training state.
        """

        actions = self._policy.apply(policy_params, obs)
        if not deterministic:
            noise = jax.random.normal(key, actions.shape) * expl_noise
            actions = actions + noise
            actions = jnp.clip(actions, -1.0, 1.0)
        return actions

    def play_step_fn(
        self,
        env_state: EnvState,
        training_state: TD3TrainingState,
        env: Env,
        deterministic: bool = False,
    ) -> Tuple[EnvState, TD3TrainingState, Transition]:
        """Plays a step in the environment. Selects an action according to TD3 rule and
        performs the environment step.

        Args:
            env_state: the current environment state
            training_state: the SAC training state
            env: the environment
            deterministic: whether to select action in a deterministic way.
                Defaults to False.

        Returns:
            the new environment state
            the new TD3 training state
            the played transition
        """
        key = training_state.key

        key, subkey = jax.random.split(key)
        actions = self.select_action(
            obs=env_state.obs,
            policy_params=training_state.policy_params,
            key=subkey,
            expl_noise=self._config.expl_noise,
            deterministic=deterministic,
        )
        training_state = training_state.replace(
            key=key,
        )
        next_env_state = env.step(env_state, actions)
        transition = Transition(
            obs=env_state.obs,
            next_obs=next_env_state.obs,
            rewards=next_env_state.reward,
            dones=next_env_state.done,
            truncations=next_env_state.info["truncation"],
            actions=actions,
        )
        return next_env_state, training_state, transition

    def play_qd_step_fn(
        self,
        env_state: EnvState,
        training_state: TD3TrainingState,
        env: Env,
        deterministic: bool = False,
    ) -> Tuple[EnvState, TD3TrainingState, QDTransition]:
        """Plays a step in the environment. Selects an action according to TD3 rule and
        performs the environment step.

        Args:
            env_state: the current environment state
            training_state: the TD3 training state
            env: the environment
            deterministic: the whether to select action in a deterministic way.
                Defaults to False.

        Returns:
            the new environment state
            the new TD3 training state
            the played transition
        """
        next_env_state, training_state, transition = self.play_step_fn(
            env_state, training_state, env, deterministic
        )
        actions = transition.actions

        truncations = next_env_state.info["truncation"]
        transition = QDTransition(
            obs=env_state.obs,
            next_obs=next_env_state.obs,
            rewards=next_env_state.reward,
            dones=next_env_state.done,
            actions=actions,
            truncations=truncations,
            state_desc=env_state.info["state_descriptor"],
            next_state_desc=next_env_state.info["state_descriptor"],
        )

        return (
            next_env_state,
            training_state,
            transition,
        )

    def eval_policy_fn(
        self,
        training_state: TD3TrainingState,
        eval_env_first_state: EnvState,
        play_step_fn: Callable[
            [EnvState, Params],
            Tuple[EnvState, Params, Transition],
        ],
    ) -> Tuple[Reward, Reward]:
        """Evaluates the agent's policy over an entire episode, across all batched
        environments.

        Args:
            training_state: TD3 training state.
            eval_env_first_state: the first state of the environment.
            play_step_fn: function defining how to play a step in the env.

        Returns:
            true return averaged over batch dimension, shape: (1,)
            true return per env, shape: (env_batch_size,)
        """
        # TODO: this generate unroll shouldn't take a random key
        state, training_state, transitions = generate_unroll(
            init_state=eval_env_first_state,
            training_state=training_state,
            episode_length=self._config.episode_length,
            play_step_fn=play_step_fn,
        )

        transitions = get_first_episode(transitions)

        true_returns = jnp.nansum(transitions.rewards, axis=0)
        true_return = jnp.mean(true_returns, axis=-1)

        return true_return, true_returns

    def eval_qd_policy_fn(
        self,
        training_state: TD3TrainingState,
        eval_env_first_state: EnvState,
        play_step_fn: Callable[
            [EnvState, Params],
            Tuple[EnvState, TD3TrainingState, QDTransition],
        ],
        descriptor_extraction_fn: Callable[[QDTransition, Mask], Descriptor],
    ) -> Tuple[Reward, Descriptor, Reward, Descriptor]:
        """Evaluates the agent's policy over an entire episode, across all batched
        environments for QD environments. Averaged descriptors are returned as well.


        Args:
            training_state: the SAC training state
            eval_env_first_state: the initial state for evaluation
            play_step_fn: the play_step function used to collect the evaluation episode

        Returns:
            the true return averaged over batch dimension, shape: (1,)
            the descriptor averaged over batch dimension, shape: (num_descriptors,)
            the true return per environment, shape: (env_batch_size,)
            the descriptor per environment, shape: (env_batch_size, num_descriptors)

        """

        state, training_state, transitions = generate_unroll(
            init_state=eval_env_first_state,
            training_state=training_state,
            episode_length=self._config.episode_length,
            play_step_fn=play_step_fn,
        )
        transitions = get_first_episode(transitions)
        true_returns = jnp.nansum(transitions.rewards, axis=0)
        true_return = jnp.mean(true_returns, axis=-1)

        transitions = jax.tree.map(lambda x: jnp.swapaxes(x, 0, 1), transitions)
        masks = jnp.isnan(transitions.rewards)
        descriptors = descriptor_extraction_fn(transitions, masks)

        mean_descriptor = jnp.mean(descriptors, axis=0)
        return true_return, mean_descriptor, true_returns, descriptors

    def update(
        self,
        training_state: TD3TrainingState,
        replay_buffer: ReplayBuffer,
    ) -> Tuple[TD3TrainingState, ReplayBuffer, Metrics]:
        """Performs a single training step: updates policy params and critic params
        through gradient descent.

        Args:
            training_state: the current training state, containing the optimizer states
                and the params of the policy and critic.
            replay_buffer: the replay buffer, filled with transitions experienced in
                the environment.

        Returns:
            A new training state, the buffer with new transitions and metrics about the
            training process.
        """

        # Sample a batch of transitions in the buffer
        key = training_state.key

        key, subkey = jax.random.split(key)
        samples = replay_buffer.sample(subkey, sample_size=self._config.batch_size)

        # Update Critic
        key, subkey = jax.random.split(key)
        critic_loss, critic_gradient = jax.value_and_grad(td3_critic_loss_fn)(
            training_state.critic_params,
            target_policy_params=training_state.target_policy_params,
            target_critic_params=training_state.target_critic_params,
            policy_fn=self._policy.apply,
            critic_fn=self._critic.apply,
            policy_noise=self._config.policy_noise,
            noise_clip=self._config.noise_clip,
            reward_scaling=self._config.reward_scaling,
            discount=self._config.discount,
            transitions=samples,
            key=subkey,
        )
        critic_optimizer = optax.adam(learning_rate=self._config.critic_learning_rate)
        critic_updates, critic_optimizer_state = critic_optimizer.update(
            critic_gradient, training_state.critic_optimizer_state
        )
        critic_params = optax.apply_updates(
            training_state.critic_params, critic_updates
        )
        # Soft update of target critic network
        target_critic_params = jax.tree.map(
            lambda x1, x2: (1.0 - self._config.soft_tau_update) * x1
            + self._config.soft_tau_update * x2,
            training_state.target_critic_params,
            critic_params,
        )

        # Update policy
        policy_loss, policy_gradient = jax.value_and_grad(td3_policy_loss_fn)(
            training_state.policy_params,
            critic_params=training_state.critic_params,
            policy_fn=self._policy.apply,
            critic_fn=self._critic.apply,
            transitions=samples,
        )

        def update_policy_step() -> Tuple[Params, Params, optax.OptState]:
            policy_optimizer = optax.adam(
                learning_rate=self._config.policy_learning_rate
            )
            (
                policy_updates,
                policy_optimizer_state,
            ) = policy_optimizer.update(
                policy_gradient, training_state.policy_optimizer_state
            )
            policy_params = optax.apply_updates(
                training_state.policy_params, policy_updates
            )
            # Soft update of target policy
            target_policy_params = jax.tree.map(
                lambda x1, x2: (1.0 - self._config.soft_tau_update) * x1
                + self._config.soft_tau_update * x2,
                training_state.target_policy_params,
                policy_params,
            )
            return policy_params, target_policy_params, policy_optimizer_state

        # Delayed update
        current_policy_state = (
            training_state.policy_params,
            training_state.target_policy_params,
            training_state.policy_optimizer_state,
        )
        policy_params, target_policy_params, policy_optimizer_state = jax.lax.cond(
            training_state.steps % self._config.policy_delay == 0,
            lambda _: update_policy_step(),
            lambda _: current_policy_state,
            operand=None,
        )

        # Create new training state
        new_training_state = training_state.replace(
            critic_params=critic_params,
            critic_optimizer_state=critic_optimizer_state,
            policy_params=policy_params,
            policy_optimizer_state=policy_optimizer_state,
            target_critic_params=target_critic_params,
            target_policy_params=target_policy_params,
            key=key,
            steps=training_state.steps + 1,
        )

        metrics = {
            "actor_loss": policy_loss,
            "critic_loss": critic_loss,
        }

        return new_training_state, replay_buffer, metrics

eval_policy_fn(training_state, eval_env_first_state, play_step_fn)

Evaluates the agent's policy over an entire episode, across all batched environments.

Parameters:
  • training_state (TD3TrainingState) –

    TD3 training state.

  • eval_env_first_state (State) –

    the first state of the environment.

  • play_step_fn (Callable[[State, Params], Tuple[State, Params, Transition]]) –

    function defining how to play a step in the env.

Returns:
  • Reward

    true return averaged over batch dimension, shape: (1,)

  • Reward

    true return per env, shape: (env_batch_size,)

Source code in qdax/baselines/td3.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def eval_policy_fn(
    self,
    training_state: TD3TrainingState,
    eval_env_first_state: EnvState,
    play_step_fn: Callable[
        [EnvState, Params],
        Tuple[EnvState, Params, Transition],
    ],
) -> Tuple[Reward, Reward]:
    """Evaluates the agent's policy over an entire episode, across all batched
    environments.

    Args:
        training_state: TD3 training state.
        eval_env_first_state: the first state of the environment.
        play_step_fn: function defining how to play a step in the env.

    Returns:
        true return averaged over batch dimension, shape: (1,)
        true return per env, shape: (env_batch_size,)
    """
    # TODO: this generate unroll shouldn't take a random key
    state, training_state, transitions = generate_unroll(
        init_state=eval_env_first_state,
        training_state=training_state,
        episode_length=self._config.episode_length,
        play_step_fn=play_step_fn,
    )

    transitions = get_first_episode(transitions)

    true_returns = jnp.nansum(transitions.rewards, axis=0)
    true_return = jnp.mean(true_returns, axis=-1)

    return true_return, true_returns

eval_qd_policy_fn(training_state, eval_env_first_state, play_step_fn, descriptor_extraction_fn)

Evaluates the agent's policy over an entire episode, across all batched environments for QD environments. Averaged descriptors are returned as well.

Parameters:
  • training_state (TD3TrainingState) –

    the SAC training state

  • eval_env_first_state (State) –

    the initial state for evaluation

  • play_step_fn (Callable[[State, Params], Tuple[State, TD3TrainingState, QDTransition]]) –

    the play_step function used to collect the evaluation episode

Returns:
  • Reward

    the true return averaged over batch dimension, shape: (1,)

  • Descriptor

    the descriptor averaged over batch dimension, shape: (num_descriptors,)

  • Reward

    the true return per environment, shape: (env_batch_size,)

  • Descriptor

    the descriptor per environment, shape: (env_batch_size, num_descriptors)

Source code in qdax/baselines/td3.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
def eval_qd_policy_fn(
    self,
    training_state: TD3TrainingState,
    eval_env_first_state: EnvState,
    play_step_fn: Callable[
        [EnvState, Params],
        Tuple[EnvState, TD3TrainingState, QDTransition],
    ],
    descriptor_extraction_fn: Callable[[QDTransition, Mask], Descriptor],
) -> Tuple[Reward, Descriptor, Reward, Descriptor]:
    """Evaluates the agent's policy over an entire episode, across all batched
    environments for QD environments. Averaged descriptors are returned as well.


    Args:
        training_state: the SAC training state
        eval_env_first_state: the initial state for evaluation
        play_step_fn: the play_step function used to collect the evaluation episode

    Returns:
        the true return averaged over batch dimension, shape: (1,)
        the descriptor averaged over batch dimension, shape: (num_descriptors,)
        the true return per environment, shape: (env_batch_size,)
        the descriptor per environment, shape: (env_batch_size, num_descriptors)

    """

    state, training_state, transitions = generate_unroll(
        init_state=eval_env_first_state,
        training_state=training_state,
        episode_length=self._config.episode_length,
        play_step_fn=play_step_fn,
    )
    transitions = get_first_episode(transitions)
    true_returns = jnp.nansum(transitions.rewards, axis=0)
    true_return = jnp.mean(true_returns, axis=-1)

    transitions = jax.tree.map(lambda x: jnp.swapaxes(x, 0, 1), transitions)
    masks = jnp.isnan(transitions.rewards)
    descriptors = descriptor_extraction_fn(transitions, masks)

    mean_descriptor = jnp.mean(descriptors, axis=0)
    return true_return, mean_descriptor, true_returns, descriptors

init(key, action_size, observation_size)

Initialise the training state of the TD3 algorithm, through creation of optimizer states and params.

Parameters:
  • key (RNGKey) –

    a random key used for random operations.

  • action_size (int) –

    the size of the action array needed to interact with the environment.

  • observation_size (int) –

    the size of the observation array retrieved from the environment.

Returns:
  • TD3TrainingState

    the initial training state.

Source code in qdax/baselines/td3.py
 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
def init(
    self, key: RNGKey, action_size: int, observation_size: int
) -> TD3TrainingState:
    """Initialise the training state of the TD3 algorithm, through creation
    of optimizer states and params.

    Args:
        key: a random key used for random operations.
        action_size: the size of the action array needed to interact with the
            environment.
        observation_size: the size of the observation array retrieved from the
            environment.

    Returns:
        the initial training state.
    """

    # Initialize critics and policy params
    fake_obs = jnp.zeros(shape=(observation_size,))
    fake_action = jnp.zeros(shape=(action_size,))
    key, subkey_1, subkey_2 = jax.random.split(key, num=3)
    critic_params = self._critic.init(subkey_1, obs=fake_obs, actions=fake_action)
    policy_params = self._policy.init(subkey_2, fake_obs)

    # Initialize target networks
    target_critic_params = jax.tree.map(
        lambda x: jnp.asarray(x.copy()), critic_params
    )
    target_policy_params = jax.tree.map(
        lambda x: jnp.asarray(x.copy()), policy_params
    )

    # Create and initialize optimizers
    critic_optimizer_state = optax.adam(learning_rate=1.0).init(critic_params)
    policy_optimizer_state = optax.adam(learning_rate=1.0).init(policy_params)

    # Initial training state
    training_state = TD3TrainingState(
        policy_optimizer_state=policy_optimizer_state,
        policy_params=policy_params,
        critic_optimizer_state=critic_optimizer_state,
        critic_params=critic_params,
        target_policy_params=target_policy_params,
        target_critic_params=target_critic_params,
        key=key,
        steps=jnp.array(0),
    )

    return training_state

play_qd_step_fn(env_state, training_state, env, deterministic=False)

Plays a step in the environment. Selects an action according to TD3 rule and performs the environment step.

Parameters:
  • env_state (State) –

    the current environment state

  • training_state (TD3TrainingState) –

    the TD3 training state

  • env (Env) –

    the environment

  • deterministic (bool, default: False ) –

    the whether to select action in a deterministic way. Defaults to False.

Returns:
  • State

    the new environment state

  • TD3TrainingState

    the new TD3 training state

  • QDTransition

    the played transition

Source code in qdax/baselines/td3.py
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
247
248
249
250
251
252
253
254
255
256
def play_qd_step_fn(
    self,
    env_state: EnvState,
    training_state: TD3TrainingState,
    env: Env,
    deterministic: bool = False,
) -> Tuple[EnvState, TD3TrainingState, QDTransition]:
    """Plays a step in the environment. Selects an action according to TD3 rule and
    performs the environment step.

    Args:
        env_state: the current environment state
        training_state: the TD3 training state
        env: the environment
        deterministic: the whether to select action in a deterministic way.
            Defaults to False.

    Returns:
        the new environment state
        the new TD3 training state
        the played transition
    """
    next_env_state, training_state, transition = self.play_step_fn(
        env_state, training_state, env, deterministic
    )
    actions = transition.actions

    truncations = next_env_state.info["truncation"]
    transition = QDTransition(
        obs=env_state.obs,
        next_obs=next_env_state.obs,
        rewards=next_env_state.reward,
        dones=next_env_state.done,
        actions=actions,
        truncations=truncations,
        state_desc=env_state.info["state_descriptor"],
        next_state_desc=next_env_state.info["state_descriptor"],
    )

    return (
        next_env_state,
        training_state,
        transition,
    )

play_step_fn(env_state, training_state, env, deterministic=False)

Plays a step in the environment. Selects an action according to TD3 rule and performs the environment step.

Parameters:
  • env_state (State) –

    the current environment state

  • training_state (TD3TrainingState) –

    the SAC training state

  • env (Env) –

    the environment

  • deterministic (bool, default: False ) –

    whether to select action in a deterministic way. Defaults to False.

Returns:
  • State

    the new environment state

  • TD3TrainingState

    the new TD3 training state

  • Transition

    the played transition

Source code in qdax/baselines/td3.py
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
def play_step_fn(
    self,
    env_state: EnvState,
    training_state: TD3TrainingState,
    env: Env,
    deterministic: bool = False,
) -> Tuple[EnvState, TD3TrainingState, Transition]:
    """Plays a step in the environment. Selects an action according to TD3 rule and
    performs the environment step.

    Args:
        env_state: the current environment state
        training_state: the SAC training state
        env: the environment
        deterministic: whether to select action in a deterministic way.
            Defaults to False.

    Returns:
        the new environment state
        the new TD3 training state
        the played transition
    """
    key = training_state.key

    key, subkey = jax.random.split(key)
    actions = self.select_action(
        obs=env_state.obs,
        policy_params=training_state.policy_params,
        key=subkey,
        expl_noise=self._config.expl_noise,
        deterministic=deterministic,
    )
    training_state = training_state.replace(
        key=key,
    )
    next_env_state = env.step(env_state, actions)
    transition = Transition(
        obs=env_state.obs,
        next_obs=next_env_state.obs,
        rewards=next_env_state.reward,
        dones=next_env_state.done,
        truncations=next_env_state.info["truncation"],
        actions=actions,
    )
    return next_env_state, training_state, transition

select_action(obs, policy_params, key, expl_noise, deterministic=False)

Selects an action according to TD3 policy. The action can be deterministic or stochastic by adding exploration noise.

Parameters:
  • obs (Observation) –

    agent observation(s)

  • policy_params (Params) –

    parameters of the agent's policy

  • key (RNGKey) –

    jax random key

  • expl_noise (float) –

    exploration noise

  • deterministic (bool, default: False ) –

    whether to select action in a deterministic way. Defaults to False.

Returns:
  • Action

    an action and an updated training state.

Source code in qdax/baselines/td3.py
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
def select_action(
    self,
    obs: Observation,
    policy_params: Params,
    key: RNGKey,
    expl_noise: float,
    deterministic: bool = False,
) -> Action:
    """Selects an action according to TD3 policy. The action can be deterministic
    or stochastic by adding exploration noise.

    Args:
        obs: agent observation(s)
        policy_params: parameters of the agent's policy
        key: jax random key
        expl_noise: exploration noise
        deterministic: whether to select action in a deterministic way.
            Defaults to False.

    Returns:
        an action and an updated training state.
    """

    actions = self._policy.apply(policy_params, obs)
    if not deterministic:
        noise = jax.random.normal(key, actions.shape) * expl_noise
        actions = actions + noise
        actions = jnp.clip(actions, -1.0, 1.0)
    return actions

update(training_state, replay_buffer)

Performs a single training step: updates policy params and critic params through gradient descent.

Parameters:
  • training_state (TD3TrainingState) –

    the current training state, containing the optimizer states and the params of the policy and critic.

  • replay_buffer (ReplayBuffer) –

    the replay buffer, filled with transitions experienced in the environment.

Returns:
  • TD3TrainingState

    A new training state, the buffer with new transitions and metrics about the

  • ReplayBuffer

    training process.

Source code in qdax/baselines/td3.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
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
407
408
409
410
411
412
413
414
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
448
449
450
451
452
453
454
def update(
    self,
    training_state: TD3TrainingState,
    replay_buffer: ReplayBuffer,
) -> Tuple[TD3TrainingState, ReplayBuffer, Metrics]:
    """Performs a single training step: updates policy params and critic params
    through gradient descent.

    Args:
        training_state: the current training state, containing the optimizer states
            and the params of the policy and critic.
        replay_buffer: the replay buffer, filled with transitions experienced in
            the environment.

    Returns:
        A new training state, the buffer with new transitions and metrics about the
        training process.
    """

    # Sample a batch of transitions in the buffer
    key = training_state.key

    key, subkey = jax.random.split(key)
    samples = replay_buffer.sample(subkey, sample_size=self._config.batch_size)

    # Update Critic
    key, subkey = jax.random.split(key)
    critic_loss, critic_gradient = jax.value_and_grad(td3_critic_loss_fn)(
        training_state.critic_params,
        target_policy_params=training_state.target_policy_params,
        target_critic_params=training_state.target_critic_params,
        policy_fn=self._policy.apply,
        critic_fn=self._critic.apply,
        policy_noise=self._config.policy_noise,
        noise_clip=self._config.noise_clip,
        reward_scaling=self._config.reward_scaling,
        discount=self._config.discount,
        transitions=samples,
        key=subkey,
    )
    critic_optimizer = optax.adam(learning_rate=self._config.critic_learning_rate)
    critic_updates, critic_optimizer_state = critic_optimizer.update(
        critic_gradient, training_state.critic_optimizer_state
    )
    critic_params = optax.apply_updates(
        training_state.critic_params, critic_updates
    )
    # Soft update of target critic network
    target_critic_params = jax.tree.map(
        lambda x1, x2: (1.0 - self._config.soft_tau_update) * x1
        + self._config.soft_tau_update * x2,
        training_state.target_critic_params,
        critic_params,
    )

    # Update policy
    policy_loss, policy_gradient = jax.value_and_grad(td3_policy_loss_fn)(
        training_state.policy_params,
        critic_params=training_state.critic_params,
        policy_fn=self._policy.apply,
        critic_fn=self._critic.apply,
        transitions=samples,
    )

    def update_policy_step() -> Tuple[Params, Params, optax.OptState]:
        policy_optimizer = optax.adam(
            learning_rate=self._config.policy_learning_rate
        )
        (
            policy_updates,
            policy_optimizer_state,
        ) = policy_optimizer.update(
            policy_gradient, training_state.policy_optimizer_state
        )
        policy_params = optax.apply_updates(
            training_state.policy_params, policy_updates
        )
        # Soft update of target policy
        target_policy_params = jax.tree.map(
            lambda x1, x2: (1.0 - self._config.soft_tau_update) * x1
            + self._config.soft_tau_update * x2,
            training_state.target_policy_params,
            policy_params,
        )
        return policy_params, target_policy_params, policy_optimizer_state

    # Delayed update
    current_policy_state = (
        training_state.policy_params,
        training_state.target_policy_params,
        training_state.policy_optimizer_state,
    )
    policy_params, target_policy_params, policy_optimizer_state = jax.lax.cond(
        training_state.steps % self._config.policy_delay == 0,
        lambda _: update_policy_step(),
        lambda _: current_policy_state,
        operand=None,
    )

    # Create new training state
    new_training_state = training_state.replace(
        critic_params=critic_params,
        critic_optimizer_state=critic_optimizer_state,
        policy_params=policy_params,
        policy_optimizer_state=policy_optimizer_state,
        target_critic_params=target_critic_params,
        target_policy_params=target_policy_params,
        key=key,
        steps=training_state.steps + 1,
    )

    metrics = {
        "actor_loss": policy_loss,
        "critic_loss": critic_loss,
    }

    return new_training_state, replay_buffer, metrics