In my reinforcement learning algorithm implementation, i need to pass the intermediate reward to the agent, wen we get 'reward = -200' or 'reward >= 90'.
In the below existing code i have implemented the reward function, but the implemented reward is only given to the agent after completing the maximum step size of the iteration loop in that current episode, but i need to pass the intermediate reward(while drastic deviation occurs) with in the episode to agent to guide it more effectively. So, i updated the existing code based on my logic.
The following problem i noticed while running the updated code:
consider my max_timesteps for each episode is 10,
i encounter the intermediate reward at the 5th timesteps of episode iteration,
here i am passing all the append data in to the PPO agent after the 5th timesteps of episode iteration
episode_rewards.append(reward)
states.append(state)
actions.append(action)
log_probs.append(log_prob.item())
values.append(agent.critic(node_features_tensor, edge_index).item())
masks.append(1.0 - float(done))
perf_metrics_log.append(perf_metrics)
here i am having doubt that, i supposed to pass only the required datas which is related with the corresponding intermediate reward and the corresponding 5th time step alone,
but in the updated code, we are sending entire append data which are append upto the 5th timesteps of episode iteration, into the PPO agent,
after that intermediate update we are Reset episodic storage, due to this inconsistency all the previous append data upto the 5th timesteps were reset, at the Final policy update at the end of the episode is getting only the datas which are append after the 5th timesteps(from 6th time steps to the 10th time steps),
but i am having the doubt in the implementation present in the updates code, where i need to pass only the corresponding data present at that present timesteps at which the intermediate reward appears and should i need to pass all the append datas to the Final policy update at the end of the episode(including the data which are already passed to the agent during intermediate reward appears).
Here what should i need to modify in the training function for properly implementing the intermediate reward in to the PPO agent.
These intermediate append datas are not the data corresponding only to the present timesteps where the intermediate reward is appeard, it the append data where all the data upto the intermediate reward appered.
performance_metrics = previous_metrics
state = next_state
# Check for intermediate reward conditions
if reward <= -200 or reward >= 90:
# Compute returns and advantages for the current accumulated data
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, intermediate_rewards, intermediate_masks, intermediate_values)
advantages = (torch.tensor(returns) - torch.tensor(intermediate_values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
agent.update_policy(intermediate_states, intermediate_actions, intermediate_log_probs, returns, advantages)
# Clear intermediate storage
intermediate_rewards = []
intermediate_states = []
intermediate_actions = []
intermediate_log_probs = []
intermediate_values = []
intermediate_masks = []
intermediate_perf_metrics_log = []
Assistant
User
here will the intermediate data will be clear after passing the datas to the PPO agent?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# Initialize the episode to start from and log lists
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Attempt to load the saved state
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['episode'] + 1 # Start from the next episode
agent.actor.load_state_dict(saved_state['actor_state_dict'])
agent.critic.load_state_dict(saved_state['critic_state_dict'])
agent.optimizer_actor.load_state_dict(saved_state['optimizer_actor_state_dict'])
agent.optimizer_critic.load_state_dict(saved_state['optimizer_critic_state_dict'])
rewards_log = saved_state['rewards_log']
losses_log = saved_state['losses_log']
metrics_log = saved_state['metrics_log']
train_targets = saved_state['train_targets']
test_targets = saved_state['test_targets']
print(f"Resuming from episode {start_episode}")
for episode in range(start_episode, num_episodes):
if episode >= num_targets:
break # Exit the loop if exhausted the number of targets
target = train_targets[episode % len(train_targets)]
node_features_tensor, edge_index, performance_metrics = env.reset(target)
state = (node_features_tensor, edge_index)
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
perf_metrics_log = []
for t in range(max_timesteps):
action, log_prob, perf_metrics = agent.select_action(state, performance_metrics)
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action, perf_metrics, target)
next_state = (next_node_features_tensor, next_edge_index)
episode_rewards.append(reward)
states.append(state)
actions.append(action)
log_probs.append(log_prob.item())
values.append(agent.critic(node_features_tensor, edge_index).item())
masks.append(1.0 - float(done))
perf_metrics_log.append(perf_metrics)
performance_metrics = previous_metrics
state = next_state
# Check for intermediate reward conditions
if reward <= -200 or reward >= 90:
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
average_loss_actor, average_loss_critic = agent.update_policy(states, actions, log_probs, returns, advantages)
# Reset episodic storage after intermediate update
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
if done:
break
# Final policy update at the end of the episode
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
average_loss_actor, average_loss_critic = agent.update_policy(states, actions, log_probs, returns, advantages)
episode_length = len(episode_rewards)
total_reward = sum(episode_rewards)
episode_lengths.append(episode_length)
agent.save_checkpoint(episode)
save_training_state(agent, episode, rewards_log, losses_log, metrics_log, train_targets, test_targets)
agent.save_checkpoint('final')
logging.info("Training Completed.")
It looks like you want to better utilize intermediate rewards during your training. To handle this effectively, you should focus on the following:
Passing only the data related to the timestep at which the intermediate reward appears.
Keeping the data consistent across the entire episode for the final policy update.
Steps to Follow:
Keep Track of Episode Data and Intermediate Data Separately: Maintain separate lists for storing episode data and intermediate data.
Push Intermediate Data to PPO Agent: When an intermediate reward is encountered, send the current timestep's data to the PPO agent.
Reset Intermediate Storage Post Update: Reset intermediate storage after sending data to the PPO agent.
Merge All Data for Final Policy Update: At the end of the episode, merge intermediate data with any remaining episode data for the final policy update.
Here’s how the modified code would look:
# Training Function
def train(env, agent, num_episodes, max_timesteps):
num_targets = 100
train_targets = CircuitEnvironment.generate_random_targets(num_targets=num_targets, seed=0)
test_targets = CircuitEnvironment.generate_random_targets(num_targets=20, seed=1)
# Initialize the episode to start from and log lists
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Attempt to load the saved state
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['episode'] + 1 # Start from the next episode
agent.actor.load_state_dict(saved_state['actor_state_dict'])
agent.critic.load_state_dict(saved_state['critic_state_dict'])
agent.optimizer_actor.load_state_dict(saved_state['optimizer_actor_state_dict'])
agent.optimizer_critic.load_state_dict(saved_state['optimizer_critic_state_dict'])
rewards_log = saved_state['rewards_log']
losses_log = saved_state['losses_log']
metrics_log = saved_state['metrics_log']
train_targets = saved_state['train_targets']
test_targets = saved_state['test_targets']
print(f"Resuming from episode {start_episode}")
for episode in range(start_episode, num_episodes):
if episode >= num_targets:
break # Exit the loop if exhausted the number of targets
target = train_targets[episode % len(train_targets)]
node_features_tensor, edge_index, performance_metrics = env.reset(target)
state = (node_features_tensor, edge_index)
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
perf_metrics_log = []
for t in range(max_timesteps):
action, log_prob, perf_metrics = agent.select_action(state, performance_metrics)
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action, perf_metrics, target)
next_state = (next_node_features_tensor, next_edge_index)
episode_rewards.append(reward)
states.append(state)
actions.append(action)
log_probs.append(log_prob.item())
values.append(agent.critic(node_features_tensor, edge_index).item())
masks.append(1.0 - float(done))
perf_metrics_log.append(perf_metrics)
performance_metrics = previous_metrics
state = next_state
# Check for intermediate reward conditions
if reward <= -200 or reward >= 90:
# Only pass data from the current timestep
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
average_loss_actor, average_loss_critic = agent.update_policy(states, actions, log_probs, returns, advantages)
# Reset episodic storage after intermediate update
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
if done:
break
# Ensure any remaining data is used in the final update
if len(episode_rewards) > 0:
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
average_loss_actor, average_loss_critic = agent.update_policy(states, actions, log_probs, returns, advantages)
# Log episode results
episode_length = len(episode_rewards)
total_reward = sum(episode_rewards)
episode_lengths.append(episode_length)
agent.save_checkpoint(episode)
save_training_state(agent, episode, rewards_log, losses_log, metrics_log, train_targets, test_targets)
agent.save_checkpoint('final')
logging.info("Training Completed.")
Key Points:
Intermediate Update: Only pass data for the current timestep during the intermediate update.
Final Update: Pass any remaining data from the episode to the final update.
This way, you ensure that significant deviations detected during intermediate steps use only relevant data, while the final update considers all actions taken over the entire episode.
I apologize for misunderstanding your requirements earlier. I see now that you need to pass the accumulated episode data up to the point of the intermediate reward, and then reset the storages after the intermediate update. You also want the final update at the end of the episode to include all relevant data, including the intermediate data that was already used for updates during the episode.
To ensure correct behavior under these requirements, here’s a refined approach:
Separate Storage for Intermediate and Final: Maintain separate lists to accumulate data for the intermediate and final updates.
Concatenate Data for Final Update: Before the final update, concatenate intermediate data used so far with the remaining episode data.
Avoid Resetting Intermediate Data After Update: To ensure the final update sees the entire episode's worth of data, do not clear the intermediate data after using it for an update.
Here’s the updated code reflecting this approach:
# Training Function
def train(env, agent, num_episodes, max_timesteps):
num_targets = 100
train_targets = CircuitEnvironment.generate_random_targets(num_targets=num_targets, seed=0)
test_targets = CircuitEnvironment.generate_random_targets(num_targets=20, seed=1)
# Initialize the episode to start from and log lists
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Attempt to load the saved state
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['episode'] + 1 # Start from the next episode
agent.actor.load_state_dict(saved_state['actor_state_dict'])
agent.critic.load_state_dict(saved_state['critic_state_dict'])
agent.optimizer_actor.load_state_dict(saved_state['optimizer_actor_state_dict'])
agent.optimizer_critic.load_state_dict(saved_state['optimizer_critic_state_dict'])
rewards_log = saved_state['rewards_log']
losses_log = saved_state['losses_log']
metrics_log = saved_state['metrics_log']
train_targets = saved_state['train_targets']
test_targets = saved_state['test_targets']
print(f"Resuming from episode {start_episode}")
for episode in range(start_episode, num_episodes):
if episode >= num_targets:
break # Exit the loop if exhausted the number of targets
target = train_targets[episode % len(train_targets)]
node_features_tensor, edge_index, performance_metrics = env.reset(target)
state = (node_features_tensor, edge_index)
# Initialize storage for episode and intermediate data
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
perf_metrics_log = []
for t in range(max_timesteps):
action, log_prob, perf_metrics = agent.select_action(state, performance_metrics)
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action, perf_metrics, target)
next_state = (next_node_features_tensor, next_edge_index)
episode_rewards.append(reward)
states.append(state)
actions.append(action)
log_probs.append(log_prob.item())
values.append(agent.critic(node_features_tensor, edge_index).item())
masks.append(1.0 - float(done))
perf_metrics_log.append(perf_metrics)
performance_metrics = previous_metrics
state = next_state
# Check for intermediate reward conditions
if reward <= -200 or reward >= 90:
# Compute returns and advantages for the current accumulated data
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
agent.update_policy(states, actions, log_probs, returns, advantages)
# Clear accumulated data without resetting the intermediate storage
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
perf_metrics_log = []
if done:
break
# Ensure any remaining data is used in the final update
if len(episode_rewards) > 0:
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
agent.update_policy(states, actions, log_probs, returns, advantages)
# Log episode results
episode_length = len(episode_rewards)
total_reward = sum(episode_rewards)
episode_lengths.append(episode_length)
agent.save_checkpoint(episode)
save_training_state(agent, episode, rewards_log, losses_log, metrics_log, train_targets, test_targets)
agent.save_checkpoint('final')
logging.info("Training Completed.")
Key Points:
Separate Storage: Maintain separate storages (episode_rewards, states, actions, log_probs, values, masks, and perf_metrics_log) for intermediate and final accumulations.
Compute Returns and Advantages for Intermediate Rewards: When an intermediate reward condition is met, compute returns and update the policy using the accumulated intermediate data.
Avoid Clearing Intermediate Storage for Final Update: Do not clear intermediate storages after each intermediate update. This ensures all data, including intermediate updates, are used in the final policy update at the end of the episode.
This approach ensures that both intermediate rewards and end-of-episode data are handled correctly, resulting in a more efficient reinforcement learning process with the PPO agent.
next_state = (next_node_features_tensor, next_edge_index)
episode_rewards.append(reward)
states.append(state)
actions.append(action)
log_probs.append(log_prob.item())
values.append(agent.critic(node_features_tensor, edge_index).item())
masks.append(1.0 - float(done))
perf_metrics_log.append(perf_metrics)
performance_metrics = previous_metrics
state = next_state
# Check for intermediate reward conditions
if reward <= -200 or reward >= 90:
# Compute returns and advantages for the current accumulated data
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
agent.update_policy(states, actions, log_probs, returns, advantages)
Here after checking the intermediate reward condition, the datas passed to the 'returns = agent.compute_gae(next_value, episode_rewards, masks, values)' code is append datas 'episode_rewards.append(reward), masks.append(1.0 - float(done)), values.append(agent.critic(node_features_tensor, edge_index).item())' which are append upto the previous timesteps(which is not the data from only the present time steps),
# Clear accumulated data without resetting the intermediate storage
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
perf_metrics_log = []
if done:
break
after Clear accumulated data, all the datas which are present upto the timesteps where the intermediate reward appear, all are cleared
here only the remaining data are passed to the final update. which is incorrect
# Ensure any remaining data is used in the final update
if len(episode_rewards) > 0:
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
Understood. To properly handle the intermediate rewards and prevent losing the earlier data during the final policy update, we need to preserve the data used for intermediate updates. This requires:
Separate Episodic Storage: Use a temporary storage for the intermediate rewards and the final update should incorporate all the data collected during the episode.
Accumulate All Data Until the End: We need to ensure that intermediate updates are performed with data up to that point, but for the final update, we must ensure that all the data (including that which was cleared previously) is included.
Here’s a revised approach:
Use a separate list for each type of intermediate data.
Accumulate all intermediate and episode data into a final list for policy updates.
Here’s the modified code:
# Training Function
def train(env, agent, num_episodes, max_timesteps):
num_targets = 100
train_targets = CircuitEnvironment.generate_random_targets(num_targets=num_targets, seed=0)
test_targets = CircuitEnvironment.generate_random_targets(num_targets=20, seed=1)
# Initialize the episode to start from and log lists
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Attempt to load the saved state
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['episode'] + 1 # Start from the next episode
agent.actor.load_state_dict(saved_state['actor_state_dict'])
agent.critic.load_state_dict(saved_state['critic_state_dict'])
agent.optimizer_actor.load_state_dict(saved_state['optimizer_actor_state_dict'])
agent.optimizer_critic.load_state_dict(saved_state['optimizer_critic_state_dict'])
rewards_log = saved_state['rewards_log']
losses_log = saved_state['losses_log']
metrics_log = saved_state['metrics_log']
train_targets = saved_state['train_targets']
test_targets = saved_state['test_targets']
print(f"Resuming from episode {start_episode}")
for episode in range(start_episode, num_episodes):
if episode >= num_targets:
break # Exit the loop if exhausted the number of targets
target = train_targets[episode % len(train_targets)]
node_features_tensor, edge_index, performance_metrics = env.reset(target)
state = (node_features_tensor, edge_index)
episode_rewards = []
intermediate_rewards = []
states = []
intermediate_states = []
actions = []
intermediate_actions = []
log_probs = []
intermediate_log_probs = []
values = []
intermediate_values = []
masks = []
intermediate_masks = []
perf_metrics_log = []
intermediate_perf_metrics_log = []
for t in range(max_timesteps):
action, log_prob, perf_metrics = agent.select_action(state, performance_metrics)
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action, perf_metrics, target)
next_state = (next_node_features_tensor, next_edge_index)
episode_rewards.append(reward)
intermediate_rewards.append(reward)
states.append(state)
intermediate_states.append(state)
actions.append(action)
intermediate_actions.append(action)
log_probs.append(log_prob.item())
intermediate_log_probs.append(log_prob.item())
values.append(agent.critic(node_features_tensor, edge_index).item())
intermediate_values.append(agent.critic(node_features_tensor, edge_index).item())
masks.append(1.0 - float(done))
intermediate_masks.append(1.0 - float(done))
perf_metrics_log.append(perf_metrics)
intermediate_perf_metrics_log.append(perf_metrics)
performance_metrics = previous_metrics
state = next_state
# Check for intermediate reward conditions
if reward <= -200 or reward >= 90:
# Compute returns and advantages for the current accumulated data
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, intermediate_rewards, intermediate_masks, intermediate_values)
advantages = (torch.tensor(returns) - torch.tensor(intermediate_values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
agent.update_policy(intermediate_states, intermediate_actions, intermediate_log_probs, returns, advantages)
# Clear intermediate storage
intermediate_rewards = []
intermediate_states = []
intermediate_actions = []
intermediate_log_probs = []
intermediate_values = []
intermediate_masks = []
intermediate_perf_metrics_log = []
if done:
break
# Final policy update with all accumulated data, including the intermediate
if len(episode_rewards) > 0:
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
agent.update_policy(states, actions, log_probs, returns, advantages)
# Log episode results
episode_length = len(episode_rewards)
total_reward = sum(episode_rewards)
episode_lengths.append(episode_length)
agent.save_checkpoint(episode)
save_training_state(agent, episode, rewards_log, losses_log, metrics_log, train_targets, test_targets)
agent.save_checkpoint('final')
logging.info("Training Completed.")
Key Points:
Intermediate Storage: Separate intermediate storage to hold data temporarily for intermediate updates.
Final Update: Use all accumulated data for the final update.
Clear Intermediate Storage Post Update: Clear only the intermediate storage post-intermediate updates to prevent the loss of the total episode data.
This approach preserves the data across the entire episode while allowing intermediate updates to be performed correctly and efficiently.
Understood, the goal is to pass only the data corresponding to the present timestep when the intermediate reward condition is met. To achieve this, we need to:
Accumulate all episode data till timestep of intermediate reward.
Reset only intermediate storage necessary for computing intermediate updates.
Ensure that intermediate storage holds data only for the current timestep at which the condition occurs.
Here's how you can achieve this:
Store intermediate updates in their own variables for a single timestep.
Incorporate this intermediate data into the final episode data accumulation.
Here’s the updated code reflecting this approach:
# Training Function
def train(env, agent, num_episodes, max_timesteps):
num_targets = 100
train_targets = CircuitEnvironment.generate_random_targets(num_targets=num_targets, seed=0)
test_targets = CircuitEnvironment.generate_random_targets(num_targets=20, seed=1)
# Initialize the episode to start from and log lists
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Attempt to load the saved state
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['episode'] + 1 # Start from the next episode
agent.actor.load_state_dict(saved_state['actor_state_dict'])
agent.critic.load_state_dict(saved_state['critic_state_dict'])
agent.optimizer_actor.load_state_dict(saved_state['optimizer_actor_state_dict'])
agent.optimizer_critic.load_state_dict(saved_state['optimizer_critic_state_dict'])
rewards_log = saved_state['rewards_log']
losses_log = saved_state['losses_log']
metrics_log = saved_state['metrics_log']
train_targets = saved_state['train_targets']
test_targets = saved_state['test_targets']
print(f"Resuming from episode {start_episode}")
for episode in range(start_episode, num_episodes):
if episode >= num_targets:
break # Exit the loop if exhausted the number of targets
target = train_targets[episode % len(train_targets)]
node_features_tensor, edge_index, performance_metrics = env.reset(target)
state = (node_features_tensor, edge_index)
# Initialize storage for episode data
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
perf_metrics_log = []
for t in range(max_timesteps):
action, log_prob, perf_metrics = agent.select_action(state, performance_metrics)
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action, perf_metrics, target)
next_state = (next_node_features_tensor, next_edge_index)
# Append data to the general episode storage
episode_rewards.append(reward)
states.append(state)
actions.append(action)
log_probs.append(log_prob.item())
values.append(agent.critic(node_features_tensor, edge_index).item())
masks.append(1.0 - float(done))
perf_metrics_log.append(perf_metrics)
performance_metrics = previous_metrics
state = next_state
# Check for intermediate reward conditions
if reward <= -200 or reward >= 90:
# Compute returns and advantages for the current state (intermediate timestep only)
intermediate_rewards = [reward]
intermediate_states = [state]
intermediate_actions = [action]
intermediate_log_probs = [log_prob.item()]
intermediate_values = [agent.critic(node_features_tensor, edge_index).item()]
intermediate_masks = [1.0 - float(done)]
intermediate_perf_metrics_log = [perf_metrics]
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, intermediate_rewards, intermediate_masks, intermediate_values)
advantages = (torch.tensor(returns) - torch.tensor(intermediate_values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
agent.update_policy(intermediate_states, intermediate_actions, intermediate_log_probs, returns, advantages)
if done:
break
# Final policy update with all accumulated data for the entire episode
if len(episode_rewards) > 0:
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
agent.update_policy(states, actions, log_probs, returns, advantages)
# Log episode results
episode_length = len(episode_rewards)
total_reward = sum(episode_rewards)
episode_lengths.append(episode_length)
agent.save_checkpoint(episode)
save_training_state(agent, episode, rewards_log, losses_log, metrics_log, train_targets, test_targets)
agent.save_checkpoint('final')
logging.info("Training Completed.")
Key Points:
Intermediate Data Storage: Use separate storage for the data at the intermediate timestep.
Intermediate Reward Condition: When the condition is met, add only the relevant data from the current timestep to the intermediate storage.
Final Update Includes All Data: Accumulate all data over the episode (including the timesteps with intermediate updates) into the final policy update.
This way, you ensure that the data used for intermediate updates corresponds only to the current timestep, without accumulating unnecessary data from previous timesteps.
In the context of your updated code, there isn't a need to clear the intermediate data explicitly because it's reinitialized each time the condition is met. The intermediate data for each condition is transient and only exists within the scope of that particular check.
Here’s a more detailed illustration to clarify the mechanism:
Accumulate All Data for the Episode: Continue storing all the episode data as usual.
Intermediate Update: When the intermediate condition (e.g., reward <= -200 or reward >= 90) is met:
Collect just the current timestep's data into new intermediate lists.
Do the PPO update using these lists and discard them after use (by virtue of them being local variables in scope).
Final Update: Use the accumulated episode data, which includes all timesteps, for the final PPO update at the end of the episode.
Here’s a refined version of the code to reflect this:
# Training Function
def train(env, agent, num_episodes, max_timesteps):
num_targets = 100
train_targets = CircuitEnvironment.generate_random_targets(num_targets=num_targets, seed=0)
test_targets = CircuitEnvironment.generate_random_targets(num_targets=20, seed=1)
# Initialize the episode to start from and log lists
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Attempt to load the saved state
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['episode'] + 1 # Start from the next episode
agent.actor.load_state_dict(saved_state['actor_state_dict'])
agent.critic.load_state_dict(saved_state['critic_state_dict'])
agent.optimizer_actor.load_state_dict(saved_state['optimizer_actor_state_dict'])
agent.optimizer_critic.load_state_dict(saved_state['optimizer_critic_state_dict'])
rewards_log = saved_state['rewards_log']
losses_log = saved_state['losses_log']
metrics_log = saved_state['metrics_log']
train_targets = saved_state['train_targets']
test_targets = saved_state['test_targets']
print(f"Resuming from episode {start_episode}")
for episode in range(start_episode, num_episodes):
if episode >= num_targets:
break # Exit the loop if exhausted the number of targets
target = train_targets[episode % len(train_targets)]
node_features_tensor, edge_index, performance_metrics = env.reset(target)
state = (node_features_tensor, edge_index)
# Initialize storage for episode data
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
perf_metrics_log = []
for t in range(max_timesteps):
action, log_prob, perf_metrics = agent.select_action(state, performance_metrics)
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action, perf_metrics, target)
next_state = (next_node_features_tensor, next_edge_index)
# Append data to the general episode storage
episode_rewards.append(reward)
states.append(state)
actions.append(action)
log_probs.append(log_prob.item())
values.append(agent.critic(node_features_tensor, edge_index).item())
masks.append(1.0 - float(done))
perf_metrics_log.append(perf_metrics)
performance_metrics = previous_metrics
state = next_state
# Check for intermediate reward conditions
if reward <= -200 or reward >= 90:
# Collecting intermediate step data only
intermediate_rewards = [reward]
intermediate_states = [state]
intermediate_actions = [action]
intermediate_log_probs = [log_prob.item()]
intermediate_values = [agent.critic(node_features_tensor, edge_index).item()]
intermediate_masks = [1.0 - float(done)]
# Compute returns and advantages for the current intermediate step
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, intermediate_rewards, intermediate_masks, intermediate_values)
advantages = (torch.tensor(returns) - torch.tensor(intermediate_values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
agent.update_policy(intermediate_states, intermediate_actions, intermediate_log_probs, returns, advantages)
if done:
break
# Final policy update with all accumulated data for the entire episode
if len(episode_rewards) > 0:
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
agent.update_policy(states, actions, log_probs, returns, advantages)
# Log episode results
episode_length = len(episode_rewards)
total_reward = sum(episode_rewards)
episode_lengths.append(episode_length)
agent.save_checkpoint(episode)
save_training_state(agent, episode, rewards_log, losses_log, metrics_log, train_targets, test_targets)
agent.save_checkpoint('final')
logging.info("Training Completed.")
Key Points:
Intermediate Storage: Intermediate data is collected for each timestep where the condition is met.
Resetting Intermediate Data: We do not need an explicit clearing of intermediate storage as it's collected and used in place without reuse in the next timestep.
Final Episode Data: Accumulate all data over the episode (including those timesteps used in intermediate updates) and update the PPO policy once more at the end of the episode using the complete history.
This way, you ensure that the intermediate reward data gets processed correctly while the final PPO update considers the entire episode, avoiding any loss of information.