|
| 1 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 | +# |
| 3 | +# This source code is licensed under the MIT license found in the |
| 4 | +# LICENSE file in the root directory of this source tree. |
| 5 | + |
| 6 | +""" |
| 7 | +Updating MPS weights in multiprocess/distributed data collectors |
| 8 | +================================================================ |
| 9 | +
|
| 10 | +Overview of the Script |
| 11 | +---------------------- |
| 12 | +
|
| 13 | +This script demonstrates a weight update in TorchRL. |
| 14 | +The script uses a custom `MPSRemoteWeightUpdater` class to update the weights of a policy network across multiple workers. |
| 15 | +
|
| 16 | +Key Features |
| 17 | +------------ |
| 18 | +
|
| 19 | +- Multi-Worker Setup: The script creates two worker processes that collect data from a Gym environment |
| 20 | + ("Pendulum-v1") using a policy network. |
| 21 | +- MPS (Metal Performance Shaders) Device: The policy network is placed on an MPS device. |
| 22 | +- Custom Weight Updater: The `MPSRemoteWeightUpdater` class is used to update the policy weights across workers. This |
| 23 | + class is necessary because MPS tensors cannot be sent over a pipe due to serialization/pickling issues in PyTorch. |
| 24 | +
|
| 25 | +Workaround for MPS Tensor Serialization Issue |
| 26 | +--------------------------------------------- |
| 27 | +
|
| 28 | +In PyTorch, MPS tensors cannot be serialized or pickled, which means they cannot be sent over a pipe or shared between |
| 29 | +processes. To work around this issue, the MPSRemoteWeightUpdater class sends the policy weights on the CPU device |
| 30 | +instead of the MPS device. The local workers then copy the weights from the CPU device to the MPS device. |
| 31 | +
|
| 32 | +Script Flow |
| 33 | +----------- |
| 34 | +
|
| 35 | +1. Initialize the environment, policy network, and collector. |
| 36 | +2. Update the policy weights using the MPSRemoteWeightUpdater. |
| 37 | +3. Collect data from the environment using the policy network. |
| 38 | +4. Zero out the policy weights after a few iterations. |
| 39 | +5. Verify that the updated policy weights are being used by checking the actions generated by the policy network. |
| 40 | +
|
| 41 | +""" |
| 42 | + |
| 43 | +import tensordict |
| 44 | +import torch |
| 45 | +from tensordict import TensorDictBase |
| 46 | +from tensordict.nn import TensorDictModule |
| 47 | +from torch import nn |
| 48 | +from torchrl.collectors import MultiSyncDataCollector, RemoteWeightUpdaterBase |
| 49 | + |
| 50 | +from torchrl.envs.libs.gym import GymEnv |
| 51 | + |
| 52 | + |
| 53 | +class MPSRemoteWeightUpdater(RemoteWeightUpdaterBase): |
| 54 | + def __init__(self, policy_weights, num_workers): |
| 55 | + # Weights are on mps device, which cannot be shared |
| 56 | + self.policy_weights = policy_weights.data |
| 57 | + self.num_workers = num_workers |
| 58 | + |
| 59 | + def _sync_weights_with_worker( |
| 60 | + self, worker_id: int | torch.device, server_weights: TensorDictBase |
| 61 | + ) -> TensorDictBase: |
| 62 | + # Send weights on cpu - the local workers will do the cpu->mps copy |
| 63 | + self.collector.pipes[worker_id].send((server_weights, "update")) |
| 64 | + val, msg = self.collector.pipes[worker_id].recv() |
| 65 | + assert msg == "updated" |
| 66 | + return server_weights |
| 67 | + |
| 68 | + def _get_server_weights(self) -> TensorDictBase: |
| 69 | + print((self.policy_weights == 0).all()) |
| 70 | + return self.policy_weights.cpu() |
| 71 | + |
| 72 | + def _maybe_map_weights(self, server_weights: TensorDictBase) -> TensorDictBase: |
| 73 | + print((server_weights == 0).all()) |
| 74 | + return server_weights |
| 75 | + |
| 76 | + def all_worker_ids(self) -> list[int] | list[torch.device]: |
| 77 | + return list(range(self.num_workers)) |
| 78 | + |
| 79 | + |
| 80 | +if __name__ == "__main__": |
| 81 | + device = "mps" |
| 82 | + |
| 83 | + def env_maker(): |
| 84 | + return GymEnv("Pendulum-v1", device="cpu") |
| 85 | + |
| 86 | + def policy_factory(device=device): |
| 87 | + return TensorDictModule( |
| 88 | + nn.Linear(3, 1), in_keys=["observation"], out_keys=["action"] |
| 89 | + ).to(device=device) |
| 90 | + |
| 91 | + policy = policy_factory() |
| 92 | + policy_weights = tensordict.from_module(policy) |
| 93 | + |
| 94 | + collector = MultiSyncDataCollector( |
| 95 | + create_env_fn=[env_maker, env_maker], |
| 96 | + policy_factory=policy_factory, |
| 97 | + total_frames=2000, |
| 98 | + max_frames_per_traj=50, |
| 99 | + frames_per_batch=200, |
| 100 | + init_random_frames=-1, |
| 101 | + reset_at_each_iter=False, |
| 102 | + device=device, |
| 103 | + storing_device="cpu", |
| 104 | + remote_weight_updater=MPSRemoteWeightUpdater(policy_weights, 2), |
| 105 | + # use_buffers=False, |
| 106 | + # cat_results="stack", |
| 107 | + ) |
| 108 | + |
| 109 | + collector.update_policy_weights_() |
| 110 | + try: |
| 111 | + for i, data in enumerate(collector): |
| 112 | + if i == 2: |
| 113 | + print(data) |
| 114 | + assert (data["action"] != 0).any() |
| 115 | + # zero the policy |
| 116 | + policy_weights.data.zero_() |
| 117 | + collector.update_policy_weights_() |
| 118 | + elif i == 3: |
| 119 | + assert (data["action"] == 0).all(), data["action"] |
| 120 | + break |
| 121 | + finally: |
| 122 | + collector.shutdown() |
0 commit comments