Skip to content

moplayground.moppo

Multi-objective PPO: the MORLAX and AMOR trainers and the components they share. See Writing an algorithm for how these fit together.

moplayground.moppo.morlax

Proximal policy optimization training.

See: https://arxiv.org/pdf/1707.06347.pdf

Classes:

Name Description
MOTrainingState

Contains training state for the learner.

Functions:

Name Description
sample_preferences
train

Attributes:

Name Type Description
InferenceParams
Metrics

InferenceParams module-attribute

InferenceParams = Tuple[running_statistics.NestedMeanStd, Params]

Metrics module-attribute

Metrics = types.Metrics

MOTrainingState

Contains training state for the learner.

Attributes:

Name Type Description
optimizer_state OptState
params MORLAXNetworkParams
normalizer_params RunningStatisticsState
env_steps UInt64
Source code in src/moplayground/moppo/morlax.py
@flax.struct.dataclass
class MOTrainingState:
    """Contains training state for the learner."""

    optimizer_state   : optax.OptState
    params            : losses.MORLAXNetworkParams
    normalizer_params : running_statistics.RunningStatisticsState
    env_steps         : types.UInt64

optimizer_state instance-attribute

optimizer_state: OptState

params instance-attribute

normalizer_params instance-attribute

normalizer_params: RunningStatisticsState

env_steps instance-attribute

env_steps: UInt64

sample_preferences

sample_preferences(key, it, sampling, K, warmup_frac, alpha, num_evals, num_envs, num_objs)
Source code in src/moplayground/moppo/morlax.py
def sample_preferences(key, it, sampling, K, warmup_frac, alpha, num_evals, num_envs, num_objs):
    cond = it < np.round(warmup_frac * num_evals)
    def warmup_fn(_):
        print('WARMUP')
        w = jnp.ones((1, num_envs, num_objs)) / num_objs
        return w

    def morl_fn(_):
        if sampling == 'dense':
            _, w_key = jax.random.split(key)
            w = jax.random.dirichlet(
                key=w_key,
                alpha=jnp.ones(num_objs) * alpha,
                shape=(1, num_envs)
            )
        elif sampling == 'sparse':
            k = K
            _, w_key = jax.random.split(key)
            w = jax.random.dirichlet(
                key=w_key,
                alpha=jnp.ones(num_objs) * alpha,
                shape=k
            )
            w = jnp.repeat(w, num_envs // k, axis=0)[jnp.newaxis, :]
        elif sampling == 'sparse-heavytail':
            k = K - num_objs
            _, w_key = jax.random.split(key)
            w = jax.random.dirichlet(
                key=w_key,
                alpha=jnp.ones(num_objs) * alpha,
                shape=k
            )
            w = jnp.concat(
                (w, jnp.eye(num_objs)),
                axis=0
            )
            w = jnp.repeat(w, num_envs // (k + num_objs), axis=0)[jnp.newaxis, :]
        elif sampling == 'single-avg':
            w = jnp.ones((1, num_envs, num_objs)) / num_objs
        else:
            raise Exception(f'Sampling type {sampling} not implemented')
        return w
    w = jax.lax.cond(
        cond,
        warmup_fn,
        morl_fn,
        None
    )
    return w

train

train(environment: Env, num_timesteps: int, max_devices_per_host: Optional[int] = None, wrap_env: bool = True, madrona_backend: bool = False, augment_pixels: bool = False, num_envs: int = 1, episode_length: Optional[int] = None, action_repeat: int = 1, wrap_env_fn: Optional[Callable[[Any], Any]] = None, randomization_fn: Optional[Callable[[System, ndarray], Tuple[System, System]]] = None, learning_rate: float = 0.0001, entropy_cost: float = 0.0001, discounting: float = 0.9, unroll_length: int = 10, batch_size: int = 32, num_minibatches: int = 16, num_updates_per_batch: int = 2, num_resets_per_eval: int = 0, normalize_observations: bool = False, reward_scaling: float = 1.0, clipping_epsilon: float = 0.3, gae_lambda: float = 0.95, max_grad_norm: Optional[float] = None, normalize_advantage: bool = True, alpha: float = 1.0, warmup_frac: float = 0.0, sampling: str = 'dense', k: int = 4, network_factory: NetworkFactory[MORLAXNetworks] = make_morlax_networks, init_policy_params: dict = None, init_normalizer_params: dict = None, init_value_params: dict = None, seed: int = 0, use_pmap_on_reset: bool = True, num_evals: int = 1, eval_env: Optional[Env] = None, num_eval_envs: int = 128, deterministic_eval: bool = False, log_training_metrics: bool = False, training_metrics_steps: Optional[int] = None, progress_fn: Callable[[int, Metrics], None] = lambda *args: None, policy_params_fn: Callable[..., None] = lambda *args: None, save_checkpoint_path: Optional[str] = None, restore_checkpoint_path: Optional[str] = None, restore_params: Optional[Any] = None, restore_value_fn: bool = True, run_evals: bool = True)
Source code in src/moplayground/moppo/morlax.py
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
def train(
    environment             : envs.Env,
    num_timesteps           : int,
    max_devices_per_host    : Optional[int] = None,
    # high-level control flow
    wrap_env                : bool = True,
    madrona_backend         : bool = False,
    augment_pixels          : bool = False,
    # environment wrapper
    num_envs                : int = 1,
    episode_length          : Optional[int] = None,
    action_repeat           : int = 1,
    wrap_env_fn             : Optional[Callable[[Any], Any]] = None,
    randomization_fn: Optional[
        Callable[[base.System, jnp.ndarray], Tuple[base.System, base.System]]
    ]                       = None,
    # ppo params
    learning_rate           : float = 1e-4,
    entropy_cost            : float = 1e-4,
    discounting             : float = 0.9,
    unroll_length           : int = 10,
    batch_size              : int = 32,
    num_minibatches         : int = 16,
    num_updates_per_batch   : int = 2,
    num_resets_per_eval     : int = 0,
    normalize_observations  : bool = False,
    reward_scaling          : float = 1.0,
    clipping_epsilon        : float = 0.3,
    gae_lambda              : float = 0.95,
    max_grad_norm           : Optional[float] = None,
    normalize_advantage     : bool = True,
    alpha                   : float = 1.0,
    warmup_frac             : float = 0.0,
    sampling                : str = 'dense',
    k                       : int = 4,
    network_factory: types.NetworkFactory[
        factory.MORLAXNetworks
    ]                       = factory.make_morlax_networks,
    init_policy_params      : dict = None,
    init_normalizer_params  : dict = None,
    init_value_params       : dict = None,
    seed                    : int = 0,
    use_pmap_on_reset       : bool = True,
    # eval
    num_evals               : int = 1,
    eval_env                : Optional[envs.Env] = None,
    num_eval_envs           : int = 128,
    deterministic_eval      : bool = False,
    # training metrics
    log_training_metrics    : bool = False,
    training_metrics_steps  : Optional[int] = None,
    # callbacks
    progress_fn             : Callable[[int, Metrics], None] = lambda *args: None,
    policy_params_fn        : Callable[..., None] = lambda *args: None,
    # checkpointing
    save_checkpoint_path    : Optional[str] = None,
    restore_checkpoint_path : Optional[str] = None,
    restore_params          : Optional[Any] = None,
    restore_value_fn        : bool = True,
    run_evals               : bool = True,
):
    assert batch_size * num_minibatches % num_envs == 0
    xt = time.time()
    process_count, process_id = _get_process_count()
    device_count, local_devices_to_use = _get_device_count(max_devices_per_host, process_count, process_id)
    assert num_envs % device_count == 0

    # The number of environment steps executed for every training step.
    env_step_per_training_step = batch_size * unroll_length * num_minibatches * action_repeat

    # The number of training_step calls per training_epoch call.
    num_evals_after_init = max(num_evals - 1, 1)
    num_training_steps_per_epoch = num_timesteps / (num_evals_after_init * env_step_per_training_step * max(num_resets_per_eval, 1))
    num_training_steps_per_epoch = np.ceil(num_training_steps_per_epoch).astype(int)

    # Get random keys
    local_key, key_env, eval_key, key_policy, key_value = _get_random_keys(seed, process_id)

    env = _maybe_wrap_env(
        environment,
        wrap_env,
        num_envs,
        episode_length,
        action_repeat,
        device_count,
        key_env,
        wrap_env_fn,
        randomization_fn,
    )

    eval_env = _maybe_wrap_env(
        eval_env, #or environment,
        wrap_env,
        num_eval_envs,
        episode_length,
        action_repeat,
        device_count        = 1,  # eval on the host only
        key_env             = eval_key,
        wrap_env_fn         = wrap_env_fn,
    )

    # Reset the environment in a vectorized fashion
    key_envs, env_state, reset_fn = _make_reset_envs(
        local_devices_to_use,
        use_pmap_on_reset,
        env,
        key_env,
        num_envs,
        process_count
    )

    # Discard the batch axes over devices and envs.
    obs_shape = jax.tree_util.tree_map(lambda x: x.shape[2:], env_state.obs)
    num_objectives = env_state.reward.shape[2]

    normalize = lambda x, y: x
    if normalize_observations:
        normalize = running_statistics.normalize
    morlax_networks: factory.MORLAXNetworks = network_factory(
        key                        = key_policy,
        observation_size           = obs_shape,
        action_size                = env.action_size,
        num_objectives             = num_objectives,
        preprocess_observations_fn = normalize,
        target_policy_params       = init_policy_params,
        target_value_params        = init_value_params
    )
    hypernetwork_inference_fn = factory.make_hypernetwork_inference_fn(
        morlax_networks
    )

    optimizer = optax.adam(learning_rate=learning_rate)
    if max_grad_norm is not None:
        # TODO(btaba): Move gradient clipping to `training/gradients.py`.
        optimizer = optax.chain(
            optax.clip_by_global_norm(max_grad_norm),
            optax.adam(learning_rate=learning_rate),
        )

    loss_fn = functools.partial(
        losses.compute_morlax_loss,
        morlax_networks     = morlax_networks,
        entropy_cost        = entropy_cost,
        discounting         = discounting,
        reward_scaling      = reward_scaling,
        gae_lambda          = gae_lambda,
        clipping_epsilon    = clipping_epsilon,
        normalize_advantage = normalize_advantage,
    )

    gradient_update_fn = gradients.gradient_update_fn(
        loss_fn, optimizer, pmap_axis_name=_PMAP_AXIS_NAME, has_aux=True
    )

    metrics_aggregator = metric_logger.EpisodeMetricsLogger(
        steps_between_logging=training_metrics_steps
        or env_step_per_training_step,
        progress_fn=progress_fn,
    )

    def minibatch_step(
        carry,
        data: acting.MultiObjectiveTransition,
        normalizer_params: running_statistics.RunningStatisticsState,
    ):
        optimizer_state, params, key = carry
        key, key_loss = jax.random.split(key)
        (_, metrics), params, optimizer_state = gradient_update_fn(
            params,
            normalizer_params,
            data,
            key_loss,
            optimizer_state=optimizer_state,
        )

        return (optimizer_state, params, key), metrics

    def sgd_step(
        carry,
        unused_t,
        data: acting.MultiObjectiveTransition,
        normalizer_params: running_statistics.RunningStatisticsState,
    ):
        optimizer_state, params, key = carry
        key, key_perm, key_grad = jax.random.split(key, 3)

        def convert_data(x: jnp.ndarray):
            x = jax.random.permutation(key_perm, x)
            x = jnp.reshape(x, (num_minibatches, -1) + x.shape[1:])
            return x

        shuffled_data = jax.tree_util.tree_map(convert_data, data)
        (optimizer_state, params, _), metrics = jax.lax.scan(
            functools.partial(minibatch_step, normalizer_params=normalizer_params),
            (optimizer_state, params, key_grad),
            shuffled_data,
            length=num_minibatches,
        )
        return (optimizer_state, params, key), metrics

    def training_step(
        carry: Tuple[MOTrainingState, envs.State, PRNGKey], unused_t, iteration
    ) -> Tuple[Tuple[MOTrainingState, envs.State, PRNGKey], Metrics]:
        training_state, state, key = carry
        key_sgd, key_generate_unroll, key_pref, new_key = jax.random.split(key, 4)
        tradeoff = sample_preferences(
            key         = key_pref,
            it          = iteration,
            sampling    = sampling,
            K           = k,
            warmup_frac = warmup_frac,
            alpha       = alpha,
            num_evals   = num_evals,
            num_envs    = num_envs,
            num_objs   = state.reward.shape[1]
        )[0]

        policy = hypernetwork_inference_fn(
            params    = (
                training_state.normalizer_params,
                training_state.params.hypernetwork,
            ),
            tradeoff = tradeoff
        )

        def scan_unroll(carry, unused_t):
            current_state, current_key = carry
            current_key, next_key = jax.random.split(current_key)
            next_state, data = acting.generate_unroll(
                env,
                current_state,
                policy,
                tradeoff,
                current_key,
                unroll_length,
                extra_fields=('truncation', 'episode_metrics', 'episode_done'),
            )
            return (next_state, next_key), data

        (state, _), data = jax.lax.scan(
            scan_unroll,
            (state, key_generate_unroll),
            (),
            length=batch_size * num_minibatches // num_envs,
        )
        # Have leading dimensions (batch_size * num_minibatches, unroll_length)
        data = jax.tree_util.tree_map(lambda x: jnp.swapaxes(x, 1, 2), data)
        data: acting.MultiObjectiveTransition = jax.tree_util.tree_map(
            lambda x: jnp.reshape(x, (-1,) + x.shape[2:]), data
        )

        if log_training_metrics:  # log unroll metrics
            jax.debug.callback(
                metrics_aggregator.update_episode_metrics,
                data.extras['state_extras']['episode_metrics'],
                data.extras['state_extras']['episode_done'],
            )
        # Update normalization params and normalize observations.
        normalizer_params = running_statistics.update(
            training_state.normalizer_params,
            data.observation,
            pmap_axis_name=_PMAP_AXIS_NAME,
        )
        (optimizer_state, params, _), metrics = jax.lax.scan(
            functools.partial(
                sgd_step, data=data, normalizer_params=normalizer_params
            ),
            (training_state.optimizer_state, training_state.params, key_sgd),
            (),
            length=num_updates_per_batch,
        )

        new_training_state = MOTrainingState(
            optimizer_state=optimizer_state,
            params=params,
            normalizer_params=normalizer_params,
            env_steps=training_state.env_steps + env_step_per_training_step,
        )
        return (new_training_state, state, new_key), metrics

    def training_epoch(
        training_state: MOTrainingState, state: envs.State, key: PRNGKey, it: int
    ) -> Tuple[MOTrainingState, envs.State, Metrics]:
        training_step_iter = functools.partial(
            training_step,
            iteration=it
        )
        (training_state, state, _), loss_metrics = jax.lax.scan(
            training_step_iter,
            (training_state, state, key),
            (),
            length=num_training_steps_per_epoch,
        )
        loss_metrics = jax.tree_util.tree_map(jnp.mean, loss_metrics)
        return training_state, state, loss_metrics

    training_epoch = jax.pmap(training_epoch, axis_name=_PMAP_AXIS_NAME, in_axes=(0, 0, 0, None))

    # Note that this is NOT a pure jittable method.
    def training_epoch_with_timing(
        training_state: MOTrainingState, env_state: envs.State, key: PRNGKey, it: int
    ) -> Tuple[MOTrainingState, envs.State, Metrics]:
        nonlocal training_walltime
        t = time.time()
        training_state, env_state = _strip_weak_type((training_state, env_state))
        result = training_epoch(training_state, env_state, key, it)
        training_state, env_state, metrics = _strip_weak_type(result)

        metrics = jax.tree_util.tree_map(jnp.mean, metrics)
        jax.tree_util.tree_map(lambda x: x.block_until_ready(), metrics)

        epoch_training_time = time.time() - t
        training_walltime += epoch_training_time
        sps = (
            num_training_steps_per_epoch
            * env_step_per_training_step
            * max(num_resets_per_eval, 1)
        ) / epoch_training_time
        print(f'{num_training_steps_per_epoch=}, {env_step_per_training_step=}')
        metrics = {
            'training/sps': sps,
            'training/walltime': training_walltime,
            **{f'training/{name}': value for name, value in metrics.items()},
        }
        return training_state, env_state, metrics  # pytype: disable=bad-return-type  # py311-upgrade

    # Initialize model params and training state.
    init_params = losses.MORLAXNetworkParams(
        hypernetwork = morlax_networks.hypernetwork.init(key_policy),
    )

    obs_shape = jax.tree_util.tree_map(
        lambda x: specs.Array(x.shape[-1:], jnp.dtype('float32')), env_state.obs
    )
    if init_normalizer_params is None:
        init_normalizer_params = running_statistics.init_state(
            obs_shape
        )
    training_state = MOTrainingState(  # pytype: disable=wrong-arg-types  # jax-ndarray
        optimizer_state=optimizer.init(init_params),  # pytype: disable=wrong-arg-types  # numpy-scalars
        params=init_params,
        normalizer_params=init_normalizer_params,
        env_steps=types.UInt64(hi=0, lo=0),
    )

    if restore_checkpoint_path is not None:
        print('restoring checkpoint')
        params = checkpoint.load(restore_checkpoint_path)
        value_params = params[2] if restore_value_fn else init_params.value
        training_state = training_state.replace(
            normalizer_params=params[0],
            params=training_state.params.replace(
                policy=params[1], value=value_params
            ),
        )

    if restore_params is not None:
        print('restoring params')
        logging.info('Restoring TrainingState from `restore_params`.')
        value_params = restore_params[2] if restore_value_fn else init_params.value
        training_state = training_state.replace(
            normalizer_params=restore_params[0],
            params=training_state.params.replace(
                policy=restore_params[1], value=value_params
            ),
        )

    if num_timesteps == 0:
        return (
            hypernetwork_inference_fn,
            (
                training_state.normalizer_params,
                training_state.params.hypernetwork,
            ),
            {},
        )
    # TODO: If we bump to jax 0.10.0 we will have to update this api
    training_state: MOTrainingState = jax.device_put_replicated(
        training_state, jax.local_devices()[:local_devices_to_use]
    )

    evaluator = acting.Evaluator(
        eval_env       = eval_env,
        eval_policy_fn = functools.partial(
            hypernetwork_inference_fn,
            deterministic = deterministic_eval,
        ),
        num_eval_envs  = num_eval_envs,
        episode_length = episode_length,
        action_repeat  = action_repeat,
        key            = eval_key,
        num_objs       = num_objectives
    )

    training_metrics = {}
    training_walltime = 0
    current_step = 0

    # Run initial eval
    metrics = {}
    if process_id == 0 and num_evals > 1 and run_evals:
        metrics = evaluator.run_evaluation(
            _unpmap((
                training_state.normalizer_params,
                training_state.params.hypernetwork,
            )),
            training_metrics={},
        )
        logging.info(metrics)
        progress_fn(0, metrics)

    # Run initial policy_params_fn.
    params = _unpmap((
        training_state.normalizer_params,
        training_state.params.hypernetwork,
    ))
    policy_params_fn(current_step, hypernetwork_inference_fn, params)

    for it in range(num_evals_after_init):
        logging.info('starting iteration %s %s', it, time.time() - xt)
        print(f'starting iteration {it} {time.time() - xt}')

        for _ in range(max(num_resets_per_eval, 1)):
            # optimization
            epoch_key, local_key = jax.random.split(local_key)
            epoch_keys = jax.random.split(epoch_key, local_devices_to_use)
            (training_state, env_state, training_metrics) = (
                training_epoch_with_timing(training_state, env_state, epoch_keys, it)
            )
            current_step = int(_unpmap(training_state.env_steps))

            key_envs = jax.vmap(
                lambda x, s: jax.random.split(x[0], s), in_axes=(0, None)
            )(key_envs, key_envs.shape[1])
            # TODO(brax-team): move extra reset logic to the AutoResetWrapper.
            env_state = reset_fn(key_envs) if num_resets_per_eval > 0 else env_state

        if process_id != 0:
            continue

        # Process id == 0.
        params = _unpmap((
            training_state.normalizer_params,
            training_state.params.hypernetwork,
        ))

        policy_params_fn(current_step, hypernetwork_inference_fn, params)

        if save_checkpoint_path is not None:
            ckpt_config = checkpoint.network_config(
                observation_size=obs_shape,
                action_size=env.action_size,
                normalize_observations=normalize_observations,
                network_factory=network_factory,
            )
            checkpoint.save(
                save_checkpoint_path, current_step, params, ckpt_config
            )

        if num_evals > 0:
            metrics = training_metrics
            if run_evals:
                metrics = evaluator.run_evaluation(
                    params,
                    training_metrics,
                )
            logging.info(metrics)
            progress_fn(current_step, metrics)

    total_steps = current_step
    if not total_steps >= num_timesteps:
        raise AssertionError(
            f'Total steps {total_steps} is less than `num_timesteps`='
            f' {num_timesteps}.'
        )

    # If there was no mistakes the training_state should still be identical on all
    # devices.
    pmap.assert_is_replicated(training_state)
    params = _unpmap((
        training_state.normalizer_params,
        training_state.params.hypernetwork,
    ))
    logging.info('total steps: %s', total_steps)
    pmap.synchronize_hosts()
    return (hypernetwork_inference_fn, params, metrics)

moplayground.moppo.amor

AMOR: tradeoff-conditioned PPO baseline (no hypernetwork).

The policy and value networks consume concat(normalized_obs, raw_tradeoff). Tradeoffs are sampled per-env per-iteration (same scheme as MORLAX) and held constant within an unroll. Inference exposes a policy(obs, tradeoff, key) closure so callers can change the tradeoff at any step without rebuilding the policy.

Classes:

Name Description
AMORTrainingState

Contains training state for the AMOR learner.

Functions:

Name Description
train

Attributes:

Name Type Description
InferenceParams
Metrics

InferenceParams module-attribute

InferenceParams = Tuple[running_statistics.NestedMeanStd, Params]

Metrics module-attribute

Metrics = types.Metrics

AMORTrainingState

Contains training state for the AMOR learner.

Attributes:

Name Type Description
optimizer_state OptState
params AMORNetworkParams
normalizer_params RunningStatisticsState
env_steps UInt64
Source code in src/moplayground/moppo/amor.py
@flax.struct.dataclass
class AMORTrainingState:
    """Contains training state for the AMOR learner."""

    optimizer_state   : optax.OptState
    params            : losses.AMORNetworkParams
    normalizer_params : running_statistics.RunningStatisticsState
    env_steps         : types.UInt64

optimizer_state instance-attribute

optimizer_state: OptState

params instance-attribute

normalizer_params instance-attribute

normalizer_params: RunningStatisticsState

env_steps instance-attribute

env_steps: UInt64

train

train(environment: Env, num_timesteps: int, max_devices_per_host: Optional[int] = None, wrap_env: bool = True, madrona_backend: bool = False, augment_pixels: bool = False, num_envs: int = 1, episode_length: Optional[int] = None, action_repeat: int = 1, wrap_env_fn: Optional[Callable[[Any], Any]] = None, randomization_fn: Optional[Callable[[System, ndarray], Tuple[System, System]]] = None, learning_rate: float = 0.0001, entropy_cost: float = 0.0001, discounting: float = 0.9, unroll_length: int = 10, batch_size: int = 32, num_minibatches: int = 16, num_updates_per_batch: int = 2, num_resets_per_eval: int = 0, normalize_observations: bool = False, reward_scaling: float = 1.0, clipping_epsilon: float = 0.3, gae_lambda: float = 0.95, max_grad_norm: Optional[float] = None, normalize_advantage: bool = True, alpha: float = 1.0, warmup_frac: float = 0.0, sampling: str = 'dense', k: int = 4, network_factory: NetworkFactory[AMORNetworks] = make_amor_networks, init_policy_params: dict = None, init_normalizer_params: dict = None, init_value_params: dict = None, seed: int = 0, use_pmap_on_reset: bool = True, num_evals: int = 1, eval_env: Optional[Env] = None, num_eval_envs: int = 128, deterministic_eval: bool = False, log_training_metrics: bool = False, training_metrics_steps: Optional[int] = None, progress_fn: Callable[[int, Metrics], None] = lambda *args: None, policy_params_fn: Callable[..., None] = lambda *args: None, save_checkpoint_path: Optional[str] = None, restore_checkpoint_path: Optional[str] = None, restore_params: Optional[Any] = None, restore_value_fn: bool = True, run_evals: bool = True)
Source code in src/moplayground/moppo/amor.py
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
def train(
    environment             : envs.Env,
    num_timesteps           : int,
    max_devices_per_host    : Optional[int] = None,
    # high-level control flow
    wrap_env                : bool = True,
    madrona_backend         : bool = False,
    augment_pixels          : bool = False,
    # environment wrapper
    num_envs                : int = 1,
    episode_length          : Optional[int] = None,
    action_repeat           : int = 1,
    wrap_env_fn             : Optional[Callable[[Any], Any]] = None,
    randomization_fn: Optional[
        Callable[[base.System, jnp.ndarray], Tuple[base.System, base.System]]
    ]                       = None,
    # ppo params
    learning_rate           : float = 1e-4,
    entropy_cost            : float = 1e-4,
    discounting             : float = 0.9,
    unroll_length           : int = 10,
    batch_size              : int = 32,
    num_minibatches         : int = 16,
    num_updates_per_batch   : int = 2,
    num_resets_per_eval     : int = 0,
    normalize_observations  : bool = False,
    reward_scaling          : float = 1.0,
    clipping_epsilon        : float = 0.3,
    gae_lambda              : float = 0.95,
    max_grad_norm           : Optional[float] = None,
    normalize_advantage     : bool = True,
    # tradeoff sampling (shared with MORLAX)
    alpha                   : float = 1.0,
    warmup_frac             : float = 0.0,
    sampling                : str = 'dense',
    k                       : int = 4,
    network_factory: types.NetworkFactory[
        factory.AMORNetworks
    ]                       = factory.make_amor_networks,
    init_policy_params      : dict = None,
    init_normalizer_params  : dict = None,
    init_value_params       : dict = None,
    seed                    : int = 0,
    use_pmap_on_reset       : bool = True,
    # eval
    num_evals               : int = 1,
    eval_env                : Optional[envs.Env] = None,
    num_eval_envs           : int = 128,
    deterministic_eval      : bool = False,
    # training metrics
    log_training_metrics    : bool = False,
    training_metrics_steps  : Optional[int] = None,
    # callbacks
    progress_fn             : Callable[[int, Metrics], None] = lambda *args: None,
    policy_params_fn        : Callable[..., None] = lambda *args: None,
    # checkpointing
    save_checkpoint_path    : Optional[str] = None,
    restore_checkpoint_path : Optional[str] = None,
    restore_params          : Optional[Any] = None,
    restore_value_fn        : bool = True,
    run_evals               : bool = True,
):
    assert batch_size * num_minibatches % num_envs == 0
    xt = time.time()
    process_count, process_id = _get_process_count()
    device_count, local_devices_to_use = _get_device_count(max_devices_per_host, process_count, process_id)
    assert num_envs % device_count == 0

    env_step_per_training_step = batch_size * unroll_length * num_minibatches * action_repeat

    num_evals_after_init = max(num_evals - 1, 1)
    num_training_steps_per_epoch = num_timesteps / (num_evals_after_init * env_step_per_training_step * max(num_resets_per_eval, 1))
    num_training_steps_per_epoch = np.ceil(num_training_steps_per_epoch).astype(int)

    local_key, key_env, eval_key, key_policy, key_value = _get_random_keys(seed, process_id)

    env = _maybe_wrap_env(
        environment,
        wrap_env,
        num_envs,
        episode_length,
        action_repeat,
        device_count,
        key_env,
        wrap_env_fn,
        randomization_fn,
    )

    eval_env = _maybe_wrap_env(
        eval_env,
        wrap_env,
        num_eval_envs,
        episode_length,
        action_repeat,
        device_count        = 1,
        key_env             = eval_key,
        wrap_env_fn         = wrap_env_fn,
    )

    key_envs, env_state, reset_fn = _make_reset_envs(
        local_devices_to_use,
        use_pmap_on_reset,
        env,
        key_env,
        num_envs,
        process_count
    )

    obs_shape = jax.tree_util.tree_map(lambda x: x.shape[2:], env_state.obs)
    num_objectives = env_state.reward.shape[2]

    normalize = lambda x, y: x
    if normalize_observations:
        normalize = running_statistics.normalize
    amor_networks: factory.AMORNetworks = network_factory(
        key                        = key_policy,
        observation_size           = obs_shape,
        action_size                = env.action_size,
        num_objectives             = num_objectives,
        preprocess_observations_fn = normalize,
    )
    amor_inference_fn = factory.make_amor_inference_fn(amor_networks)
    baked_inference_fn = _make_baked_inference_fn(amor_inference_fn)

    optimizer = optax.adam(learning_rate=learning_rate)
    if max_grad_norm is not None:
        optimizer = optax.chain(
            optax.clip_by_global_norm(max_grad_norm),
            optax.adam(learning_rate=learning_rate),
        )

    loss_fn = functools.partial(
        losses.compute_amor_loss,
        amor_networks       = amor_networks,
        entropy_cost        = entropy_cost,
        discounting         = discounting,
        reward_scaling      = reward_scaling,
        gae_lambda          = gae_lambda,
        clipping_epsilon    = clipping_epsilon,
        normalize_advantage = normalize_advantage,
    )

    gradient_update_fn = gradients.gradient_update_fn(
        loss_fn, optimizer, pmap_axis_name=_PMAP_AXIS_NAME, has_aux=True
    )

    metrics_aggregator = metric_logger.EpisodeMetricsLogger(
        steps_between_logging=training_metrics_steps
        or env_step_per_training_step,
        progress_fn=progress_fn,
    )

    def minibatch_step(
        carry,
        data: acting.MultiObjectiveTransition,
        normalizer_params: running_statistics.RunningStatisticsState,
    ):
        optimizer_state, params, key = carry
        key, key_loss = jax.random.split(key)
        (_, metrics), params, optimizer_state = gradient_update_fn(
            params,
            normalizer_params,
            data,
            key_loss,
            optimizer_state=optimizer_state,
        )
        return (optimizer_state, params, key), metrics

    def sgd_step(
        carry,
        unused_t,
        data: acting.MultiObjectiveTransition,
        normalizer_params: running_statistics.RunningStatisticsState,
    ):
        optimizer_state, params, key = carry
        key, key_perm, key_grad = jax.random.split(key, 3)

        def convert_data(x: jnp.ndarray):
            x = jax.random.permutation(key_perm, x)
            x = jnp.reshape(x, (num_minibatches, -1) + x.shape[1:])
            return x

        shuffled_data = jax.tree_util.tree_map(convert_data, data)
        (optimizer_state, params, _), metrics = jax.lax.scan(
            functools.partial(minibatch_step, normalizer_params=normalizer_params),
            (optimizer_state, params, key_grad),
            shuffled_data,
            length=num_minibatches,
        )
        return (optimizer_state, params, key), metrics

    def training_step(
        carry: Tuple[AMORTrainingState, envs.State, PRNGKey], unused_t, iteration
    ) -> Tuple[Tuple[AMORTrainingState, envs.State, PRNGKey], Metrics]:
        training_state, state, key = carry
        key_sgd, key_generate_unroll, key_pref, new_key = jax.random.split(key, 4)
        tradeoff = sample_preferences(
            key         = key_pref,
            it          = iteration,
            sampling    = sampling,
            K           = k,
            warmup_frac = warmup_frac,
            alpha       = alpha,
            num_evals   = num_evals,
            num_envs    = num_envs,
            num_objs    = state.reward.shape[1]
        )[0]  # strip leading 1 axis -> (num_envs, num_objs)

        # AMOR's flat policy: tradeoff is concatenated to obs inside the network.
        # Within an unroll the tradeoff is held constant per-env (matches MORLAX).
        policy = baked_inference_fn(
            params    = (training_state.normalizer_params, training_state.params.policy),
            tradeoff = tradeoff,
        )

        def scan_unroll(carry, unused_t):
            current_state, current_key = carry
            current_key, next_key = jax.random.split(current_key)
            next_state, data = acting.generate_unroll(
                env,
                current_state,
                policy,
                tradeoff,
                current_key,
                unroll_length,
                extra_fields=('truncation', 'episode_metrics', 'episode_done'),
            )
            return (next_state, next_key), data

        (state, _), data = jax.lax.scan(
            scan_unroll,
            (state, key_generate_unroll),
            (),
            length=batch_size * num_minibatches // num_envs,
        )
        data = jax.tree_util.tree_map(lambda x: jnp.swapaxes(x, 1, 2), data)
        data: acting.MultiObjectiveTransition = jax.tree_util.tree_map(
            lambda x: jnp.reshape(x, (-1,) + x.shape[2:]), data
        )

        if log_training_metrics:
            jax.debug.callback(
                metrics_aggregator.update_episode_metrics,
                data.extras['state_extras']['episode_metrics'],
                data.extras['state_extras']['episode_done'],
            )

        normalizer_params = running_statistics.update(
            training_state.normalizer_params,
            data.observation,
            pmap_axis_name=_PMAP_AXIS_NAME,
        )
        (optimizer_state, params, _), metrics = jax.lax.scan(
            functools.partial(
                sgd_step, data=data, normalizer_params=normalizer_params
            ),
            (training_state.optimizer_state, training_state.params, key_sgd),
            (),
            length=num_updates_per_batch,
        )

        new_training_state = AMORTrainingState(
            optimizer_state=optimizer_state,
            params=params,
            normalizer_params=normalizer_params,
            env_steps=training_state.env_steps + env_step_per_training_step,
        )
        return (new_training_state, state, new_key), metrics

    def training_epoch(
        training_state: AMORTrainingState, state: envs.State, key: PRNGKey, it: int
    ) -> Tuple[AMORTrainingState, envs.State, Metrics]:
        training_step_iter = functools.partial(training_step, iteration=it)
        (training_state, state, _), loss_metrics = jax.lax.scan(
            training_step_iter,
            (training_state, state, key),
            (),
            length=num_training_steps_per_epoch,
        )
        loss_metrics = jax.tree_util.tree_map(jnp.mean, loss_metrics)
        return training_state, state, loss_metrics

    training_epoch = jax.pmap(training_epoch, axis_name=_PMAP_AXIS_NAME, in_axes=(0, 0, 0, None))

    def training_epoch_with_timing(
        training_state: AMORTrainingState, env_state: envs.State, key: PRNGKey, it: int
    ) -> Tuple[AMORTrainingState, envs.State, Metrics]:
        nonlocal training_walltime
        t = time.time()
        training_state, env_state = _strip_weak_type((training_state, env_state))
        result = training_epoch(training_state, env_state, key, it)
        training_state, env_state, metrics = _strip_weak_type(result)

        metrics = jax.tree_util.tree_map(jnp.mean, metrics)
        jax.tree_util.tree_map(lambda x: x.block_until_ready(), metrics)

        epoch_training_time = time.time() - t
        training_walltime += epoch_training_time
        sps = (
            num_training_steps_per_epoch
            * env_step_per_training_step
            * max(num_resets_per_eval, 1)
        ) / epoch_training_time
        print(f'{num_training_steps_per_epoch=}, {env_step_per_training_step=}')
        metrics = {
            'training/sps': sps,
            'training/walltime': training_walltime,
            **{f'training/{name}': value for name, value in metrics.items()},
        }
        return training_state, env_state, metrics

    # Initialize model params and training state.
    if init_policy_params is None:
        init_policy_params = amor_networks.policy_network.init(key_policy)
    if init_value_params is None:
        init_value_params = amor_networks.value_network.init(key_value)

    init_params = losses.AMORNetworkParams(
        policy = init_policy_params,
        value  = init_value_params,
    )

    obs_shape_specs = jax.tree_util.tree_map(
        lambda x: specs.Array(x.shape[-1:], jnp.dtype('float32')), env_state.obs
    )
    if init_normalizer_params is None:
        init_normalizer_params = running_statistics.init_state(obs_shape_specs)
    training_state = AMORTrainingState(
        optimizer_state=optimizer.init(init_params),
        params=init_params,
        normalizer_params=init_normalizer_params,
        env_steps=types.UInt64(hi=0, lo=0),
    )

    if restore_checkpoint_path is not None:
        print('restoring checkpoint')
        restored = checkpoint.load(restore_checkpoint_path)
        # restored = (normalizer, policy, value) — standard 3-tuple
        value_params = restored[2] if restore_value_fn else init_params.value
        training_state = training_state.replace(
            normalizer_params=restored[0],
            params=training_state.params.replace(
                policy=restored[1], value=value_params
            ),
        )

    if restore_params is not None:
        print('restoring params')
        logging.info('Restoring TrainingState from `restore_params`.')
        value_params = restore_params[2] if restore_value_fn else init_params.value
        training_state = training_state.replace(
            normalizer_params=restore_params[0],
            params=training_state.params.replace(
                policy=restore_params[1], value=value_params
            ),
        )

    if num_timesteps == 0:
        return (
            amor_inference_fn,
            (
                training_state.normalizer_params,
                training_state.params.policy,
                training_state.params.value,
            ),
            {},
        )

    training_state: AMORTrainingState = jax.device_put_replicated(
        training_state, jax.local_devices()[:local_devices_to_use]
    )

    evaluator = acting.Evaluator(
        eval_env       = eval_env,
        eval_policy_fn = functools.partial(
            baked_inference_fn,
            deterministic = deterministic_eval,
        ),
        num_eval_envs  = num_eval_envs,
        episode_length = episode_length,
        action_repeat  = action_repeat,
        key            = eval_key,
        num_objs       = num_objectives,
    )

    training_metrics = {}
    training_walltime = 0
    current_step = 0

    metrics = {}
    if process_id == 0 and num_evals > 1 and run_evals:
        metrics = evaluator.run_evaluation(
            _unpmap((
                training_state.normalizer_params,
                training_state.params.policy,
            )),
            training_metrics={},
        )
        logging.info(metrics)
        progress_fn(0, metrics)

    params = _unpmap((
        training_state.normalizer_params,
        training_state.params.policy,
        training_state.params.value,
    ))
    policy_params_fn(current_step, baked_inference_fn, params)

    for it in range(num_evals_after_init):
        logging.info('starting iteration %s %s', it, time.time() - xt)
        print(f'starting iteration {it} {time.time() - xt}')

        for _ in range(max(num_resets_per_eval, 1)):
            epoch_key, local_key = jax.random.split(local_key)
            epoch_keys = jax.random.split(epoch_key, local_devices_to_use)
            (training_state, env_state, training_metrics) = (
                training_epoch_with_timing(training_state, env_state, epoch_keys, it)
            )
            current_step = int(_unpmap(training_state.env_steps))

            key_envs = jax.vmap(
                lambda x, s: jax.random.split(x[0], s), in_axes=(0, None)
            )(key_envs, key_envs.shape[1])
            env_state = reset_fn(key_envs) if num_resets_per_eval > 0 else env_state

        if process_id != 0:
            continue

        params = _unpmap((
            training_state.normalizer_params,
            training_state.params.policy,
            training_state.params.value,
        ))

        policy_params_fn(current_step, baked_inference_fn, params)

        if save_checkpoint_path is not None:
            ckpt_config = checkpoint.network_config(
                observation_size=obs_shape,
                action_size=env.action_size,
                normalize_observations=normalize_observations,
                network_factory=network_factory,
            )
            checkpoint.save(save_checkpoint_path, current_step, params, ckpt_config)

        if num_evals > 0:
            metrics = training_metrics
            if run_evals:
                metrics = evaluator.run_evaluation(
                    _unpmap((
                        training_state.normalizer_params,
                        training_state.params.policy,
                    )),
                    training_metrics,
                )
            logging.info(metrics)
            progress_fn(current_step, metrics)

    total_steps = current_step
    if not total_steps >= num_timesteps:
        raise AssertionError(
            f'Total steps {total_steps} is less than `num_timesteps`='
            f' {num_timesteps}.'
        )

    pmap.assert_is_replicated(training_state)
    params = _unpmap((
        training_state.normalizer_params,
        training_state.params.policy,
        training_state.params.value,
    ))
    logging.info('total steps: %s', total_steps)
    pmap.synchronize_hosts()
    return (amor_inference_fn, params, metrics)

moplayground.moppo.losses

Proximal policy optimization training.

See: https://arxiv.org/pdf/1707.06347.pdf

Classes:

Name Description
MORLAXNetworkParams

Contains training state for the learner.

AMORNetworkParams

Contains training state for the AMOR learner.

Functions:

Name Description
compute_mo_gae

Calculates the Generalized Advantage Estimation (GAE) in the

compute_morlax_loss

Computes PPO loss.

compute_amor_loss

Multi-objective PPO loss for AMOR.

MORLAXNetworkParams

Contains training state for the learner.

Attributes:

Name Type Description
hypernetwork Params
Source code in src/moplayground/moppo/losses.py
@flax.struct.dataclass
class MORLAXNetworkParams:
    """Contains training state for the learner."""
    hypernetwork: Params

hypernetwork instance-attribute

hypernetwork: Params

AMORNetworkParams

Contains training state for the AMOR learner.

AMOR has no hypernetwork; the policy and value networks are flat MLPs that take concat(obs, tradeoff) as input.

Attributes:

Name Type Description
policy Params
value Params
Source code in src/moplayground/moppo/losses.py
@flax.struct.dataclass
class AMORNetworkParams:
    """Contains training state for the AMOR learner.

    AMOR has no hypernetwork; the policy and value networks are flat MLPs that
    take ``concat(obs, tradeoff)`` as input.
    """
    policy: Params
    value:  Params

policy instance-attribute

policy: Params

value instance-attribute

value: Params

compute_mo_gae

compute_mo_gae(truncation: ndarray, termination: ndarray, rewards: ndarray, values: ndarray, bootstrap_value: ndarray, lambda_: float = 1.0, discount: float = 0.99)

Calculates the Generalized Advantage Estimation (GAE) in the multi-objective setting. T represents time, B is the batch size, and M is the number of objectives

Parameters:

Name Type Description Default
truncation ndarray

[T, B] truncation signal.

required
termination ndarray

[T, B] termination signal.

required
rewards ndarray

[T, B, M] multi-objective rewards generated by following the policy.

required
values ndarray

[T, B, M] multi-objective value function estimates wrt. the target policy.

required
bootstrap_value ndarray

[B, M] multi-objective value function estimate at time T.

required
lambda_ float

Mix between 1-step (lambda_=0) and n-step (lambda_=1). Defaults to lambda_=1.

1.0
discount float

TD discount.

0.99

Returns:

Type Description

Values [T, B, M]: can be used as target to train a baseline (V(x_t) - vs_t)^2. Advantages [T, B, M]: for policy loss

Source code in src/moplayground/moppo/losses.py
def compute_mo_gae(
    truncation: jnp.ndarray,
    termination: jnp.ndarray,
    rewards: jnp.ndarray,
    values: jnp.ndarray,
    bootstrap_value: jnp.ndarray,
    lambda_: float = 1.0,
    discount: float = 0.99,
):
    """Calculates the Generalized Advantage Estimation (GAE) in the
    multi-objective setting. T represents time, B is the batch size, and 
    M is the number of objectives

    Args:
        truncation: [T, B] truncation signal.
        termination: [T, B] termination signal.
        rewards: [T, B, M] multi-objective rewards generated by following the policy.
        values: [T, B, M] multi-objective value function estimates wrt. the target policy.
        bootstrap_value: [B, M] multi-objective value function estimate at time T.
        lambda_: Mix between 1-step (lambda_=0) and n-step (lambda_=1). Defaults to lambda_=1.
        discount: TD discount.

    Returns:
        Values [T, B, M]: can be used as target to train a baseline (V(x_t) - vs_t)^2.
        Advantages [T, B, M]: for policy loss
    """
    truncation_mask = (1 - truncation)[..., None]  # -> [T, B, 1]
    termination = termination[..., None]           # -> [T, B, 1]

    # Shift values for t+1
    values_t_plus_1 = jnp.concatenate(
        [values[1:], jnp.expand_dims(bootstrap_value, 0)], axis=0
    )  # [T, B, M]

    # Vectorized TD residuals 
    deltas = rewards + discount * (1 - termination) * values_t_plus_1 - values
    deltas *= truncation_mask  # mask out truncated steps

    acc = jnp.zeros_like(bootstrap_value)  # [B, M]

    def compute_vs_minus_v_xs(carry, target_t):
        lambda_, acc = carry
        trunc_mask_t, delta_t, term_t = target_t
        acc = delta_t + discount * (1 - term_t) * trunc_mask_t * lambda_ * acc
        return (lambda_, acc), acc

    (_, _), vs_minus_v_xs = jax.lax.scan(
        compute_vs_minus_v_xs,
        (lambda_, acc),
        (truncation_mask, deltas, termination),
        length=int(truncation_mask.shape[0]),
        reverse=True,
    )

    # Add back baseline value
    vs = vs_minus_v_xs + values  # [T, B, K]

    vs_t_plus_1 = jnp.concatenate(
        [vs[1:], jnp.expand_dims(bootstrap_value, 0)], axis=0
    )

    advantages = (
        rewards + discount * (1 - termination) * vs_t_plus_1 - values
    ) * truncation_mask

    return jax.lax.stop_gradient(vs), jax.lax.stop_gradient(advantages)

compute_morlax_loss

compute_morlax_loss(params: MORLAXNetworkParams, normalizer_params: Any, data: MultiObjectiveTransition, rng: ndarray, morlax_networks: MORLAXNetworks, entropy_cost: float = 0.0001, discounting: float = 0.9, reward_scaling: float = 1.0, gae_lambda: float = 0.95, clipping_epsilon: float = 0.3, normalize_advantage: bool = True) -> Tuple[ndarray, Metrics]

Computes PPO loss.

Parameters:

Name Type Description Default
params MORLAXNetworkParams

Network parameters,

required
normalizer_params Any

Parameters of the normalizer.

required
data MultiObjectiveTransition

Transition that with leading dimension [B, T]. extra fields required are ['state_extras']['truncation'], ['policy_extras']['raw_action'], ['policy_extras']['log_prob']

required
rng ndarray

Random key

required
morlax_networks MORLAXNetworks

MORLAX networks.

required
entropy_cost float

entropy cost.

0.0001
discounting float

discounting,

0.9
reward_scaling float

reward multiplier.

1.0
gae_lambda float

General advantage estimation lambda.

0.95
clipping_epsilon float

Policy loss clipping epsilon

0.3
normalize_advantage bool

whether to normalize advantage estimate

True

Returns:

Type Description
Tuple[ndarray, Metrics]

A tuple (loss, metrics)

Source code in src/moplayground/moppo/losses.py
def compute_morlax_loss(
    params              : MORLAXNetworkParams,
    normalizer_params   : Any,
    data                : MultiObjectiveTransition,
    rng                 : jnp.ndarray,
    morlax_networks     : factory.MORLAXNetworks,
    entropy_cost        : float = 1e-4,
    discounting         : float = 0.9,
    reward_scaling      : float = 1.0,
    gae_lambda          : float = 0.95,
    clipping_epsilon    : float = 0.3,
    normalize_advantage : bool = True,
) -> Tuple[jnp.ndarray, types.Metrics]:
    """Computes PPO loss.

    Args:
      params: Network parameters,
      normalizer_params: Parameters of the normalizer.
      data: Transition that with leading dimension [B, T]. extra fields required
        are ``['state_extras']['truncation']``, ``['policy_extras']['raw_action']``,
        ``['policy_extras']['log_prob']``
      rng: Random key
      morlax_networks: MORLAX networks.
      entropy_cost: entropy cost.
      discounting: discounting,
      reward_scaling: reward multiplier.
      gae_lambda: General advantage estimation lambda.
      clipping_epsilon: Policy loss clipping epsilon
      normalize_advantage: whether to normalize advantage estimate

    Returns:
      A tuple (loss, metrics)
    """
    parametric_action_distribution = morlax_networks.parametric_action_distribution
    policy_apply        = jax.vmap(morlax_networks.policy_network.apply, in_axes=(None, 0, 1))
    value_apply         = jax.vmap(morlax_networks.value_network.apply,  in_axes=(None, 0, 1))
    single_value_apply  = jax.vmap(morlax_networks.value_network.apply,  in_axes=(None, 0, 0))
    policy_params, value_params = morlax_networks.hypernetwork.apply(
        params.hypernetwork, data.tradeoff[:, 0]
    )

    # Put the time dimension first.
    data = jax.tree_util.tree_map(lambda x: jnp.swapaxes(x, 0, 1), data)
    # print(f'{data=}')

    # policy...
    policy_logits = policy_apply(
        normalizer_params, policy_params, data.observation
    )
    policy_logits = jnp.swapaxes(policy_logits, 0, 1)

    # value...
    baseline = value_apply(
        normalizer_params, value_params, data.observation
    )
    baseline = jnp.swapaxes(baseline, 0, 1)
    terminal_obs = jax.tree_util.tree_map(lambda x: x[-1], data.next_observation)
    bootstrap_value = single_value_apply(
        normalizer_params, value_params, terminal_obs
    )
    rewards = data.reward * reward_scaling
    rewards = jnp.sum(data.tradeoff * rewards, axis=2)

    truncation = data.extras['state_extras']['truncation']
    termination = (1 - data.discount) * (1 - truncation)

    target_action_log_probs = parametric_action_distribution.log_prob(
        policy_logits, data.extras['policy_extras']['raw_action']
    )
    behaviour_action_log_probs = data.extras['policy_extras']['log_prob']

    vs, advantages = losses.compute_gae(
        truncation      = truncation,
        termination     = termination,
        rewards         = rewards,
        values          = baseline,
        bootstrap_value = bootstrap_value,
        lambda_         = gae_lambda,
        discount        = discounting,
    )
    if normalize_advantage:
        advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
    rho_s = jnp.exp(target_action_log_probs - behaviour_action_log_probs)

    surrogate_loss1 = rho_s * advantages
    surrogate_loss2 = (
        jnp.clip(rho_s, 1 - clipping_epsilon, 1 + clipping_epsilon) * advantages
    )

    policy_loss = -jnp.mean(jnp.minimum(surrogate_loss1, surrogate_loss2))

    # Value function loss
    v_error = vs - baseline
    v_loss = jnp.mean(v_error * v_error) * 0.5 * 0.5

    # Entropy reward
    entropy = jnp.mean(parametric_action_distribution.entropy(policy_logits, rng))
    entropy_loss = entropy_cost * -entropy

    total_loss = policy_loss + v_loss + entropy_loss

    return total_loss, {
        'total_loss'   : total_loss,
        'policy_loss'  : policy_loss,
        'v_loss'       : v_loss,
        'entropy_loss' : entropy_loss,
    }

compute_amor_loss

compute_amor_loss(params: AMORNetworkParams, normalizer_params: Any, data: MultiObjectiveTransition, rng: ndarray, amor_networks: AMORNetworks, entropy_cost: float = 0.0001, discounting: float = 0.9, reward_scaling: float = 1.0, gae_lambda: float = 0.95, clipping_epsilon: float = 0.3, normalize_advantage: bool = True) -> Tuple[ndarray, Metrics]

Multi-objective PPO loss for AMOR.

Identical to compute_morlax_loss except the policy and value networks are flat (no hypernetwork): they consume (obs, tradeoff) directly.

Source code in src/moplayground/moppo/losses.py
def compute_amor_loss(
    params              : AMORNetworkParams,
    normalizer_params   : Any,
    data                : MultiObjectiveTransition,
    rng                 : jnp.ndarray,
    amor_networks       : factory.AMORNetworks,
    entropy_cost        : float = 1e-4,
    discounting         : float = 0.9,
    reward_scaling      : float = 1.0,
    gae_lambda          : float = 0.95,
    clipping_epsilon    : float = 0.3,
    normalize_advantage : bool = True,
) -> Tuple[jnp.ndarray, types.Metrics]:
    """Multi-objective PPO loss for AMOR.

    Identical to ``compute_morlax_loss`` except the policy and value networks
    are flat (no hypernetwork): they consume ``(obs, tradeoff)`` directly.
    """
    parametric_action_distribution = amor_networks.parametric_action_distribution

    # Put the time dimension first: data is currently [B, T, ...].
    data = jax.tree_util.tree_map(lambda x: jnp.swapaxes(x, 0, 1), data)
    # Now data has leading dims [T, B, ...].

    # Policy and value forward passes. Networks are shared across the batch;
    # only obs (axis 1 in [T, B, ...]) and tradeoff vary across the batch.
    # Vmap over the B axis: obs/tradeoff in_axes=1, params/normalizer shared.
    policy_apply = jax.vmap(
        amor_networks.policy_network.apply,
        in_axes=(None, None, 1, 1),
        out_axes=1,
    )
    value_apply = jax.vmap(
        amor_networks.value_network.apply,
        in_axes=(None, None, 1, 1),
        out_axes=1,
    )

    policy_logits = policy_apply(
        normalizer_params, params.policy, data.observation, data.tradeoff
    )
    baseline = value_apply(
        normalizer_params, params.value, data.observation, data.tradeoff
    )

    # Bootstrap value at the terminal observation (one per env, no time axis).
    terminal_obs = jax.tree_util.tree_map(lambda x: x[-1], data.next_observation)
    terminal_tradeoff = data.tradeoff[-1]
    single_value_apply = jax.vmap(
        amor_networks.value_network.apply,
        in_axes=(None, None, 0, 0),
    )
    bootstrap_value = single_value_apply(
        normalizer_params, params.value, terminal_obs, terminal_tradeoff
    )

    rewards = data.reward * reward_scaling  # [T, B, M]

    truncation = data.extras['state_extras']['truncation']
    termination = (1 - data.discount) * (1 - truncation)

    target_action_log_probs = parametric_action_distribution.log_prob(
        policy_logits, data.extras['policy_extras']['raw_action']
    )
    behaviour_action_log_probs = data.extras['policy_extras']['log_prob']

    # Vector GAE: per-objective vs and advantages of shape [T, B, M].
    vs, vec_advantages = compute_mo_gae(
        truncation      = truncation,
        termination     = termination,
        rewards         = rewards,
        values          = baseline,
        bootstrap_value = bootstrap_value,
        lambda_         = gae_lambda,
        discount        = discounting,
    )
    # Scalarize advantages with the per-step tradeoff for the policy update.
    advantages = jnp.sum(data.tradeoff * vec_advantages, axis=-1)  # [T, B]
    if normalize_advantage:
        advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
    rho_s = jnp.exp(target_action_log_probs - behaviour_action_log_probs)

    surrogate_loss1 = rho_s * advantages
    surrogate_loss2 = (
        jnp.clip(rho_s, 1 - clipping_epsilon, 1 + clipping_epsilon) * advantages
    )

    policy_loss = -jnp.mean(jnp.minimum(surrogate_loss1, surrogate_loss2))

    # Vector value loss: equal weight across objectives (no normalization).
    v_error = vs - baseline  # [T, B, M]
    v_loss = jnp.mean(v_error * v_error) * 0.5 * 0.5

    entropy = jnp.mean(parametric_action_distribution.entropy(policy_logits, rng))
    entropy_loss = entropy_cost * -entropy

    total_loss = policy_loss + v_loss + entropy_loss

    return total_loss, {
        'total_loss'   : total_loss,
        'policy_loss'  : policy_loss,
        'v_loss'       : v_loss,
        'entropy_loss' : entropy_loss,
    }

moplayground.moppo.factory

PPO networks.

Classes:

Name Description
FeedForwardHypernetwork
MORLAXNetworks
AMORNetworks

Functions:

Name Description
make_hypernetwork_inference_fn

Creates params and inference function for the PPO agent.

make_morlax_networks

Make PPO networks with preprocessor.

make_hypernetwork
make_amor_policy_network

AMOR policy network: input is concat(normalized_obs, raw_tradeoff).

make_amor_value_network

AMOR value network: input is concat(normalized_obs, raw_tradeoff),

make_amor_networks

Make AMOR networks (tradeoff-conditioned policy + multi-objective value).

make_amor_inference_fn

Creates an inference function for AMOR.

Attributes:

Name Type Description
ActivationFn
Initializer

ActivationFn module-attribute

ActivationFn = Callable[[jnp.ndarray], jnp.ndarray]

Initializer module-attribute

Initializer = Callable[..., Any]

FeedForwardHypernetwork dataclass

Attributes:

Name Type Description
init Callable[..., Any]
apply Callable[..., Any]
get_features Callable[..., Any]
get_flat_mlps Callable[..., Any]
Source code in src/moplayground/moppo/factory.py
@dataclasses.dataclass
class FeedForwardHypernetwork:
    init            : Callable[..., Any]
    apply           : Callable[..., Any]
    get_features    : Callable[..., Any]
    get_flat_mlps   : Callable[..., Any]

init instance-attribute

init: Callable[..., Any]

apply instance-attribute

apply: Callable[..., Any]

get_features instance-attribute

get_features: Callable[..., Any]

get_flat_mlps instance-attribute

get_flat_mlps: Callable[..., Any]

MORLAXNetworks

Attributes:

Name Type Description
hypernetwork FeedForwardHypernetwork
policy_network FeedForwardNetwork
value_network FeedForwardNetwork
parametric_action_distribution ParametricDistribution
Source code in src/moplayground/moppo/factory.py
@flax.struct.dataclass
class MORLAXNetworks:
    hypernetwork                   : FeedForwardHypernetwork
    policy_network                 : networks.FeedForwardNetwork
    value_network                  : networks.FeedForwardNetwork
    parametric_action_distribution : distribution.ParametricDistribution

hypernetwork instance-attribute

policy_network instance-attribute

policy_network: FeedForwardNetwork

value_network instance-attribute

value_network: FeedForwardNetwork

parametric_action_distribution instance-attribute

parametric_action_distribution: ParametricDistribution

AMORNetworks

Attributes:

Name Type Description
policy_network FeedForwardNetwork
value_network FeedForwardNetwork
parametric_action_distribution ParametricDistribution
Source code in src/moplayground/moppo/factory.py
@flax.struct.dataclass
class AMORNetworks:
    policy_network                 : networks.FeedForwardNetwork
    value_network                  : networks.FeedForwardNetwork
    parametric_action_distribution : distribution.ParametricDistribution

policy_network instance-attribute

policy_network: FeedForwardNetwork

value_network instance-attribute

value_network: FeedForwardNetwork

parametric_action_distribution instance-attribute

parametric_action_distribution: ParametricDistribution

make_hypernetwork_inference_fn

make_hypernetwork_inference_fn(ppo_networks: MORLAXNetworks)

Creates params and inference function for the PPO agent.

Source code in src/moplayground/moppo/factory.py
def make_hypernetwork_inference_fn(ppo_networks: MORLAXNetworks):
    """Creates params and inference function for the PPO agent."""

    def hypernetwork_inference_fn(
        params: types.Params, tradeoff: jax.Array, single_policy: bool = False, deterministic: bool = False
    ) -> types.Policy:
        normalizer_params, hypernet_params = params
        policy_network = ppo_networks.policy_network
        policy_params = ppo_networks.hypernetwork.apply(hypernet_params, tradeoff)[0]

        if len(tradeoff.shape) == 1:
            policy_apply = policy_network.apply
        else:
            policy_apply = jax.vmap(policy_network.apply, in_axes=(None, 0, 0))
        parametric_action_distribution = ppo_networks.parametric_action_distribution


        def policy(
            observations: types.Observation, key_sample: PRNGKey
        ) -> Tuple[types.Action, types.Extra]:
            param_subset = (normalizer_params, policy_params)  # normalizer and policy params
            logits = policy_apply(*param_subset, observations)
            if deterministic:
                return ppo_networks.parametric_action_distribution.mode(logits), {}
            raw_actions = parametric_action_distribution.sample_no_postprocessing(
                logits, key_sample
            )
            log_prob = parametric_action_distribution.log_prob(logits, raw_actions)
            postprocessed_actions = parametric_action_distribution.postprocess(
                raw_actions
            )
            return postprocessed_actions, {
                'log_prob'   : log_prob,
                'raw_action' : raw_actions,
            }

        return policy

    return hypernetwork_inference_fn

make_morlax_networks

make_morlax_networks(observation_size: ObservationSize, action_size: int, num_objectives: int, hypersize: tuple, key: Array, target_policy_params: dict = None, target_value_params: dict = None, preprocess_observations_fn: PreprocessObservationFn = identity_observation_preprocessor, policy_hidden_layer_sizes: Sequence[int] = (32,) * 4, value_hidden_layer_sizes: Sequence[int] = (256,) * 5, activation: ActivationFn = swish, policy_obs_key: str = 'state', value_obs_key: str = 'state', distribution_type: Literal['normal', 'tanh_normal'] = 'tanh_normal', noise_std_type: Literal['scalar', 'log'] = 'scalar', init_noise_std: float = 1.0, state_dependent_std: bool = False, hypertype: str = 'MLP', num_features: int = 8) -> MORLAXNetworks

Make PPO networks with preprocessor.

Source code in src/moplayground/moppo/factory.py
def make_morlax_networks(
    observation_size          : types.ObservationSize,
    action_size               : int,
    num_objectives            : int,
    hypersize                 : tuple,
    key                       : jax.Array,
    target_policy_params      : dict = None,
    target_value_params       : dict = None,
    preprocess_observations_fn: types.PreprocessObservationFn = types.identity_observation_preprocessor,
    policy_hidden_layer_sizes : Sequence[int] = (32,) * 4,
    value_hidden_layer_sizes  : Sequence[int] = (256,) * 5,
    activation                : networks.ActivationFn = linen.swish,
    policy_obs_key            : str = 'state',
    value_obs_key             : str = 'state',
    distribution_type         : Literal['normal', 'tanh_normal'] = 'tanh_normal',
    noise_std_type            : Literal['scalar', 'log'] = 'scalar',
    init_noise_std            : float = 1.0,
    state_dependent_std       : bool = False,
    hypertype                 : str = 'MLP',
    num_features              : int = 8
) -> MORLAXNetworks:
    """Make PPO networks with preprocessor."""
    parametric_action_distribution: distribution.ParametricDistribution
    if distribution_type == 'normal':
        parametric_action_distribution = distribution.NormalDistribution(
            event_size=action_size
        )
    elif distribution_type == 'tanh_normal':
        parametric_action_distribution = distribution.NormalTanhDistribution(
            event_size=action_size
        )
    else:
        raise ValueError(
            f'Unsupported distribution type: {distribution_type}. Must be one'
            ' of "normal" or "tanh_normal".'
        )
    policy_network = networks.make_policy_network(
        param_size                 = parametric_action_distribution.param_size,
        obs_size                   = observation_size,
        preprocess_observations_fn = preprocess_observations_fn,
        hidden_layer_sizes         = policy_hidden_layer_sizes,
        activation                 = activation,
        obs_key                    = policy_obs_key,
        distribution_type          = distribution_type,
        noise_std_type             = noise_std_type,
        init_noise_std             = init_noise_std,
        state_dependent_std        = state_dependent_std,
        # layer_norm                 = True
    )

    value_network = networks.make_value_network(
        obs_size                   = observation_size,
        preprocess_observations_fn = preprocess_observations_fn,
        hidden_layer_sizes         = value_hidden_layer_sizes,
        activation                 = activation,
        obs_key                    = value_obs_key,
    )

    if target_policy_params is None:
        target_policy_params = policy_network.init(key)
    if target_value_params is None:
        target_value_params = value_network.init(key)

    hypernetwork = make_hypernetwork(
        observation_size   = observation_size,
        num_objectives     = num_objectives,
        target_policy_dict = target_policy_params,
        target_value_dict  = target_value_params,
        hypersize          = hypersize,
        hypertype          = hypertype,
        policy_obs_key     = policy_obs_key,
        num_features       = num_features
    )

    return MORLAXNetworks(
        hypernetwork                   = hypernetwork,
        policy_network                 = policy_network,
        value_network                  = value_network,
        parametric_action_distribution = parametric_action_distribution,
    )

make_hypernetwork

make_hypernetwork(observation_size: int, num_objectives: int, target_policy_dict: dict, hypersize: tuple, hypertype: str = 'MLP', policy_obs_key: str = 'state', num_features: int = 8, target_value_dict: dict = None)
Source code in src/moplayground/moppo/factory.py
def make_hypernetwork(
    observation_size   : int,
    num_objectives     : int,
    target_policy_dict : dict,
    hypersize          : tuple,
    hypertype          : str = 'MLP',
    policy_obs_key     : str = 'state',
    num_features       : int = 8,
    target_value_dict  : dict = None,
):
    obs_dim = networks._get_obs_state_size(observation_size, policy_obs_key)
    if hypertype == 'single':
        hypernet = ActorCriticHypernet(
            target_policy_dict = target_policy_dict,
            target_value_dict  = target_value_dict,
            num_objs           = num_objectives,
            obs_dim            = obs_dim,
            hypersize          = hypersize,
            num_features       = num_features
        )
    elif hypertype == 'dual':
        hypernet = DualA2CHypernet(
            target_policy_dict = target_policy_dict,
            target_value_dict  = target_value_dict,
            num_objs           = num_objectives,
            obs_dim            = obs_dim,
            hypersize          = hypersize,
            num_features       = num_features
        )
    else:
        raise Exception(f'Invalid hypertype {hypertype}. Must be "single" or "dual".')

    dummy_pref = jnp.zeros(num_objectives)
    def init(key):
        return hypernet.init(key, dummy_pref)

    def apply(params, prefs):
        if len(prefs.shape) == 1:
            prefs = prefs / jnp.sum(prefs)
        else:
            prefs = prefs / jnp.sum(prefs, axis=1)[:, jnp.newaxis]
        mlps, flat_mlps, features = hypernet.apply(params, prefs)
        return mlps, flat_mlps, features

    def get_mlps(params, prefs):
        return apply(params, prefs)[0]

    def get_flat_mlps(params, prefs):
        return apply(params, prefs)[1]

    def get_features(params, prefs):
        return apply(params, prefs)[2]

    wrapped_hypernet = FeedForwardHypernetwork(
        init            = init,
        apply           = get_mlps,
        get_flat_mlps = get_flat_mlps,
        get_features    = get_features
    )

    return wrapped_hypernet

make_amor_policy_network

make_amor_policy_network(param_size: int, obs_size: ObservationSize, num_objectives: int, preprocess_observations_fn: PreprocessObservationFn = identity_observation_preprocessor, hidden_layer_sizes: Sequence[int] = (256, 256), activation: ActivationFn = relu, kernel_init: Initializer = lecun_uniform(), layer_norm: bool = False, obs_key: str = 'state', distribution_type: Literal['normal', 'tanh_normal'] = 'tanh_normal', noise_std_type: Literal['scalar', 'log'] = 'scalar', init_noise_std: float = 1.0, state_dependent_std: bool = False) -> FeedForwardNetwork

AMOR policy network: input is concat(normalized_obs, raw_tradeoff).

Source code in src/moplayground/moppo/factory.py
def make_amor_policy_network(
    param_size                : int,
    obs_size                  : types.ObservationSize,
    num_objectives            : int,
    preprocess_observations_fn: types.PreprocessObservationFn = types.identity_observation_preprocessor,
    hidden_layer_sizes        : Sequence[int] = (256, 256),
    activation                : networks.ActivationFn = linen.relu,
    kernel_init               : Initializer = jax.nn.initializers.lecun_uniform(),
    layer_norm                : bool = False,
    obs_key                   : str = 'state',
    distribution_type         : Literal['normal', 'tanh_normal'] = 'tanh_normal',
    noise_std_type            : Literal['scalar', 'log'] = 'scalar',
    init_noise_std            : float = 1.0,
    state_dependent_std       : bool = False,
) -> networks.FeedForwardNetwork:
    """AMOR policy network: input is concat(normalized_obs, raw_tradeoff)."""
    if distribution_type == 'tanh_normal':
        policy_module = networks.MLP(
            layer_sizes = list(hidden_layer_sizes) + [param_size],
            activation  = activation,
            kernel_init = kernel_init,
            layer_norm  = layer_norm,
        )
    elif distribution_type == 'normal':
        policy_module = networks.PolicyModuleWithStd(
            param_size          = param_size,
            hidden_layer_sizes  = hidden_layer_sizes,
            activation          = activation,
            kernel_init         = kernel_init,
            layer_norm          = layer_norm,
            noise_std_type      = noise_std_type,
            init_noise_std      = init_noise_std,
            state_dependent_std = state_dependent_std,
        )
    else:
        raise ValueError(
            f'Unsupported distribution type: {distribution_type}. Must be one'
            ' of "normal" or "tanh_normal".'
        )

    def apply(processor_params, policy_params, obs, tradeoff):
        x = _amor_normalize_and_concat(
            obs, tradeoff, processor_params, preprocess_observations_fn, obs_key
        )
        return policy_module.apply(policy_params, x)

    obs_dim = networks._get_obs_state_size(obs_size, obs_key)
    augmented_dim = obs_dim + num_objectives
    dummy_input = jnp.zeros((1, augmented_dim))

    def init(key):
        return policy_module.init(key, dummy_input)

    return networks.FeedForwardNetwork(init=init, apply=apply)

make_amor_value_network

make_amor_value_network(obs_size: ObservationSize, num_objectives: int, preprocess_observations_fn: PreprocessObservationFn = identity_observation_preprocessor, hidden_layer_sizes: Sequence[int] = (256, 256), activation: ActivationFn = relu, obs_key: str = 'state') -> FeedForwardNetwork

AMOR value network: input is concat(normalized_obs, raw_tradeoff), output is a vector of length num_objectives — one expected return per objective. The tradeoff-scalarized advantage is formed in the loss.

Source code in src/moplayground/moppo/factory.py
def make_amor_value_network(
    obs_size                  : types.ObservationSize,
    num_objectives            : int,
    preprocess_observations_fn: types.PreprocessObservationFn = types.identity_observation_preprocessor,
    hidden_layer_sizes        : Sequence[int] = (256, 256),
    activation                : networks.ActivationFn = linen.relu,
    obs_key                   : str = 'state',
) -> networks.FeedForwardNetwork:
    """AMOR value network: input is concat(normalized_obs, raw_tradeoff),
    output is a vector of length ``num_objectives`` — one expected return per
    objective. The tradeoff-scalarized advantage is formed in the loss."""
    value_module = networks.MLP(
        layer_sizes = list(hidden_layer_sizes) + [num_objectives],
        activation  = activation,
        kernel_init = jax.nn.initializers.lecun_uniform(),
    )

    def apply(processor_params, value_params, obs, tradeoff):
        x = _amor_normalize_and_concat(
            obs, tradeoff, processor_params, preprocess_observations_fn, obs_key
        )
        return value_module.apply(value_params, x)

    obs_dim = networks._get_obs_state_size(obs_size, obs_key)
    augmented_dim = obs_dim + num_objectives
    dummy_input = jnp.zeros((1, augmented_dim))
    return networks.FeedForwardNetwork(
        init=lambda key: value_module.init(key, dummy_input), apply=apply
    )

make_amor_networks

make_amor_networks(observation_size: ObservationSize, action_size: int, num_objectives: int, key: Array, preprocess_observations_fn: PreprocessObservationFn = identity_observation_preprocessor, policy_hidden_layer_sizes: Sequence[int] = (64,) * 2, value_hidden_layer_sizes: Sequence[int] = (256,) * 5, activation: ActivationFn = swish, policy_obs_key: str = 'state', value_obs_key: str = 'state', distribution_type: Literal['normal', 'tanh_normal'] = 'tanh_normal', noise_std_type: Literal['scalar', 'log'] = 'scalar', init_noise_std: float = 1.0, state_dependent_std: bool = False) -> AMORNetworks

Make AMOR networks (tradeoff-conditioned policy + multi-objective value).

Unlike MORLAX (which uses a hypernetwork to output policy weights per tradeoff), AMOR's policy and value networks take the tradeoff as part of their input, concatenated to the (normalized) observation.

Source code in src/moplayground/moppo/factory.py
def make_amor_networks(
    observation_size          : types.ObservationSize,
    action_size               : int,
    num_objectives            : int,
    key                       : jax.Array,
    preprocess_observations_fn: types.PreprocessObservationFn = types.identity_observation_preprocessor,
    policy_hidden_layer_sizes : Sequence[int] = (64,) * 2,
    value_hidden_layer_sizes  : Sequence[int] = (256,) * 5,
    activation                : networks.ActivationFn = linen.swish,
    policy_obs_key            : str = 'state',
    value_obs_key             : str = 'state',
    distribution_type         : Literal['normal', 'tanh_normal'] = 'tanh_normal',
    noise_std_type            : Literal['scalar', 'log'] = 'scalar',
    init_noise_std            : float = 1.0,
    state_dependent_std       : bool = False,
) -> AMORNetworks:
    """Make AMOR networks (tradeoff-conditioned policy + multi-objective value).

    Unlike MORLAX (which uses a hypernetwork to output policy weights per tradeoff),
    AMOR's policy and value networks take the tradeoff as part of their input,
    concatenated to the (normalized) observation.
    """
    if distribution_type == 'normal':
        parametric_action_distribution = distribution.NormalDistribution(
            event_size=action_size
        )
    elif distribution_type == 'tanh_normal':
        parametric_action_distribution = distribution.NormalTanhDistribution(
            event_size=action_size
        )
    else:
        raise ValueError(
            f'Unsupported distribution type: {distribution_type}. Must be one'
            ' of "normal" or "tanh_normal".'
        )

    policy_network = make_amor_policy_network(
        param_size                 = parametric_action_distribution.param_size,
        obs_size                   = observation_size,
        num_objectives             = num_objectives,
        preprocess_observations_fn = preprocess_observations_fn,
        hidden_layer_sizes         = policy_hidden_layer_sizes,
        activation                 = activation,
        obs_key                    = policy_obs_key,
        distribution_type          = distribution_type,
        noise_std_type             = noise_std_type,
        init_noise_std             = init_noise_std,
        state_dependent_std        = state_dependent_std,
    )

    value_network = make_amor_value_network(
        obs_size                   = observation_size,
        num_objectives             = num_objectives,
        preprocess_observations_fn = preprocess_observations_fn,
        hidden_layer_sizes         = value_hidden_layer_sizes,
        activation                 = activation,
        obs_key                    = value_obs_key,
    )

    return AMORNetworks(
        policy_network                 = policy_network,
        value_network                  = value_network,
        parametric_action_distribution = parametric_action_distribution,
    )

make_amor_inference_fn

make_amor_inference_fn(amor_networks: AMORNetworks)

Creates an inference function for AMOR.

Returned closure: amor_inference_fn(params, deterministic=False) -> policy(obs, tradeoff, key). Unlike MORLAX's hypernetwork_inference_fn (which bakes the tradeoff into the closure at construction), AMOR's policy takes the tradeoff at call time, so the tradeoff can be changed at any step without rebuilding the policy.

Source code in src/moplayground/moppo/factory.py
def make_amor_inference_fn(amor_networks: AMORNetworks):
    """Creates an inference function for AMOR.

    Returned closure: ``amor_inference_fn(params, deterministic=False) -> policy(obs, tradeoff, key)``.
    Unlike MORLAX's ``hypernetwork_inference_fn`` (which bakes the tradeoff into the
    closure at construction), AMOR's policy takes the tradeoff at call time, so the
    tradeoff can be changed at any step without rebuilding the policy.
    """

    def amor_inference_fn(
        params: types.Params, deterministic: bool = False
    ) -> Callable:
        normalizer_params, policy_params = params
        dist = amor_networks.parametric_action_distribution

        def policy(
            observations: types.Observation,
            tradeoff: jax.Array,
            key_sample: jax.Array,
        ) -> Tuple[types.Action, types.Extra]:
            logits = amor_networks.policy_network.apply(
                normalizer_params, policy_params, observations, tradeoff
            )
            if deterministic:
                return dist.mode(logits), {}
            raw_actions = dist.sample_no_postprocessing(logits, key_sample)
            log_prob = dist.log_prob(logits, raw_actions)
            postprocessed_actions = dist.postprocess(raw_actions)
            return postprocessed_actions, {
                'log_prob'   : log_prob,
                'raw_action' : raw_actions,
            }

        return policy

    return amor_inference_fn

moplayground.moppo.acting

Brax training acting functions.

Classes:

Name Description
MultiObjectiveTransition

Container for a transition.

Evaluator

Class to run evaluations.

Functions:

Name Description
actor_step

Collect data.

generate_unroll

Collect trajectories of given unroll_length.

Attributes:

Name Type Description
State
Env

State module-attribute

State = envs.State

Env module-attribute

Env = envs.Env

MultiObjectiveTransition

Bases: NamedTuple

Container for a transition.

Attributes:

Name Type Description
observation NestedArray
action NestedArray
reward NestedArray
tradeoff NestedArray
discount NestedArray
next_observation NestedArray
extras NestedArray
Source code in src/moplayground/moppo/acting.py
class MultiObjectiveTransition(NamedTuple):
    """Container for a transition."""

    observation: NestedArray
    action: NestedArray
    reward: NestedArray
    tradeoff: NestedArray
    discount: NestedArray
    next_observation: NestedArray
    extras: NestedArray = ()  # pytype: disable=annotation-type-mismatch  # jax-ndarray

observation instance-attribute

observation: NestedArray

action instance-attribute

action: NestedArray

reward instance-attribute

reward: NestedArray

tradeoff instance-attribute

tradeoff: NestedArray

discount instance-attribute

discount: NestedArray

next_observation instance-attribute

next_observation: NestedArray

extras class-attribute instance-attribute

extras: NestedArray = ()

Evaluator

Class to run evaluations.

Methods:

Name Description
run_evaluation

Run one epoch of evaluation.

Attributes:

Name Type Description
num_eval_envs
num_objs
Source code in src/moplayground/moppo/acting.py
class Evaluator:
    """Class to run evaluations."""

    def __init__(
        self,
        eval_env: envs.Env,
        num_objs: int,
        eval_policy_fn,
        num_eval_envs: int,
        episode_length: int,
        action_repeat: int,
        key: PRNGKey,
    ):
        self._key = key
        self._eval_walltime = 0.0

        eval_env = MultiObjectiveEvalWrapper(eval_env)

        def generate_eval_unroll(
            policy_params, key: PRNGKey, tradeoffs
        ) -> State:
            reset_keys = jax.random.split(key, num_eval_envs)
            eval_first_state = eval_env.reset(reset_keys)
            return generate_unroll(
                eval_env,
                eval_first_state,
                eval_policy_fn(policy_params, tradeoffs),
                tradeoffs,
                key,
                unroll_length=episode_length // action_repeat,
            )[0]

        self._generate_eval_unroll = jax.jit(generate_eval_unroll)
        self._steps_per_unroll = episode_length * num_eval_envs
        self.num_eval_envs = num_eval_envs
        self.num_objs = num_objs

    def run_evaluation(
        self,
        policy_params,
        training_metrics: Metrics,
        aggregate_episodes: bool = True,
    ) -> Metrics:
        """Run one epoch of evaluation."""
        self._key, unroll_key = jax.random.split(self._key)

        t = time.time()
        _, w_key = jax.random.split(self._key)
        tradeoffs = jax.random.dirichlet(key=w_key, alpha=jnp.ones(self.num_objs), shape=self.num_eval_envs)
        # tradeoffs = jnp.ones((self.num_eval_envs, self.num_objs)) / self.num_objs
        eval_state = self._generate_eval_unroll(policy_params, unroll_key, tradeoffs)
        eval_metrics = eval_state.info['eval_metrics']
        eval_metrics.active_episodes.block_until_ready()
        epoch_eval_time = time.time() - t
        metrics = {}
        # for fn in [np.mean, np.std]:
        #     suffix = '_std' if fn == np.std else ''
        #     metrics.update({
        #         f'eval/episode_{name}{suffix}': (
        #             fn(value, axis=0) if aggregate_episodes else value
        #         )
        #         for name, value in eval_metrics.episode_metrics.items()
        #     })
        # metrics['eval/avg_episode_length'] = np.mean(eval_metrics.episode_steps)
        # metrics['eval/std_episode_length'] = np.std(eval_metrics.episode_steps)
        # metrics['eval/epoch_eval_time'] = epoch_eval_time
        # metrics['eval/sps'] = self._steps_per_unroll / epoch_eval_time
        # self._eval_walltime = self._eval_walltime + epoch_eval_time
        # metrics = {
        #     'eval/walltime': self._eval_walltime,
        #     **training_metrics,
        #     **metrics,
        # }
        metrics = eval_metrics.episode_metrics
        metrics['tradeoff'] = tradeoffs

        return metrics  # pytype: disable=bad-return-type  # jax-ndarray

num_eval_envs instance-attribute

num_eval_envs = num_eval_envs

num_objs instance-attribute

num_objs = num_objs

run_evaluation

run_evaluation(policy_params, training_metrics: Metrics, aggregate_episodes: bool = True) -> Metrics

Run one epoch of evaluation.

Source code in src/moplayground/moppo/acting.py
def run_evaluation(
    self,
    policy_params,
    training_metrics: Metrics,
    aggregate_episodes: bool = True,
) -> Metrics:
    """Run one epoch of evaluation."""
    self._key, unroll_key = jax.random.split(self._key)

    t = time.time()
    _, w_key = jax.random.split(self._key)
    tradeoffs = jax.random.dirichlet(key=w_key, alpha=jnp.ones(self.num_objs), shape=self.num_eval_envs)
    # tradeoffs = jnp.ones((self.num_eval_envs, self.num_objs)) / self.num_objs
    eval_state = self._generate_eval_unroll(policy_params, unroll_key, tradeoffs)
    eval_metrics = eval_state.info['eval_metrics']
    eval_metrics.active_episodes.block_until_ready()
    epoch_eval_time = time.time() - t
    metrics = {}
    # for fn in [np.mean, np.std]:
    #     suffix = '_std' if fn == np.std else ''
    #     metrics.update({
    #         f'eval/episode_{name}{suffix}': (
    #             fn(value, axis=0) if aggregate_episodes else value
    #         )
    #         for name, value in eval_metrics.episode_metrics.items()
    #     })
    # metrics['eval/avg_episode_length'] = np.mean(eval_metrics.episode_steps)
    # metrics['eval/std_episode_length'] = np.std(eval_metrics.episode_steps)
    # metrics['eval/epoch_eval_time'] = epoch_eval_time
    # metrics['eval/sps'] = self._steps_per_unroll / epoch_eval_time
    # self._eval_walltime = self._eval_walltime + epoch_eval_time
    # metrics = {
    #     'eval/walltime': self._eval_walltime,
    #     **training_metrics,
    #     **metrics,
    # }
    metrics = eval_metrics.episode_metrics
    metrics['tradeoff'] = tradeoffs

    return metrics  # pytype: disable=bad-return-type  # jax-ndarray

actor_step

actor_step(env: Env, env_state: State, policy: Policy, tradeoff, key: PRNGKey, extra_fields: Sequence[str] = ()) -> Tuple[State, MultiObjectiveTransition]

Collect data.

Source code in src/moplayground/moppo/acting.py
def actor_step(
    env: Env,
    env_state: State,
    policy: Policy,
    tradeoff,
    key: PRNGKey,
    extra_fields: Sequence[str] = (),
) -> Tuple[State, MultiObjectiveTransition]:
    """Collect data."""
    actions, policy_extras = policy(env_state.obs, key)
    nstate = env.step(env_state, actions)
    state_extras = {x: nstate.info[x] for x in extra_fields}
    return nstate, MultiObjectiveTransition(  # pytype: disable=wrong-arg-types  # jax-ndarray
        observation=env_state.obs,
        action=actions,
        reward=nstate.reward,
        tradeoff=tradeoff.copy(),
        discount=1 - nstate.done,
        next_observation=nstate.obs,
        extras={'policy_extras': policy_extras, 'state_extras': state_extras},
    )

generate_unroll

generate_unroll(env: Env, env_state: State, policy: Policy, tradeoff: Array, key: PRNGKey, unroll_length: int, extra_fields: Sequence[str] = ()) -> Tuple[State, MultiObjectiveTransition]

Collect trajectories of given unroll_length.

Source code in src/moplayground/moppo/acting.py
def generate_unroll(
    env: Env,
    env_state: State,
    policy: Policy,
    tradeoff: jax.Array,
    key: PRNGKey,
    unroll_length: int,
    extra_fields: Sequence[str] = (),
) -> Tuple[State, MultiObjectiveTransition]:
    """Collect trajectories of given unroll_length."""

    @jax.jit
    def f(carry, unused_t):
        state, current_key = carry
        current_key, next_key = jax.random.split(current_key)
        nstate, transition = actor_step(
            env, state, policy, tradeoff, current_key, extra_fields=extra_fields
        )
        return (nstate, next_key), transition

    (final_state, _), data = jax.lax.scan(
        f, (env_state, key), (), length=unroll_length
    )
    return final_state, data

moplayground.moppo.networks

Classes:

Name Description
MLP
Hypernet
HypernetMLP
FakeHypernet
ActorCriticHypernet
DualA2CHypernet

Functions:

Name Description
flatten_model
count_params

Count the total number of parameters in a Flax model.

MLP

Bases: Module

Attributes:

Name Type Description
obs_dim int
hidden_sizes Sequence[int]
action_dim int
Source code in src/moplayground/moppo/networks.py
class MLP(nn.Module):
    obs_dim: int                
    hidden_sizes: Sequence[int] 
    action_dim: int             

    @nn.compact
    def __call__(self, x):
        x = x.reshape(-1, self.obs_dim)

        # Hidden layers
        for h in self.hidden_sizes:
            # x = nn.LayerNorm()(x)
            x = nn.Dense(h)(x)
            x = nn.swish(x)

        # Output layer
        x = nn.Dense(self.action_dim)(x)
        return x

obs_dim instance-attribute

obs_dim: int

hidden_sizes instance-attribute

hidden_sizes: Sequence[int]

action_dim instance-attribute

action_dim: int

Hypernet

Bases: Module

Methods:

Name Description
setup

Attributes:

Name Type Description
target_model_dict Module
num_objs int
obs_dim int
hypersize tuple
num_features int
W_variance float
Source code in src/moplayground/moppo/networks.py
class Hypernet(nn.Module):
    target_model_dict: nn.Module
    num_objs: int
    obs_dim: int
    hypersize: tuple
    num_features: int = 8
    W_variance: float = 0.0

    def setup(self):
        # Init target policy params
        target_params = self.target_model_dict['params']

        num_params = 0
        target_policy_info = []

        _, num_params, target_policy_info = flatten_model(target_params)

        # Save as immutable attributes
        self.target_policy_info = tuple(target_policy_info)
        self.num_params = num_params

        # Hypernetwork MLP
        self.pref_mlp = MLP(
            obs_dim      = self.num_objs,
            hidden_sizes = self.hypersize,
            action_dim   = self.num_features
        )

        flat_init, num_params, target_policy_info = flatten_model(target_params)
        # print(target_policy_info)
        # target_policy_info = [('hidden_0/bias', (64,)), ('hidden_0/kernel', (17, 64)), ('hidden_1/bias', (64,)), ('hidden_1/kernel', (64, 64)), ('hidden_2/bias', (12,)), ('hidden_2/kernel', (64, 12))]


        self.target_policy_info = tuple(target_policy_info)
        self.num_params = num_params

        # Hypernet params
        self.W = self.param(
            "W",
            lambda key: (
                jax.random.uniform(key, (self.num_features, self.num_params), minval=-1, maxval=1)
                * self.W_variance
            ),
        )
        self.b = self.param("b", lambda key: flat_init)

    def __call__(self, pref, single=False):
        features = self.pref_mlp(pref)  # (..., num_features)
        flat_params = jnp.dot(features, self.W) + self.b  # (..., num_params)

        # Reshape back into dict
        sorted_params = {}
        cnt = 0
        for name, shape in self.target_policy_info:
            size = np.prod(shape)
            sorted_params[name] = flat_params[..., cnt:cnt+size].reshape((-1,) + shape)
            cnt += size

        nested_params = traverse_util.unflatten_dict({
            tuple(k.split("/")): v if not single else v[0] for k, v in sorted_params.items()
        })
        nested_params = FrozenDict(nested_params)

        # Wrap under "params" collection for Flax
        return flat_params, {"params": nested_params}

target_model_dict instance-attribute

target_model_dict: Module

num_objs instance-attribute

num_objs: int

obs_dim instance-attribute

obs_dim: int

hypersize instance-attribute

hypersize: tuple

num_features class-attribute instance-attribute

num_features: int = 8

W_variance class-attribute instance-attribute

W_variance: float = 0.0

setup

setup()
Source code in src/moplayground/moppo/networks.py
def setup(self):
    # Init target policy params
    target_params = self.target_model_dict['params']

    num_params = 0
    target_policy_info = []

    _, num_params, target_policy_info = flatten_model(target_params)

    # Save as immutable attributes
    self.target_policy_info = tuple(target_policy_info)
    self.num_params = num_params

    # Hypernetwork MLP
    self.pref_mlp = MLP(
        obs_dim      = self.num_objs,
        hidden_sizes = self.hypersize,
        action_dim   = self.num_features
    )

    flat_init, num_params, target_policy_info = flatten_model(target_params)
    # print(target_policy_info)
    # target_policy_info = [('hidden_0/bias', (64,)), ('hidden_0/kernel', (17, 64)), ('hidden_1/bias', (64,)), ('hidden_1/kernel', (64, 64)), ('hidden_2/bias', (12,)), ('hidden_2/kernel', (64, 12))]


    self.target_policy_info = tuple(target_policy_info)
    self.num_params = num_params

    # Hypernet params
    self.W = self.param(
        "W",
        lambda key: (
            jax.random.uniform(key, (self.num_features, self.num_params), minval=-1, maxval=1)
            * self.W_variance
        ),
    )
    self.b = self.param("b", lambda key: flat_init)

HypernetMLP

Bases: Module

Methods:

Name Description
setup

Attributes:

Name Type Description
target_model_dict dict
num_objs int
obs_dim int
hypersize tuple
Source code in src/moplayground/moppo/networks.py
class HypernetMLP(nn.Module):
    target_model_dict: dict
    num_objs: int
    obs_dim: int
    hypersize: tuple

    def setup(self):
        # Init target policy params
        target_params = self.target_model_dict['params']

        num_params = 0
        target_policy_info = []

        _, num_params, target_policy_info = flatten_model(target_params)

        # Save as immutable attributes
        self.target_policy_info = tuple(target_policy_info)
        self.num_params = num_params

        # Hypernetwork MLP
        self.mlp = MLP(
            obs_dim      = self.num_objs,
            hidden_sizes = self.hypersize,
            action_dim   = self.num_params
        )

    def __call__(self, pref, single=False):
        flat_params = self.mlp(pref)

        # Reshape back into dict
        sorted_params = {}
        cnt = 0
        for name, shape in self.target_policy_info:
            size = np.prod(shape)
            sorted_params[name] = flat_params[..., cnt:cnt+size].reshape((-1,) + shape)
            cnt += size

        nested_params = traverse_util.unflatten_dict({
            tuple(k.split("/")): v if not single else v[0] for k, v in sorted_params.items()
        })
        nested_params = FrozenDict(nested_params)

        # Wrap under "params" collection for Flax
        return flat_params, {"params": nested_params}

target_model_dict instance-attribute

target_model_dict: dict

num_objs instance-attribute

num_objs: int

obs_dim instance-attribute

obs_dim: int

hypersize instance-attribute

hypersize: tuple

setup

setup()
Source code in src/moplayground/moppo/networks.py
def setup(self):
    # Init target policy params
    target_params = self.target_model_dict['params']

    num_params = 0
    target_policy_info = []

    _, num_params, target_policy_info = flatten_model(target_params)

    # Save as immutable attributes
    self.target_policy_info = tuple(target_policy_info)
    self.num_params = num_params

    # Hypernetwork MLP
    self.mlp = MLP(
        obs_dim      = self.num_objs,
        hidden_sizes = self.hypersize,
        action_dim   = self.num_params
    )

FakeHypernet

Bases: Module

Methods:

Name Description
setup

Attributes:

Name Type Description
target_model_dict dict
num_objs int
obs_dim int
hypersize tuple
Source code in src/moplayground/moppo/networks.py
class FakeHypernet(nn.Module):
    target_model_dict: dict
    num_objs: int
    obs_dim: int
    hypersize: tuple

    def setup(self):
        # Init target policy params
        target_params = self.target_model_dict['params']

        num_params = 0
        target_policy_info = []

        flat_params, num_params, target_policy_info = flatten_model(target_params)

        # Save as immutable attributes
        self.target_policy_info = tuple(target_policy_info)
        self.num_params = num_params
        self.flat_params = self.param(
            'flat_params',
            lambda key: flat_params
        )

    def __call__(self, pref, single=False):
        flat_params = self.flat_params
        if not single:
            flat_params = jnp.repeat(
                flat_params[jnp.newaxis, :], 
                pref.shape[0], 
                axis=0
            )

        # Reshape back into dict
        sorted_params = {}
        cnt = 0
        for name, shape in self.target_policy_info:
            size = np.prod(shape)
            sorted_params[name] = flat_params[..., cnt:cnt+size].reshape((-1,) + shape)
            cnt += size

        nested_params = traverse_util.unflatten_dict({
            tuple(k.split("/")): v if not single else v[0] for k, v in sorted_params.items()
        })
        nested_params = FrozenDict(nested_params)

        # Wrap under "params" collection for Flax
        return flat_params, {"params": nested_params}

target_model_dict instance-attribute

target_model_dict: dict

num_objs instance-attribute

num_objs: int

obs_dim instance-attribute

obs_dim: int

hypersize instance-attribute

hypersize: tuple

setup

setup()
Source code in src/moplayground/moppo/networks.py
def setup(self):
    # Init target policy params
    target_params = self.target_model_dict['params']

    num_params = 0
    target_policy_info = []

    flat_params, num_params, target_policy_info = flatten_model(target_params)

    # Save as immutable attributes
    self.target_policy_info = tuple(target_policy_info)
    self.num_params = num_params
    self.flat_params = self.param(
        'flat_params',
        lambda key: flat_params
    )

ActorCriticHypernet

Bases: Module

Methods:

Name Description
setup
unflatten_params

Attributes:

Name Type Description
target_policy_dict dict
target_value_dict dict
num_objs int
obs_dim int
hypersize tuple
num_features int
W_variance float
Source code in src/moplayground/moppo/networks.py
class ActorCriticHypernet(nn.Module):
    target_policy_dict: dict
    target_value_dict: dict
    num_objs: int
    obs_dim: int
    hypersize: tuple = (128, 128)
    num_features: int = 8
    W_variance: float = 0.0

    def setup(self):
        # Init target policy params
        target_policy_params = self.target_policy_dict['params']
        target_value_params  = self.target_value_dict['params']

        target_policy_info = []
        target_value_info  = []

        policy_flat_init, num_policy_params, target_policy_info = flatten_model(target_policy_params)
        value_flat_init, num_value_params, target_value_info    = flatten_model(target_value_params)

        # Save as immutable attributes
        self.target_policy_info = tuple(target_policy_info)
        self.target_value_info  = tuple(target_value_info)
        self.num_policy_params  = num_policy_params
        self.num_value_params   = num_value_params
        self.num_params         = num_policy_params + num_value_params

        # Hypernetwork MLP
        self.mlp = MLP(
            obs_dim      = self.num_objs,
            hidden_sizes = self.hypersize,
            action_dim   = self.num_features
        )

        # Hypernet params
        self.W = self.param(
            "W",
            lambda key: (
                jax.random.uniform(key, (self.num_features, self.num_params), minval=-1, maxval=1)
                * self.W_variance
            ),
        )
        self.b = self.param(
            "b",
            lambda key: jnp.hstack((policy_flat_init, value_flat_init))
        )

    def unflatten_params(self, flat_params, target_network, single):
        # Reshape back into dict
        sorted_params = {}
        cnt = 0
        for name, shape in target_network:
            size = np.prod(shape)
            sorted_params[name] = flat_params[..., cnt:cnt+size].reshape((-1,) + shape)
            cnt += size

        nested_params = traverse_util.unflatten_dict({
            tuple(k.split("/")): v if not single else v[0] for k, v in sorted_params.items()
        })
        nested_params = FrozenDict(nested_params)

        # Wrap under "params" collection for Flax
        return {"params": nested_params}

    def __call__(self, pref):
        single = len(pref.shape) == 1
        features = self.mlp(pref)
        flat_params = jnp.dot(features, self.W) + self.b

        policy_flat_params = flat_params[..., :self.num_policy_params]
        policy_sort_params = self.unflatten_params(
            flat_params    = policy_flat_params,
            target_network = self.target_policy_info,
            single         = single
        )

        value_flat_params  = flat_params[..., -self.num_value_params:]
        value_sort_params  = self.unflatten_params(
            flat_params    = value_flat_params,
            target_network = self.target_value_info,
            single         = single
        )

        return ((policy_sort_params, value_sort_params),
                (policy_flat_params, value_flat_params),
                features)

target_policy_dict instance-attribute

target_policy_dict: dict

target_value_dict instance-attribute

target_value_dict: dict

num_objs instance-attribute

num_objs: int

obs_dim instance-attribute

obs_dim: int

hypersize class-attribute instance-attribute

hypersize: tuple = (128, 128)

num_features class-attribute instance-attribute

num_features: int = 8

W_variance class-attribute instance-attribute

W_variance: float = 0.0

setup

setup()
Source code in src/moplayground/moppo/networks.py
def setup(self):
    # Init target policy params
    target_policy_params = self.target_policy_dict['params']
    target_value_params  = self.target_value_dict['params']

    target_policy_info = []
    target_value_info  = []

    policy_flat_init, num_policy_params, target_policy_info = flatten_model(target_policy_params)
    value_flat_init, num_value_params, target_value_info    = flatten_model(target_value_params)

    # Save as immutable attributes
    self.target_policy_info = tuple(target_policy_info)
    self.target_value_info  = tuple(target_value_info)
    self.num_policy_params  = num_policy_params
    self.num_value_params   = num_value_params
    self.num_params         = num_policy_params + num_value_params

    # Hypernetwork MLP
    self.mlp = MLP(
        obs_dim      = self.num_objs,
        hidden_sizes = self.hypersize,
        action_dim   = self.num_features
    )

    # Hypernet params
    self.W = self.param(
        "W",
        lambda key: (
            jax.random.uniform(key, (self.num_features, self.num_params), minval=-1, maxval=1)
            * self.W_variance
        ),
    )
    self.b = self.param(
        "b",
        lambda key: jnp.hstack((policy_flat_init, value_flat_init))
    )

unflatten_params

unflatten_params(flat_params, target_network, single)
Source code in src/moplayground/moppo/networks.py
def unflatten_params(self, flat_params, target_network, single):
    # Reshape back into dict
    sorted_params = {}
    cnt = 0
    for name, shape in target_network:
        size = np.prod(shape)
        sorted_params[name] = flat_params[..., cnt:cnt+size].reshape((-1,) + shape)
        cnt += size

    nested_params = traverse_util.unflatten_dict({
        tuple(k.split("/")): v if not single else v[0] for k, v in sorted_params.items()
    })
    nested_params = FrozenDict(nested_params)

    # Wrap under "params" collection for Flax
    return {"params": nested_params}

DualA2CHypernet

Bases: Module

Methods:

Name Description
setup
unflatten_params

Attributes:

Name Type Description
target_policy_dict dict
target_value_dict dict
num_objs int
obs_dim int
hypersize tuple
num_features int
W_variance float
Source code in src/moplayground/moppo/networks.py
class DualA2CHypernet(nn.Module):
    target_policy_dict: dict
    target_value_dict: dict
    num_objs: int
    obs_dim: int
    hypersize: tuple = (128, 128)
    num_features: int = 8
    W_variance: float = 0.0

    def setup(self):
        # Init target policy params
        target_policy_params = self.target_policy_dict['params']
        target_value_params  = self.target_value_dict['params']

        target_policy_info = []
        target_value_info  = []

        policy_flat_init, num_policy_params, target_policy_info = flatten_model(target_policy_params)
        value_flat_init, num_value_params, target_value_info    = flatten_model(target_value_params)

        # Save as immutable attributes
        self.target_policy_info = tuple(target_policy_info)
        self.target_value_info  = tuple(target_value_info)
        self.num_policy_params  = num_policy_params
        self.num_value_params   = num_value_params

        # Hypernetwork MLP
        self.policy_mlp = MLP(
            obs_dim      = self.num_objs,
            hidden_sizes = self.hypersize,
            action_dim   = self.num_features
        )
        self.value_mlp = MLP(
            obs_dim      = self.num_objs,
            hidden_sizes = self.hypersize,
            action_dim   = self.num_features
        )

        # Hypernet params
        self.policy_W = self.param(
            "policy_W",
            lambda key: (
                jax.random.uniform(key, (self.num_features, self.num_policy_params), minval=-1, maxval=1)
                * self.W_variance
            ),
        )
        self.policy_b = self.param(
            "policy_b",
            lambda key: policy_flat_init
        )

        # Hypernet params
        self.value_W = self.param(
            "value_W",
            lambda key: (
                jax.random.uniform(key, (self.num_features, self.num_value_params), minval=-1, maxval=1)
                * self.W_variance
            ),
        )
        self.value_b = self.param(
            "value_b",
            lambda key: value_flat_init
        )

    def unflatten_params(self, flat_params, target_network, single):
        # Reshape back into dict
        sorted_params = {}
        cnt = 0
        for name, shape in target_network:
            size = np.prod(shape)
            sorted_params[name] = flat_params[..., cnt:cnt+size].reshape((-1,) + shape)
            cnt += size

        nested_params = traverse_util.unflatten_dict({
            tuple(k.split("/")): v if not single else v[0] for k, v in sorted_params.items()
        })
        nested_params = FrozenDict(nested_params)

        # Wrap under "params" collection for Flax
        return {"params": nested_params}

    def __call__(self, pref):
        policy_features = self.policy_mlp(pref)
        value_features  = self.value_mlp(pref)
        policy_flat_params = jnp.dot(policy_features, self.policy_W) + self.policy_b
        value_flat_params  = jnp.dot(value_features,  self.value_W) + self.value_b

        policy_sort_params = self.unflatten_params(
            flat_params    = policy_flat_params,
            target_network = self.target_policy_info,
            single         = len(pref.shape) == 1
        )

        value_sort_params  = self.unflatten_params(
            flat_params    = value_flat_params,
            target_network = self.target_value_info,
            single         = len(pref.shape) == 1
        )

        return ((policy_sort_params, value_sort_params),
                (policy_flat_params, value_flat_params),
                (policy_features, value_features))

target_policy_dict instance-attribute

target_policy_dict: dict

target_value_dict instance-attribute

target_value_dict: dict

num_objs instance-attribute

num_objs: int

obs_dim instance-attribute

obs_dim: int

hypersize class-attribute instance-attribute

hypersize: tuple = (128, 128)

num_features class-attribute instance-attribute

num_features: int = 8

W_variance class-attribute instance-attribute

W_variance: float = 0.0

setup

setup()
Source code in src/moplayground/moppo/networks.py
def setup(self):
    # Init target policy params
    target_policy_params = self.target_policy_dict['params']
    target_value_params  = self.target_value_dict['params']

    target_policy_info = []
    target_value_info  = []

    policy_flat_init, num_policy_params, target_policy_info = flatten_model(target_policy_params)
    value_flat_init, num_value_params, target_value_info    = flatten_model(target_value_params)

    # Save as immutable attributes
    self.target_policy_info = tuple(target_policy_info)
    self.target_value_info  = tuple(target_value_info)
    self.num_policy_params  = num_policy_params
    self.num_value_params   = num_value_params

    # Hypernetwork MLP
    self.policy_mlp = MLP(
        obs_dim      = self.num_objs,
        hidden_sizes = self.hypersize,
        action_dim   = self.num_features
    )
    self.value_mlp = MLP(
        obs_dim      = self.num_objs,
        hidden_sizes = self.hypersize,
        action_dim   = self.num_features
    )

    # Hypernet params
    self.policy_W = self.param(
        "policy_W",
        lambda key: (
            jax.random.uniform(key, (self.num_features, self.num_policy_params), minval=-1, maxval=1)
            * self.W_variance
        ),
    )
    self.policy_b = self.param(
        "policy_b",
        lambda key: policy_flat_init
    )

    # Hypernet params
    self.value_W = self.param(
        "value_W",
        lambda key: (
            jax.random.uniform(key, (self.num_features, self.num_value_params), minval=-1, maxval=1)
            * self.W_variance
        ),
    )
    self.value_b = self.param(
        "value_b",
        lambda key: value_flat_init
    )

unflatten_params

unflatten_params(flat_params, target_network, single)
Source code in src/moplayground/moppo/networks.py
def unflatten_params(self, flat_params, target_network, single):
    # Reshape back into dict
    sorted_params = {}
    cnt = 0
    for name, shape in target_network:
        size = np.prod(shape)
        sorted_params[name] = flat_params[..., cnt:cnt+size].reshape((-1,) + shape)
        cnt += size

    nested_params = traverse_util.unflatten_dict({
        tuple(k.split("/")): v if not single else v[0] for k, v in sorted_params.items()
    })
    nested_params = FrozenDict(nested_params)

    # Wrap under "params" collection for Flax
    return {"params": nested_params}

flatten_model

flatten_model(target_params)
Source code in src/moplayground/moppo/networks.py
def flatten_model(target_params):
    flat_params_list = []
    num_params = 0
    target_policy_info = []

    def flatten_dict(d, prefix=""):
        items = []
        for k, v in d.items():
            if isinstance(v, (dict, FrozenDict)):
                items.extend(flatten_dict(v, prefix + k + "/"))
            else:
                items.append((prefix + k, v))
        items.sort()
        return items

    for name, param in flatten_dict(target_params):
        shape = param.shape
        target_policy_info.append((name, shape))
        num_params += np.prod(shape)
        flat_params_list.append(param.reshape(-1))

    flat_init = jnp.concatenate(flat_params_list)

    return flat_init, num_params, target_policy_info

count_params

count_params(params)

Count the total number of parameters in a Flax model.

Source code in src/moplayground/moppo/networks.py
def count_params(params):
    """Count the total number of parameters in a Flax model."""
    return sum(jnp.size(p) for p in jax.tree_util.tree_leaves(params))