MCPcopy Index your code
hub / github.com/OpenDriveLab/TCP / train

Method train

roach/models/ppo.py:103–210  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

101 return True
102
103 def train(self):
104 for param_group in self.policy.optimizer.param_groups:
105 param_group["lr"] = self.learning_rate
106
107 entropy_losses, exploration_losses, pg_losses, value_losses, losses = [], [], [], [], []
108 clip_fractions = []
109 approx_kl_divs = []
110
111 # train for gradient_steps epochs
112 epoch = 0
113 data_len = int(self.buffer.buffer_size * self.buffer.n_envs / self.batch_size)
114 for epoch in range(self.n_epochs):
115 approx_kl_divs = []
116 # Do a complete pass on the rollout buffer
117 self.buffer.start_caching(self.batch_size)
118 # while self.buffer.sample_queue.qsize() < 3:
119 # time.sleep(0.01)
120 for i in range(data_len):
121
122 if self.buffer.sample_queue.empty():
123 while self.buffer.sample_queue.empty():
124 # print(f'buffer_empty: {self.buffer.sample_queue.qsize()}')
125 time.sleep(0.01)
126 rollout_data = self.buffer.sample_queue.get()
127
128 values, log_prob, entropy_loss, exploration_loss, distribution = self.policy.evaluate_actions(
129 rollout_data.observations, rollout_data.actions, rollout_data.exploration_suggests,
130 detach_values=False)
131 # Normalize advantage
132 advantages = rollout_data.advantages
133 # advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
134
135 # ratio between old and new policy, should be one at the first iteration
136 ratio = th.exp(log_prob - rollout_data.old_log_prob)
137
138 # clipped surrogate loss
139 policy_loss_1 = advantages * ratio
140 policy_loss_2 = advantages * th.clamp(ratio, 1 - self.clip_range, 1 + self.clip_range)
141 policy_loss = -th.min(policy_loss_1, policy_loss_2).mean()
142
143 # Logging
144 clip_fraction = th.mean((th.abs(ratio - 1) > self.clip_range).float()).item()
145 clip_fractions.append(clip_fraction)
146
147 if self.clip_range_vf is None:
148 # No clipping
149 values_pred = values
150 else:
151 # Clip the different between old and new value
152 # NOTE: this depends on the reward scaling
153 values_pred = rollout_data.old_values + th.clamp(values - rollout_data.old_values,
154 -self.clip_range_vf, self.clip_range_vf)
155 # Value loss using the TD(gae_lambda) target
156 value_loss = F.mse_loss(rollout_data.returns, values_pred)
157
158 loss = policy_loss + self.vf_coef * value_loss \
159 + self.ent_coef * entropy_loss + self.explore_coef * exploration_loss
160

Callers 1

learnMethod · 0.95

Calls 9

start_cachingMethod · 0.80
getMethod · 0.80
evaluate_actionsMethod · 0.80
update_valuesMethod · 0.80
forward_valueMethod · 0.80
flattenMethod · 0.80
stepMethod · 0.45
proba_distributionMethod · 0.45

Tested by

no test coverage detected