In my implementation i used reinforcement learning technique with graph neural network, in the analog circuit synthesis optimization process.
In general(common among all types): Fixed circuit topology (netlist) is converted in to graph structure, during optimization process, in the fixed topology(netlist/graph) the node features(circuit device component values/dimensions) are alone dynamic in nature, where the nodes(components and nets), edges(connection between components and nets) and edge features are static in nature.
Framework of my implementation:
-circuit netlist(represented in the environment simulation) is convert into graph network, graph network is embedded in to graph neural network.
-the node features and edge features/adjacency matrix/edge index, are my state values from the environment to the RL agent(actor and critic with GNN).
-circuit has target specification metrics(obtained value need to meet with in the target value range) and the device component(each component need to optimize) in the circuit has specific ranges(bounds) for tuning.
-RL agent generated action space for the values of the device component and pass it to the environment, where the environment, simulates the data and generate the state and reward function (reward function is based on the difference between the target and obtained performance metrics, we get penalties when deviation).
-the optimization aim is to get maximum reward(all the obtained value must be with in the target value range).
-based on the reward/penalty loss function were generated from the critic network, the actor network predicts new action space using the policy using the loss function in RL agent.
-The process is goes on until all the obtained value with in the target value range.
I need to know, can i able to modify the existing framework into below requirement:
-as same as the first type implementation procedure, instead of reaching target value range and end the optimization, we first train the agent by tuning the action space(continuous) with in its bounds to meet the target design specification, train the agent for different set of random number of performance metrics within the target range(predefined ranges for each metrics). using reward calculate the loss function and tune the action space to achieve each target. (i also need to know what else if the target doesnot reach from different continuous action space is there any stopping criteria)
-and after training i need to test the trained agent with the another set of random generated target specifications(which were not used in the training process)
-and i also need to test the trained agent with same circuit topology with another CMOS technology file
I have my exixting code in three splitups(full code divided in continuous three splitup because of large number of codes), i will provide my existing code for your reference, will you provide me the updated code for my requiement.
the circuit environment gets input action space for the variables(8) 'W1', 'W3', 'W5', 'W6', 'W7','Ib', 'Cc', 'Vc', and generate four output performance mertics 'gain', 'bw', 'ugf', 'pm' for each action space input, and from the environment we get state data(node feature tensor and edge index) and reward values(whether the output performance metrics reach the target metrics or not, based on the difference we calculate the cummulated reward values)
-generating random target metrics 'gain', 'bw', 'ugf', 'pm', must be discrete with in the ranges,
CircuitEnvironment.PERFORMANCE_METRICS_TARGET_LOW = np.array([48, 30e3, 10e6, 60])
CircuitEnvironment.PERFORMANCE_METRICS_TARGET_HIGH = np.array([100, 100e3, 100e6, 75])
-the action space must be in continuous with in the range for the action space variables 'W1', 'W3', 'W5', 'W6', 'W7','Ib', 'Cc', 'Vc',
bounds_low = np.array([0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 15e-6, 0.1e-12, 0.8])
bounds_high = np.array([50e-6, 50e-6, 50e-6, 50e-6, 50e-6, 30e-6, 10e-12, 1.4])
-training and testing target metrics must not be overlapped(no same discrete target metrics used in both testing and training process)
-Integrating the necessary data from the updated entire code into your save and load file process involves ensuring that all relevant state information is saved and loaded correctly in the training and testing process.
Assistant
To modify your existing reinforcement learning framework to meet the new requirements, we need to make several adjustments:
Train the agent for a range of target design specifications.
Define stopping criteria.
Validate the trained agent with new target specifications.
Validate the agent with another CMOS technology file.
Ensure no overlap in training and testing metrics.
Include the save/load functionality for the trained model.
Below, I outline how you can modify your code to incorporate these requirements in a generic way. Note that integrating all this functionality into existing code would require detailed insights into your current implementation. I'll provide a framework on how to change the logic, and you will need to map these suggestions to your actual code structure.
Step-by-Step Modifications:
Step 1: Generate Random Target Specifications
Create discrete random target metrics for training and testing with no overlap:
python
import numpy as np
class CircuitEnvironment:
# Given ranges for metrics
PERFORMANCE_METRICS_TARGET_LOW = np.array([48, 30e3, 10e6, 60])
PERFORMANCE_METRICS_TARGET_HIGH = np.array([100, 100e3, 100e6, 75])
@staticmethod
def generate_random_targets(num_targets, train=True):
np.random.seed(0 if train else 1) # Different seed for train/test
target_ranges = CircuitEnvironment.PERFORMANCE_METRICS_TARGET_HIGH - CircuitEnvironment.PERFORMANCE_METRICS_TARGET_LOW
random_targets = np.random.rand(num_targets, 4) * target_ranges + CircuitEnvironment.PERFORMANCE_METRICS_TARGET_LOW
return random_targets.astype(int) # Discrete and int values
# Example usage
train_targets = CircuitEnvironment.generate_random_targets(num_targets=100, train=True)
test_targets = CircuitEnvironment.generate_random_targets(num_targets=20, train=False)
User
the circuit environment gets input action space for the variables(8) 'W1', 'W3', 'W5', 'W6', 'W7','Ib', 'Cc', 'Vc', and generate four output performance mertics 'gain', 'bw', 'ugf', 'pm' for each action space input, and from the environment we get state data(node feature tensor and edge index) and reward values(whether the output performance metrics reach the target metrics or not, based on the difference we calculate the cummulated reward values)
-generating random target metrics 'gain', 'bw', 'ugf', 'pm', must be discrete with in the ranges,
CircuitEnvironment.PERFORMANCE_METRICS_TARGET_LOW = np.array([48, 30e3, 10e6, 60])
CircuitEnvironment.PERFORMANCE_METRICS_TARGET_HIGH = np.array([100, 100e3, 100e6, 75])
-the action space must be in continuous with in the range for the action space variables 'W1', 'W3', 'W5', 'W6', 'W7','Ib', 'Cc', 'Vc',
bounds_low = np.array([0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 15e-6, 0.1e-12, 0.8])
bounds_high = np.array([50e-6, 50e-6, 50e-6, 50e-6, 50e-6, 30e-6, 10e-12, 1.4])
-training and testing target metrics must not be overlapped(no same discrete target metrics used in both testing and training process)
-Integrating the necessary data from the updated entire code into your save and load file process involves ensuring that all relevant state information is saved and loaded correctly in the training and testing process.
I have my exixting code in three splitups(full code divided in continuous three splitup because of large number of codes), i will provide my existing code for your reference, will you provide me the updated code for my requiement.
Assistant
To integrate your requirements into your existing reinforcement learning framework for circuit environment optimization, I will provide you a structured way to implement the necessary changes. Since your code is split into three parts and is large, I'll focus on demonstrating how to incorporate the changes you need across your codebase.
Summary of Changes
Generate Random Target Metrics:
Ensure generated target metrics for training and testing do not overlap.
Modify Training Loop:
Train the agent using a range of randomly generated target specifications.
Define Stopping Criteria:
Introduce a criteria for stopping the optimization process if targets are not met.
Modify Testing Loop:
Test the trained agent with a different set of targets that were not used during training.
Load CMOS Technology File:
Ensure environment can handle multiple technology files.
Save/Load Model State:
Save and load the RL agent's state for training and testing.
Step-by-Step Implementation
1. Generate Random Target Metrics
Create a utility function for generating non-overlapping training and testing target metrics:
I have my exixting code in three splitups(full code divided in continuous three splitup because of large number of codes), i will provide my existing code for your reference, will you provide me the updated code for my requiement.
Assistant
Sure, I'd be happy to assist in integrating the new requirements into your existing code. Please go ahead and provide the three parts of your existing code. Once I have these, I can help you modify and integrate the necessary changes for generating random target metrics, training and testing the agent, defining stopping criteria, handling multiple CMOS technology files, and saving/loading the agent's state.
User
splitup 1: here all the function with in the class 'CircuitEnvironment' was implemented for my existing objective, we need to update it to the new required objectives,
Thank you for providing the first part of your code, which includes the CircuitEnvironment class. I'll now update it to meet your new requirements. Here are the primary changes:
Random Target Generation: Add functionality to generate random target metrics for training and testing.
Modified reset and step Methods: Adjust these methods to handle new target metrics during training and testing.
Stopping Criteria: Introduce a criterion to stop the environment when required.
Handle CMOS Technology Files: Ensure that the environment can handle different technology files.
Here’s the updated code for the CircuitEnvironment class:
python
User
splitup 2: here all the function with in the function 'train' was implemented for my existing objective, we need to update it to the new required objectives,
To update your existing objectives in the train function to incorporate new requirements— such as generating random target metrics, ensuring no overlap between training and testing data, stopping criteria — you need to make the following changes:
Generate Random Target Metrics: Adjust the environment reset method to include random target metrics.
Ensure Non-overlapping Training and Testing Targets: Create separate target metric sets for training and testing.
Add Stopping Criteria: Implement a stopping criterion within your training loop.
Save and Load Model States: Enhance the save and load functionality to correctly handle the new requirements.
I'll incorporate these changes while maintaining the rest of your existing functionality.
Updated Training Code:
python
User
splitup 3: here all the function with in the class 'PPOAgent' was implemented for my existing objective, we need to update it to the new required objectives,
To update the PPOAgent class in line with your new requirements, we'll need to make the following adjustments:
Handling Different CMOS Technology Files: This is already delegated to the environment, so no changes required here.
Selecting and Scaling Actions: Ensure action bounds are correctly handled when selecting actions.
Saving and Loading State: Ensure the models and optimizers are correctly saved and loaded.
Reward and Performance Metrics: No changes appear necessary unless more context is provided.
Here's the updated code:
Updated PPOAgent Class:
python
User
do we need to save and load the random generated target metrics(un overlapped separate for training and testing with in the bounds) for training and testing process, in the existing save and load process,
and also we need to save and load all the necessary needed data's in the traiing and testing process to the next day run(I stop the process in present day and run from the saved data in next day)
I am having another doubt that do we need separate function for train and test process, if we need provide me the appropriate code for the testing the trained agent, with the random target metrics(un overlapped with training target metrics) and with another circuit(same circuit topology with different cmos technology file).
Assistant
Saving and Loading Random Generated Target Metrics
Yes, it would be prudent to save and load the random generated target metrics to ensure consistency across runs, especially if you need to pause and resume training/testing. This guarantees that your training and testing data remain the same even if you restart the process on a different day.
Separate Functions for Training and Testing
Yes, it is good practice to have separate functions for training and testing.
Below, I'll update your functions to include saving and loading of the target metrics and provide separate functions for training and testing processes.
Updated Code
Saving and Loading Functions
First, update the saving and loading functions to include the target metrics.
python
import torch
import os
import numpy as np
import pandas as pd
def save_training_state(agent, episode, rewards_log, losses_log, metrics_log, train_targets, test_targets, filepath='training_state.pt'):
state = {
'episode': episode,
'actor_state_dict': agent.actor.state_dict(),
'critic_state_dict': agent.critic.state_dict(),
'optimizer_actor_state_dict': agent.optimizer_actor.state_dict(),
'optimizer_critic_state_dict': agent.optimizer_critic.state_dict(),
'rewards_log': rewards_log,
'losses_log': losses_log,
'metrics_log': metrics_log,
'train_targets': train_targets,
'test_targets': test_targets
}
torch.save(state, filepath)
def load_training_state(filepath='training_state.pt'):
if os.path.isfile(filepath):
state = torch.load(filepath)
return state
else:
return None
Training Function
Next, update the training function to handle loading the target metrics correctly.
python
User
do we need to add the train_targets and test_targets in the existing save and load trainig state or we need separate save and load for the random generated metrics.
# Generate random target metrics if not loaded
train_targets = CircuitEnvironment.generate_random_targets(num_targets=100, seed=0)
test_targets = CircuitEnvironment.generate_random_targets(num_targets=20, seed=1)
Assistant
It’s a good idea to integrate the saving and loading of the target metrics within the existing save and load functions. This ensures all necessary state information, including the target metrics, is encapsulated together. This prevents any inconsistency or mismatch between the model state and the target metrics when you resume training.
Updated Training and Saving/Loading Functions
Below, I'll ensure that the target metrics are included within the existing save_training_state and load_training_state functions, and integrate them properly within the train function.
Saving and Loading Functions
Integrate the target metrics into the existing save and load functions:
The training loop should account for different target specifications:
python
def train_agent(env, agent, num_targets):
train_targets = CircuitEnvironment.generate_random_targets(num_targets=num_targets, train=True)
for target in train_targets:
step = 0
total_reward = 0
state = env.reset(target)
while True:
action = agent.select_action(state)
next_state, reward = env.step(action)
agent.update(state, action, reward, next_state)
total_reward += reward
step += 1
if agent.stop_criteria(total_reward, step):
break
state = next_state
# Integrate this in your existing training function
Step 4: Update Testing Process
Similar to the training process, but with testing targets and no model updates:
python
def test_agent(env, agent, num_targets):
test_targets = CircuitEnvironment.generate_random_targets(num_targets=num_targets, train=False)
rewards = []
for target in test_targets:
step = 0
total_reward = 0
state = env.reset(target)
while True:
action = agent.select_action(state)
next_state, reward = env.step(action)
total_reward += reward
step += 1
if agent.stop_criteria(total_reward, step):
break
state = next_state
rewards.append(total_reward)
return rewards
# Integrate this in your existing testing function
Step 5: CMOS Technology File
Ensure your agent/environment can switch between different technology files:
You will need to integrate these snippets into your actual codebase, adjusting for specific details and ensuring the environment, agent, and training/testing logic align appropriately. If you provide the existing code, specific implementation details could be adjusted more precisely.
2. Modify Training Loop
Integrate the new training targets into your RL agent's training loop:
python
# Assuming you have an already defined Agent and Environment class.
class Agent:
def __init__(self, max_steps=10000, tolerance=1e-2, model=None, optimizer=None):
self.max_steps = max_steps
self.tolerance = tolerance
self.model = model
self.optimizer = optimizer
def stop_criteria(self, reward, step):
return reward >= (1 - self.tolerance) or step >= self.max_steps
def save(self, path):
torch.save({
'model_state_dict': self.model.state_dict(),
'optimizer_state_dict': self.optimizer.state_dict(),
}, path)
def load(self, path):
checkpoint = torch.load(path)
self.model.load_state_dict(checkpoint['model_state_dict'])
self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
def select_action(self, state):
# Implement action selection logic
pass
def update(self, state, action, reward, next_state):
# Implement learning (agent update) logic
pass
# Example training loop
def train_agent(env, agent, num_targets):
train_targets = CircuitEnvironment.generate_random_targets(num_targets=num_targets, seed=0)
for target in train_targets:
step = 0
total_reward = 0
state = env.reset(target)
while True:
action = agent.select_action(state)
next_state, reward = env.step(action)
agent.update(state, action, reward, next_state)
total_reward += reward
step += 1
if agent.stop_criteria(total_reward, step):
break
state = next_state
# Integrate this in your actual training function
To integrate these changes into your existing codebase, you would:
Add the generate_random_targets method to CircuitEnvironment.
Modify your training function to loop through the train_targets as described.
Define the stopping criteria in the Agent class.
Modify the test function to loop through the test_targets and avoid updating the agent.
Update the environment to handle different CMOS technology files.
Add the save and load methods to the Agent class and call them appropriately.
If you provide the specific segments of your current codebase, I can help integrate these changes directly into your existing functions and classes.
# Initialize tensors as None
self.node_features_tensor = None
self.edge_index = None
def reset(self):
# Environment reset: typically would reset the simulator state and return initial observation
# Initialize parameters within bounds
initial_parameters = np.random.uniform(self.bounds_low, self.bounds_high)
# Run simulation with initial parameters
performance_metrics, temp_netlist_path = run_simulation(initial_parameters)
# Process netlist to generate model inputs
node_features_tensor, edge_index = netlist_to_graph(temp_netlist_path)
# Update class variables
self.node_features_tensor = node_features_tensor
self.edge_index = edge_index
return node_features_tensor, edge_index, performance_metrics
def step(self, raw_actions, previous_metrics):
# Process the step in the environment
# Ensure raw_actions is a 1D array
raw_actions = np.squeeze(raw_actions)
# Run simulation with new parameters
performance_metrics, temp_netlist_path = run_simulation(raw_actions)
# Convert to graph representation
node_features_tensor, edge_index = netlist_to_graph(temp_netlist_path)
# Calculate reward based on performance metrics and transistor_regions
reward = self.calculate_reward(performance_metrics, previous_metrics)
# Check if the episode is done
done = self.check_done(performance_metrics)
# Update previous_metrics for the next step
previous_metrics = performance_metrics
# Update class variables
self.node_features_tensor = node_features_tensor
self.edge_index = edge_index
return node_features_tensor, edge_index, reward, done, previous_metrics
def is_performance_metrics_in_target(self, metrics):
return np.all(metrics >= self.PERFORMANCE_METRICS_TARGET_LOW) and np.all(metrics <= self.PERFORMANCE_METRICS_TARGET_HIGH)
def calculate_reward(self, c_metrics, p_metrics):
metrics_order = ['gain', 'bw', 'ugf', 'pm']
reward = 0
current_metrics = np.array([c_metrics[k] for k in metrics_order])
performance_metrics_in_target = self.is_performance_metrics_in_target(current_metrics)
if performance_metrics_in_target:
reward += 200
return reward
for idx, metric_name in enumerate(metrics_order):
current_value = c_metrics[metric_name]
previous_value = p_metrics[metric_name]
target_low = self.PERFORMANCE_METRICS_TARGET_LOW[idx]
target_high = self.PERFORMANCE_METRICS_TARGET_HIGH[idx]
if metric_name in ['gain', 'bw', 'ugf']:
if current_value > previous_value:
if current_value > target_high:
reward += self.LARGE_REWARD
elif current_value > target_low:
reward += self.SMALL_REWARD
elif previous_value < target_low and current_value > target_low:
reward += self.VERY_HIGH_REWARD
elif current_value < target_low:
reward -= self.LARGE_PENALTY
elif metric_name == 'pm':
if target_low <= current_value <= target_high:
reward += self.LARGE_REWARD
if previous_value < target_low or previous_value > target_high:
reward += self.VERY_HIGH_REWARD
else:
reward -= self.LARGE_PENALTY
if current_value < previous_value and current_value < target_low:
reward -= self.PENALTY
elif current_value > previous_value and current_value > target_high:
reward -= self.PENALTY
if metric_name == 'gain' and current_value < 0:
reward -= 100
return reward
def check_done(self, performance_metrics):
# Check if all performance metrics are within target range and saturation condition is met
for metric, value in performance_metrics.items():
lower_bound, upper_bound = self.target_metrics[metric]
if not (lower_bound <= value <= upper_bound):
return False
return True
import numpy as np
class CircuitEnvironment:
PERFORMANCE_METRICS_TARGET_LOW = np.array([48, 30e3, 10e6, 60])
PERFORMANCE_METRICS_TARGET_HIGH = np.array([100, 100e3, 100e6, 75])
LARGE_REWARD = 10
SMALL_REWARD = 1
VERY_HIGH_REWARD = 20
LARGE_PENALTY = -10
PENALTY = -1
def __init__(self, bounds_low, bounds_high, technology_file=None):
# Initialization code: setup bounds, target metrics, etc.
self.bounds_low = bounds_low
self.bounds_high = bounds_high
self.technology_file = technology_file
self.load_technology_file()
# Initialize tensors as None
self.node_features_tensor = None
self.edge_index = None
self.target_metrics = None
def load_technology_file(self):
if self.technology_file:
# Pseudo code for loading technology file
print(f"Loaded technology file: {self.technology_file}")
@staticmethod
def generate_random_targets(num_targets, seed):
np.random.seed(seed)
target_ranges = CircuitEnvironment.PERFORMANCE_METRICS_TARGET_HIGH - CircuitEnvironment.PERFORMANCE_METRICS_TARGET_LOW
random_targets = np.random.rand(num_targets, 4) * target_ranges + CircuitEnvironment.PERFORMANCE_METRICS_TARGET_LOW
return random_targets.astype(int)
def reset(self, target_metrics=None):
# Environment reset: typically would reset the simulator state and return initial observation
if target_metrics is not None:
self.target_metrics = target_metrics
# Initialize parameters within bounds
initial_parameters = np.random.uniform(self.bounds_low, self.bounds_high)
# Run simulation with initial parameters
performance_metrics, temp_netlist_path = run_simulation(initial_parameters)
# Process netlist to generate model inputs
node_features_tensor, edge_index = netlist_to_graph(temp_netlist_path)
# Update class variables
self.node_features_tensor = node_features_tensor
self.edge_index = edge_index
return node_features_tensor, edge_index, performance_metrics
def step(self, raw_actions):
# Process the step in the environment
# Ensure raw_actions is a 1D array
raw_actions = np.squeeze(raw_actions)
# Run simulation with new parameters
performance_metrics, temp_netlist_path = run_simulation(raw_actions)
# Convert to graph representation
node_features_tensor, edge_index = netlist_to_graph(temp_netlist_path)
# Calculate reward based on performance metrics
reward = self.calculate_reward(performance_metrics)
# Check if the episode is done
done = self.check_done(performance_metrics)
# Update class variables
self.node_features_tensor = node_features_tensor
self.edge_index = edge_index
return node_features_tensor, edge_index, reward, done
def is_performance_metrics_in_target(self, metrics):
return np.all(metrics >= self.PERFORMANCE_METRICS_TARGET_LOW) and np.all(metrics <= self.PERFORMANCE_METRICS_TARGET_HIGH)
def calculate_reward(self, c_metrics):
metrics_order = ['gain', 'bw', 'ugf', 'pm']
reward = 0
current_metrics = np.array([c_metrics[k] for k in metrics_order])
performance_metrics_in_target = self.is_performance_metrics_in_target(current_metrics)
if performance_metrics_in_target:
reward += 200
return reward
for idx, metric_name in enumerate(metrics_order):
current_value = c_metrics[metric_name]
target_low = self.PERFORMANCE_METRICS_TARGET_LOW[idx]
target_high = self.PERFORMANCE_METRICS_TARGET_HIGH[idx]
if metric_name in ['gain', 'bw', 'ugf']:
if current_value > target_high:
reward += self.LARGE_REWARD
elif target_low <= current_value <= target_high:
reward += self.SMALL_REWARD
else:
reward -= self.LARGE_PENALTY
elif metric_name == 'pm':
if target_low <= current_value <= target_high:
reward += self.LARGE_REWARD
else:
reward -= self.LARGE_PENALTY
if current_value < 0:
reward -= 100
return reward
def check_done(self, performance_metrics):
if self.target_metrics is None:
return False
for idx, metric_name in enumerate(['gain', 'bw', 'ugf', 'pm']):
lower_bound, upper_bound = self.target_metrics[idx]
if not (lower_bound <= performance_metrics[metric_name] <= upper_bound):
return False
return True
# Example usage
train_targets = CircuitEnvironment.generate_random_targets(num_targets=100, seed=0)
test_targets = CircuitEnvironment.generate_random_targets(num_targets=20, seed=1)
# Initialize environment
bounds_low = np.array([0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 15e-6, 0.1e-12, 0.8])
bounds_high = np.array([50e-6, 50e-6, 50e-6, 50e-6, 50e-6, 30e-6, 10e-12, 1.4])
env = CircuitEnvironment(bounds_low, bounds_high, technology_file="default_tech_file.json")
With these changes, the CircuitEnvironment class can now handle generating new targets for both training and testing, incorporate stop criteria, and manage technology files.
Please provide the second and third parts of your code so we can continue updating them to fit your new requirements.
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Check if a previous training state exists and load it
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['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']
print(f"Resuming from episode {start_episode}")
for episode in range(start_episode, num_episodes):
node_features_tensor, edge_index, performance_metrics = env.reset()
state = (node_features_tensor, edge_index)
episode_rewards = []
states = []
actions = []
log_probs = []
values = []
masks = []
perf_metrics_log = []
start_time2 = time.time()
for t in range(max_timesteps):
start_time1 = time.time()
# Selecting action based on the current state
action, log_prob, perf_metrics = agent.select_action(state, performance_metrics)
start_time = time.time()
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action, perf_metrics)
end_time = time.time()
runtime = end_time - start_time
print(f"runtime: {runtime} seconds")
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
end_time1 = time.time()
runtime1 = end_time1 - start_time1
print(f"runtime1: {runtime1} seconds")
if done:
break
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
# Correcting format for updating the policy
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
# Update the policy with collected data
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)
# Compute mean episode reward and deployment accuracy (example placeholders)
mean_episode_reward = total_reward / episode_length
deployment_accuracy = calculate_accuracy(perf_metrics_log)
# Compute minimum and maximum episode rewards
min_episode_reward = min(episode_rewards)
max_episode_reward = max(episode_rewards)
# Append to logs for pandas DataFrame
rewards_log.append({'episode': episode + 1, 'total_reward': total_reward})
losses_log.append({'episode': episode + 1, 'actor_loss': average_loss_actor, 'critic_loss': average_loss_critic})
metrics_log.append({'episode': episode + 1, 'Mean Episode Reward': mean_episode_reward, 'Min Episode Reward': min_episode_reward, 'Max Episode Reward': max_episode_reward, 'Deployment Accuracy': deployment_accuracy})
episode_lengths.append(episode_length)
# Save model checkpoints and pandas data frame logging every n episodes
agent.save_checkpoint(episode)
if episode % 5 == 0 or episode == num_episodes - 1:
# Calls to ‘pd.DataFrame.to_csv’ replaced with conditional checkpoint inside loop
pd.DataFrame(rewards_log).to_csv(os.path.join(agent.log_dir, 'rewards_log.csv'), index=False)
pd.DataFrame(losses_log).to_csv(os.path.join(agent.log_dir, 'losses_log.csv'), index=False)
pd.DataFrame(metrics_log).to_csv(os.path.join(agent.log_dir, 'metrics_log.csv'), index=False)
# Save the current training state
save_training_state(agent, episode, rewards_log, losses_log, metrics_log)
# Final save for logs
pd.DataFrame(rewards_log).to_csv(os.path.join(agent.log_dir, 'final_rewards_log.csv'), index=False)
pd.DataFrame(losses_log).to_csv(os.path.join(agent.log_dir, 'final_losses_log.csv'), index=False)
pd.DataFrame(metrics_log).to_csv(os.path.join(agent.log_dir, 'final_metrics_log.csv'), index=False)
# Consider also saving final model checkpoints
agent.save_checkpoint('final')
logging.info("Training Completed.")
in_channels = 23 # Number of input features
out_channels = 23 # Number of output actions or features
state_dim = 23 # Dimension of state representation, to match critic input
action_space = 8 # Environment’s action space
lr_actor = 1e-4
lr_critic = 3e-4
gamma = 0.99
gae_lambda = 0.95
epsilon = 0.2
policy_clip = 0.2
epochs = 10
entropy_coef=0.01
import os
import torch
import numpy as np
import time
import pandas as pd
import logging
# save and load process for training process
def save_training_state(agent, episode, rewards_log, losses_log, metrics_log, filepath='training_state_LTS1.pt'):
state = {
'episode': episode,
'actor_state_dict': agent.actor.state_dict(),
'critic_state_dict': agent.critic.state_dict(),
'optimizer_actor_state_dict': agent.optimizer_actor.state_dict(),
'optimizer_critic_state_dict': agent.optimizer_critic.state_dict(),
'rewards_log': rewards_log,
'losses_log': losses_log,
'metrics_log': metrics_log
}
torch.save(state, filepath)
def load_training_state(filepath='training_state_LTS1.pt'):
if os.path.isfile(filepath):
state = torch.load(filepath)
return state
else:
return None
def train(env, agent, num_episodes, max_timesteps):
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Check if a previous training state exists and load it
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['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']
print(f"Resuming from episode {start_episode}")
# Generate random target metrics for training
train_targets = CircuitEnvironment.generate_random_targets(num_targets=100, seed=0)
for episode in range(start_episode, num_episodes):
# Select a random target for this episode
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):
start_time1 = time.time()
# Selecting action based on the current state
action, log_prob, perf_metrics = agent.select_action(state, performance_metrics)
start_time = time.time()
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action)
end_time = time.time()
runtime = end_time - start_time
print(f"runtime: {runtime} seconds")
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
end_time1 = time.time()
runtime1 = end_time1 - start_time1
print(f"runtime1: {runtime1} seconds")
if done:
break
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
# Correcting format for updating the policy
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
# Update the policy with collected data
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)
# Compute mean episode reward and deployment accuracy (example placeholders)
mean_episode_reward = total_reward / episode_length
deployment_accuracy = calculate_accuracy(perf_metrics_log)
# Compute minimum and maximum episode rewards
min_episode_reward = min(episode_rewards)
max_episode_reward = max(episode_rewards)
# Append to logs for pandas DataFrame
rewards_log.append({'episode': episode + 1, 'total_reward': total_reward})
losses_log.append({'episode': episode + 1, 'actor_loss': average_loss_actor, 'critic_loss': average_loss_critic})
metrics_log.append({'episode': episode + 1, 'Mean Episode Reward': mean_episode_reward, 'Min Episode Reward': min_episode_reward, 'Max Episode Reward': max_episode_reward, 'Deployment Accuracy': deployment_accuracy})
episode_lengths.append(episode_length)
# Save model checkpoints and pandas data frame logging every n episodes
agent.save_checkpoint(episode)
if episode % 5 == 0 or episode == num_episodes - 1:
# Calls to ‘pd.DataFrame.to_csv’ replaced with conditional checkpoint inside loop
pd.DataFrame(rewards_log).to_csv(os.path.join(agent.log_dir, 'rewards_log.csv'), index=False)
pd.DataFrame(losses_log).to_csv(os.path.join(agent.log_dir, 'losses_log.csv'), index=False)
pd.DataFrame(metrics_log).to_csv(os.path.join(agent.log_dir, 'metrics_log.csv'), index=False)
# Save the current training state
save_training_state(agent, episode, rewards_log, losses_log, metrics_log)
# Final save for logs
pd.DataFrame(rewards_log).to_csv(os.path.join(agent.log_dir, 'final_rewards_log.csv'), index=False)
pd.DataFrame(losses_log).to_csv(os.path.join(agent.log_dir, 'final_losses_log.csv'), index=False)
pd.DataFrame(metrics_log).to_csv(os.path.join(agent.log_dir, 'final_metrics_log.csv'), index=False)
# Consider also saving final model checkpoints
agent.save_checkpoint('final')
logging.info("Training Completed.")
# Initialize environment parameters
# Define the values for bounds, and target metrics
bounds_low = np.array([0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 15e-6, 0.1e-12, 0.8])
bounds_high = np.array([50e-6, 50e-6, 50e-6, 50e-6, 50e-6, 30e-6, 10e-12, 1.4])
target_metrics = {
'gain': (48, 100),
'bw': (30e3, 100e3),
'ugf': (10e6, 100e6),
'pm': (60, 75)
}
# Define the constants and target metrics for reward calculation
CircuitEnvironment.PERFORMANCE_METRICS_TARGET_LOW = np.array([48, 30e3, 10e6, 60])
CircuitEnvironment.PERFORMANCE_METRICS_TARGET_HIGH = np.array([100, 100e3, 100e6, 75])
CircuitEnvironment.VERY_HIGH_REWARD = 20
CircuitEnvironment.LARGE_REWARD = 10
CircuitEnvironment.SMALL_REWARD = 5
CircuitEnvironment.PENALTY = 5
CircuitEnvironment.LARGE_PENALTY = 10
# Initialize Hyperparameters
in_channels = 23 # Number of input features
out_channels = 23 # Number of output actions or features
state_dim = 23 # Dimension of state representation, to match critic input
action_space = 8 # Environment’s action space
lr_actor = 1e-4
lr_critic = 3e-4
gamma = 0.99
gae_lambda = 0.95
epsilon = 0.2
policy_clip = 0.2
epochs = 10
entropy_coef=0.01
# Initialize parameters for trainnig agent
num_episodes = 1000
max_timesteps = 100
# Create the environment
env = CircuitEnvironment(bounds_low, bounds_high, technology_file="default_tech_file.json")
agent = PPOAgent(state_dim, action_space, lr_actor, lr_critic, gamma, gae_lambda, epsilon, policy_clip, epochs, entropy_coef)
# Train agent
train(env, agent, num_episodes, max_timesteps)
Explanation of the Changes:
Random Target Metric Generation for Training:
train_targets are generated using the CircuitEnvironment.generate_random_targets method.
Each episode selects one of these targets for training, ensuring different conditions in each run.
Modified train Function:
Uses env.reset(target) to pass the randomly selected target metric for each episode.
Loading and Saving State:
Modified to handle saving and loading of the new setup with the save_training_state and load_training_state functions.
Next Steps:
Please provide the third part of your code. This will allow me to integrate these changes throughout your entire implementation.
gnn_model_actor = CustomGNN(in_channels=state_dim, out_channels=23)
gnn_model_critic = CustomGNN(in_channels=state_dim, out_channels=23)
self.actor = Actor(gnn_model_actor)
self.critic = Critic(gnn_model_critic)
self.optimizer_actor = optim.Adam(self.actor.parameters(), lr=lr_actor)
self.optimizer_critic = optim.Adam(self.critic.parameters(), lr=lr_critic)
self.action_space = action_space # Assume continuous
self.log_dir = 'OPAMP_GNNRL_LTS1_log_file'
os.makedirs(self.log_dir, exist_ok=True)
def save_checkpoint(self, episode):
torch.save(self.actor.state_dict(), os.path.join(self.log_dir, f'actor_{episode}.pt'))
torch.save(self.critic.state_dict(), os.path.join(self.log_dir, f'critic_{episode}.pt'))
def load_checkpoint(self, episode):
self.actor.load_state_dict(torch.load(os.path.join(self.log_dir, f'actor_{episode}.pt')))
self.critic.load_state_dict(torch.load(os.path.join(self.log_dir, f'critic_{episode}.pt')))
def select_action(self, state, performance_metrics):
action_means, action_stds = self.actor(state)
#print("action_means", action_means)
dist = torch.distributions.Normal(action_means, action_stds)
action = dist.sample()
log_probs = dist.log_prob(action).sum(axis=-1) # Summing over actions if action space is multi-dimensional
# Using tanh to squash gnn_output to [-1, 1]
scaled_action = torch.tanh(action)
# Now scale and shift the normalized output to the action bounds
scaled_actions = self.actor.bounds_low + (self.actor.bounds_high - self.actor.bounds_low) * ((scaled_action + 1) / 2)
# Converting to numpy array for easier manipulation
scaled_actions_np = scaled_actions.detach().numpy()
# Rounding operations as per requirements
rounded_actions = np.zeros_like(scaled_actions_np)
# Rounding to two decimal places after scaling by 1e-6 for L1, L3, L5, L6, L7, W1, W3, W5, W6, W7
rounded_actions[:5] = np.round(scaled_actions_np[:5] * 1e6, 2) / 1e6
# Rounding to the nearest whole number after scaling by 1e-6 for Ib
rounded_actions[5] = np.round(scaled_actions_np[5] * 1e6) / 1e6
# Rounding to one decimal place for Cc. Scale by 1e12, round, and scale back.
rounded_actions[6] = np.round(scaled_actions_np[6] * 1e12, 1) / 1e12
# Rounding to one decimal place for Vb directly
rounded_actions[7] = np.round(scaled_actions_np[7], 1) # for Vb
print("rounded_actions", rounded_actions)
return rounded_actions, log_probs.detach(), performance_metrics
def compute_gae(self, next_value, rewards, masks, values):
# Generalized Advantage Estimation (GAE)
returns = []
gae = 0
for step in reversed(range(len(rewards))):
delta = rewards[step] + self.gamma * next_value * masks[step] - values[step]
gae = delta + self.gamma * self.gae_lambda * masks[step] * gae
returns.insert(0, gae + values[step])
next_value = values[step]
return returns
def update_policy(self, prev_states, prev_actions, prev_log_probs, returns, advantages):
device = next(self.actor.parameters()).device # Get the device from the actor model
advantages = torch.tensor(advantages, dtype=torch.float32, device=device)
returns = torch.tensor(returns, dtype=torch.float32, device=device)
prev_log_probs = torch.tensor(prev_log_probs, dtype=torch.float32, device=device)
# Initialize lists to accumulate losses
actor_losses = []
critic_losses = []
for _ in range(self.epochs):
log_probs_batch, state_values_batch, entropies_batch = [], [], []
for state, action in zip(prev_states, prev_actions):
node_features_tensor, edge_index = state
node_features_tensor = node_features_tensor.to(device)
edge_index = edge_index.to(device) if edge_index is not None else None
action_means, action_stds = self.actor(state)
# Getting the state value prediction from the critic using the flattened state
state_value = self.critic(node_features_tensor, edge_index).unsqueeze(0) # Direct application with adjusted state
dist = torch.distributions.Normal(action_means, action_stds)
action_tensor = torch.tensor(action, dtype=torch.float32, device=action_means.device)
log_prob = dist.log_prob(action_tensor).sum(axis=-1).unsqueeze(0)
log_probs_batch.append(log_prob)
entropy = dist.entropy().sum(axis=-1).unsqueeze(0)
entropies_batch.append(entropy)
state_values_batch.append(state_value) # No additional unsqueeze(0) needed here after correction
# Convert to tensors
log_probs = torch.cat(log_probs_batch).to(prev_log_probs.device)
state_values = torch.cat(state_values_batch).squeeze(-1).to(returns.device) # Ensuring the correct final shape for state_values
entropy = torch.cat(entropies_batch)
# Surrogate function
ratios = torch.exp(log_probs - prev_log_probs)
#advantages_batch = returns - state_values.detach()
surr1 = ratios * advantages
surr2 = torch.clamp(ratios, 1.0 - self.policy_clip, 1.0 + self.policy_clip) * advantages
actor_loss = - torch.min(surr1, surr2).mean() - self.entropy_coef * entropy.mean()
critic_loss = F.mse_loss(state_values, returns)
# Update actor
self.optimizer_actor.zero_grad()
#actor_loss.backward()
actor_loss.backward(retain_graph=True)
torch.nn.utils.clip_grad_norm_(self.actor.parameters(), max_norm=1.0)
self.optimizer_actor.step()
# Update critic
self.optimizer_critic.zero_grad()
critic_loss.backward()
torch.nn.utils.clip_grad_norm_(self.critic.parameters(), max_norm=1.0)
self.optimizer_critic.step()
# Append the item loss to the lists
actor_losses.append(actor_loss.item()) # Use item() to extract scalar value
critic_losses.append(critic_loss.item()) # Use item() to extract scalar value
# Calculate average loss over all epochs
average_loss_actor = sum(actor_losses) / len(actor_losses)
average_loss_critic = sum(critic_losses) / len(critic_losses)
return average_loss_actor, average_loss_critic
import torch
import torch.nn.functional as F
import torch.optim as optim
import os
import numpy as np
# Assuming CustomGNN, Actor, and Critic classes are defined elsewhere
class PPOAgent:
def __init__(self, state_dim, action_space, lr_actor, lr_critic, gamma, gae_lambda, epsilon, policy_clip, epochs, entropy_coef):
self.gamma = gamma
self.gae_lambda = gae_lambda
self.epsilon = epsilon
self.policy_clip = policy_clip
self.epochs = epochs
self.entropy_coef = entropy_coef # Dynamic entropy coefficient
gnn_model_actor = CustomGNN(in_channels=state_dim, out_channels=23)
gnn_model_critic = CustomGNN(in_channels=state_dim, out_channels=23)
self.actor = Actor(gnn_model_actor)
self.critic = Critic(gnn_model_critic)
self.optimizer_actor = optim.Adam(self.actor.parameters(), lr=lr_actor)
self.optimizer_critic = optim.Adam(self.critic.parameters(), lr=lr_critic)
self.action_space = action_space # Assume continuous
self.log_dir = 'OPAMP_GNNRL_LTS1_log_file'
os.makedirs(self.log_dir, exist_ok=True)
# Initialize action bounds (assumed they are available in Actor module)
self.bounds_low = np.array([0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 15e-6, 0.1e-12, 0.8])
self.bounds_high = np.array([50e-6, 50e-6, 50e-6, 50e-6, 50e-6, 30e-6, 10e-12, 1.4])
def save_checkpoint(self, episode):
torch.save(self.actor.state_dict(), os.path.join(self.log_dir, f'actor_{episode}.pt'))
torch.save(self.critic.state_dict(), os.path.join(self.log_dir, f'critic_{episode}.pt'))
def load_checkpoint(self, episode):
self.actor.load_state_dict(torch.load(os.path.join(self.log_dir, f'actor_{episode}.pt')))
self.critic.load_state_dict(torch.load(os.path.join(self.log_dir, f'critic_{episode}.pt')))
def select_action(self, state):
action_means, action_stds = self.actor(state)
dist = torch.distributions.Normal(action_means, action_stds)
action = dist.sample()
log_probs = dist.log_prob(action).sum(axis=-1) # Summing over actions if action space is multi-dimensional
# Using tanh to squash gnn_output to [-1, 1]
scaled_action = torch.tanh(action)
# Now scale and shift the normalized output to the action bounds
scaled_actions = self.bounds_low + (self.bounds_high - self.bounds_low) * ((scaled_action + 1) / 2)
# Converting to numpy array for easier manipulation
scaled_actions_np = scaled_actions.detach().numpy()
# Rounding operations as per requirements
rounded_actions = np.zeros_like(scaled_actions_np)
# Rounding to two decimal places after scaling by 1e-6 for W1, W3, W5, W6, W7
rounded_actions[:5] = np.round(scaled_actions_np[:5] * 1e6, 2) / 1e6
# Rounding to the nearest whole number after scaling by 1e-6 for Ib
rounded_actions[5] = np.round(scaled_actions_np[5] * 1e6) / 1e6
# Rounding to one decimal place for Cc. Scale by 1e12, round, and scale back.
rounded_actions[6] = np.round(scaled_actions_np[6] * 1e12, 1) / 1e12
# Rounding to one decimal place for Vc directly
rounded_actions[7] = np.round(scaled_actions_np[7], 1) # for Vc
return rounded_actions, log_probs.detach()
def compute_gae(self, next_value, rewards, masks, values):
# Generalized Advantage Estimation (GAE)
returns = []
gae = 0
for step in reversed(range(len(rewards))):
delta = rewards[step] + self.gamma * next_value * masks[step] - values[step]
gae = delta + self.gamma * self.gae_lambda * masks[step] * gae
returns.insert(0, gae + values[step])
next_value = values[step]
return returns
def update_policy(self, prev_states, prev_actions, prev_log_probs, returns, advantages):
device = next(self.actor.parameters()).device # Get the device from the actor model
advantages = torch.tensor(advantages, dtype=torch.float32, device=device)
returns = torch.tensor(returns, dtype=torch.float32, device=device)
prev_log_probs = torch.tensor(prev_log_probs, dtype=torch.float32, device=device)
# Initialize lists to accumulate losses
actor_losses = []
critic_losses = []
for _ in range(self.epochs):
log_probs_batch, state_values_batch, entropies_batch = [], [], []
for state, action in zip(prev_states, prev_actions):
node_features_tensor, edge_index = state
node_features_tensor = node_features_tensor.to(device)
edge_index = edge_index.to(device) if edge_index is not None else None
action_means, action_stds = self.actor(state)
# Getting the state value prediction from the critic using the flattened state
state_value = self.critic(node_features_tensor, edge_index).unsqueeze(0) # Direct application with adjusted state
dist = torch.distributions.Normal(action_means, action_stds)
action_tensor = torch.tensor(action, dtype=torch.float32, device=action_means.device)
log_prob = dist.log_prob(action_tensor).sum(axis=-1).unsqueeze(0)
log_probs_batch.append(log_prob)
entropy = dist.entropy().sum(axis=-1).unsqueeze(0)
entropies_batch.append(entropy)
state_values_batch.append(state_value) # No additional unsqueeze(0) needed here after correction
# Convert to tensors
log_probs = torch.cat(log_probs_batch).to(prev_log_probs.device)
state_values = torch.cat(state_values_batch).squeeze(-1).to(returns.device) # Ensuring the correct final shape for state_values
entropy = torch.cat(entropies_batch)
# Surrogate function
ratios = torch.exp(log_probs - prev_log_probs)
#advantages_batch = returns - state_values.detach()
surr1 = ratios * advantages
surr2 = torch.clamp(ratios, 1.0 - self.policy_clip, 1.0 + self.policy_clip) * advantages
actor_loss = - torch.min(surr1, surr2).mean() - self.entropy_coef * entropy.mean()
critic_loss = F.mse_loss(state_values, returns)
# Update actor
self.optimizer_actor.zero_grad()
actor_loss.backward(retain_graph=True)
torch.nn.utils.clip_grad_norm_(self.actor.parameters(), max_norm=1.0)
self.optimizer_actor.step()
# Update critic
self.optimizer_critic.zero_grad()
critic_loss.backward()
torch.nn.utils.clip_grad_norm_(self.critic.parameters(), max_norm=1.0)
self.optimizer_critic.step()
# Append the item loss to the lists
actor_losses.append(actor_loss.item()) # Use item() to extract scalar value
critic_losses.append(critic_loss.item()) # Use item() to extract scalar value
# Calculate average loss over all epochs
average_loss_actor = sum(actor_losses) / len(actor_losses)
average_loss_critic = sum(critic_losses) / len(critic_losses)
return average_loss_actor, average_loss_critic
Explanation of the Changes
Action Bounds Initialization:
Added self.bounds_low and self.bounds_high initialization based on the given bounds.
Action Selection:
The logic for action scaling and rounding has been retained for discretizing continuous actions based on specified rules.
Saving and Loading Checkpoints:
Implemented consistent methods to save and load model checkpoints to ensure they can be saved and restored properly during training.
Summary of Changes
Random Target Metric Generation:
CircuitEnvironment.generate_random_targets ensures unique training and testing sets.
Training Process:
Training function adjusted to select specific targets per episode.
Action Selection:
Updated the action bounds within PPOAgent.select_action and ensured they are scaled and rounded correctly.
Next Steps
Integrate this updated PPOAgent and the modified train function (from Splitup 2) with the enhanced CircuitEnvironment class (from Splitup 1). This will allow your agent to train and test using non-overlapping target metrics effectively and handle different technology files as needed.
import time
import logging
def train(env, agent, num_episodes, max_timesteps):
# Generate random target metrics if not loaded
train_targets = CircuitEnvironment.generate_random_targets(num_targets=100, seed=0)
test_targets = CircuitEnvironment.generate_random_targets(num_targets=20, seed=1)
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Check if a previous training state exists and load it
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['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):
# Select a random target for this episode (cyclic access to train 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):
start_time1 = time.time()
# Selecting action based on the current state
action, log_prob = agent.select_action(state)
start_time = time.time()
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action)
end_time = time.time()
runtime = end_time - start_time
print(f"runtime: {runtime} seconds")
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(performance_metrics)
performance_metrics = previous_metrics
state = next_state
end_time1 = time.time()
runtime1 = end_time1 - start_time1
print(f"runtime1: {runtime1} seconds")
if done:
break
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
# Correcting format for updating the policy
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
# Update the policy with collected data
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)
# Compute mean episode reward and deployment accuracy (example placeholders)
mean_episode_reward = total_reward / episode_length
deployment_accuracy = calculate_accuracy(perf_metrics_log)
# Compute minimum and maximum episode rewards
min_episode_reward = min(episode_rewards)
max_episode_reward = max(episode_rewards)
# Append to logs for pandas DataFrame
rewards_log.append({'episode': episode + 1, 'total_reward': total_reward})
losses_log.append({'episode': episode + 1, 'actor_loss': average_loss_actor, 'critic_loss': average_loss_critic})
metrics_log.append({'episode': episode + 1, 'Mean Episode Reward': mean_episode_reward, 'Min Episode Reward': min_episode_reward, 'Max Episode Reward': max_episode_reward, 'Deployment Accuracy': deployment_accuracy})
episode_lengths.append(episode_length)
# Save model checkpoints and pandas data frame logging every n episodes
agent.save_checkpoint(episode)
if episode % 5 == 0 or episode == num_episodes - 1:
# Calls to ‘pd.DataFrame.to_csv’ replaced with conditional checkpoint inside loop
pd.DataFrame(rewards_log).to_csv(os.path.join(agent.log_dir, 'rewards_log.csv'), index=False)
pd.DataFrame(losses_log).to_csv(os.path.join(agent.log_dir, 'losses_log.csv'), index=False)
pd.DataFrame(metrics_log).to_csv(os.path.join(agent.log_dir, 'metrics_log.csv'), index=False)
# Save the current training state
save_training_state(agent, episode, rewards_log, losses_log, metrics_log, train_targets, test_targets)
# Final save for logs
pd.DataFrame(rewards_log).to_csv(os.path.join(agent.log_dir, 'final_rewards_log.csv'), index=False)
pd.DataFrame(losses_log).to_csv(os.path.join(agent.log_dir, 'final_losses_log.csv'), index=False)
pd.DataFrame(metrics_log).to_csv(os.path.join(agent.log_dir, 'final_metrics_log.csv'), index=False)
# Consider also saving final model checkpoints
agent.save_checkpoint('final')
logging.info("Training Completed.")
Testing Function
Create a separate function for testing the trained agent with new target metrics and technology files.
python
def test(env, agent, num_targets, testing_separate_targets=True):
# Generate separate test targets if not using pre-loaded
if testing_separate_targets:
test_targets = CircuitEnvironment.generate_random_targets(num_targets=num_targets, seed=1)
rewards_log = []
metrics_log = []
for i, target in enumerate(test_targets):
node_features_tensor, edge_index, performance_metrics = env.reset(target)
state = (node_features_tensor, edge_index)
episode_rewards = []
states = []
actions = []
values = []
masks = []
perf_metrics_log = []
done = False
while not done:
# Selecting action based on the current state
action, log_prob = agent.select_action(state)
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action)
state = (next_node_features_tensor, next_edge_index)
episode_rewards.append(reward)
perf_metrics_log.append(performance_metrics)
performance_metrics = previous_metrics
total_reward = sum(episode_rewards)
# Compute mean episode reward and deployment accuracy (example placeholders)
mean_episode_reward = total_reward / len(episode_rewards)
deployment_accuracy = calculate_accuracy(perf_metrics_log)
# Append to logs for pandas DataFrame
rewards_log.append({'episode': i + 1, 'total_reward': total_reward})
metrics_log.append({'episode': i + 1, 'Mean Episode Reward': mean_episode_reward, 'Deployment Accuracy': deployment_accuracy})
# Final save for logs
log_dir = 'OPAMP_GNNRL_LTS1_test_log_file'
os.makedirs(log_dir, exist_ok=True)
pd.DataFrame(rewards_log).to_csv(os.path.join(log_dir, 'test_rewards_log.csv'), index=False)
pd.DataFrame(metrics_log).to_csv(os.path.join(log_dir, 'test_metrics_log.csv'), index=False)
logging.info("Testing Completed.")
Main Script
Finally, ensure you have the correct sequence to first train and then test the agent.
Updated to include saving and loading of train_targets and test_targets.
Train Function:
Loads training state and resumes correctly.
Selects different targets for each episode from train_targets.
Test Function:
Tests the trained agent on new target specifications, logging the results.
Main Script:
Sequentially trains the agent and then tests it using a possibly different CMOS technology file.
With these updates, you'll be able to save and load crucial state information, ensuring continuity between training sessions, and evaluate your agent under different conditions systematically.
def train(env, agent, num_episodes, max_timesteps):
# Default initialization
train_targets = CircuitEnvironment.generate_random_targets(num_targets=100, seed=0)
test_targets = CircuitEnvironment.generate_random_targets(num_targets=20, seed=1)
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
# Check if a previous training state exists and load it
saved_state = load_training_state()
if saved_state:
start_episode = saved_state['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):
# Select a random target for this episode (cyclic access to train 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):
start_time1 = time.time()
# Selecting action based on the current state
action, log_prob = agent.select_action(state)
start_time = time.time()
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action)
end_time = time.time()
runtime = end_time - start_time
print(f"runtime: {runtime} seconds")
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(performance_metrics)
performance_metrics = previous_metrics
state = next_state
end_time1 = time.time()
runtime1 = end_time1 - start_time1
print(f"runtime1: {runtime1} seconds")
if done:
break
next_value = agent.critic(state[0], state[1]).item() if not done else 0
returns = agent.compute_gae(next_value, episode_rewards, masks, values)
# Correcting format for updating the policy
advantages = (torch.tensor(returns) - torch.tensor(values)).detach().numpy()
returns = torch.tensor(returns).detach().numpy()
# Update the policy with collected data
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)
# Compute mean episode reward and deployment accuracy (example placeholders)
mean_episode_reward = total_reward / episode_length
deployment_accuracy = calculate_accuracy(perf_metrics_log)
# Compute minimum and maximum episode rewards
min_episode_reward = min(episode_rewards)
max_episode_reward = max(episode_rewards)
# Append to logs for pandas DataFrame
rewards_log.append({'episode': episode + 1, 'total_reward': total_reward})
losses_log.append({'episode': episode + 1, 'actor_loss': average_loss_actor, 'critic_loss': average_loss_critic})
metrics_log.append({'episode': episode + 1, 'Mean Episode Reward': mean_episode_reward, 'Min Episode Reward': min_episode_reward, 'Max Episode Reward': max_episode_reward, 'Deployment Accuracy': deployment_accuracy})
episode_lengths.append(episode_length)
# Save model checkpoints and pandas data frame logging every n episodes
agent.save_checkpoint(episode)
if episode % 5 == 0 or episode == num_episodes - 1:
# Calls to ‘pd.DataFrame.to_csv’ replaced with conditional checkpoint inside loop
pd.DataFrame(rewards_log).to_csv(os.path.join(agent.log_dir, 'rewards_log.csv'), index=False)
pd.DataFrame(losses_log).to_csv(os.path.join(agent.log_dir, 'losses_log.csv'), index=False)
pd.DataFrame(metrics_log).to_csv(os.path.join(agent.log_dir, 'metrics_log.csv'), index=False)
# Save the current training state
save_training_state(agent, episode, rewards_log, losses_log, metrics_log, train_targets, test_targets)
# Final save for logs
pd.DataFrame(rewards_log).to_csv(os.path.join(agent.log_dir, 'final_rewards_log.csv'), index=False)
pd.DataFrame(losses_log).to_csv(os.path.join(agent.log_dir, 'final_losses_log.csv'), index=False)
pd.DataFrame(metrics_log).to_csv(os.path.join(agent.log_dir, 'final_metrics_log.csv'), index=False)
# Consider also saving final model checkpoints
agent.save_checkpoint('final')
logging.info("Training Completed.")
Test Function
Make sure the test function only loads the test targets and uses them.
python
def test(env, agent, num_targets, test_targets=None):
rewards_log = []
metrics_log = []
if not test_targets:
test_targets = CircuitEnvironment.generate_random_targets(num_targets=num_targets, seed=1) # Default behavior for new test
for i, target in enumerate(test_targets):
node_features_tensor, edge_index, performance_metrics = env.reset(target)
state = (node_features_tensor, edge_index)
episode_rewards = []
states = []
actions = []
values = []
masks = []
perf_metrics_log = []
done = False
while not done:
# Selecting action based on the current state
action, log_prob = agent.select_action(state)
next_node_features_tensor, next_edge_index, reward, done, previous_metrics = env.step(action)
state = (next_node_features_tensor, next_edge_index)
episode_rewards.append(reward)
perf_metrics_log.append(performance_metrics)
performance_metrics = previous_metrics
total_reward = sum(episode_rewards)
# Compute mean episode reward and deployment accuracy (example placeholders)
mean_episode_reward = total_reward / len(episode_rewards)
deployment_accuracy = calculate_accuracy(perf_metrics_log)
# Append to logs for pandas DataFrame
rewards_log.append({'episode': i + 1, 'total_reward': total_reward})
metrics_log.append({'episode': i + 1, 'Mean Episode Reward': mean_episode_reward, 'Deployment Accuracy': deployment_accuracy})
# Final save for logs
log_dir = 'OPAMP_GNNRL_LTS1_test_log_file'
os.makedirs(log_dir, exist_ok=True)
pd.DataFrame(rewards_log).to_csv(os.path.join(log_dir, 'test_rewards_log.csv'), index=False)
pd.DataFrame(metrics_log).to_csv(os.path.join(log_dir, 'test_metrics_log.csv'), index=False)
logging.info("Testing Completed.")
Main Script
Tie everything together in the main script:
python
# Main Script
import logging
# Initialization parameters
bounds_low = np.array([0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 15e-6, 0.1e-12, 0.8])
bounds_high = np.array([50e-6, 50e-6, 50e-6, 50e-6, 50e-6, 30e-6, 10e-12, 1.4])
# PPO Hyperparameters
state_dim = 23
action_space = 8
lr_actor = 1e-4
lr_critic = 3e-4
gamma = 0.99
gae_lambda = 0.95
epsilon = 0.2
policy_clip = 0.2
epochs = 10
entropy_coef = 0.01
# Create the environment
env = CircuitEnvironment(bounds_low, bounds_high, technology_file="default_tech_file.json")
agent = PPOAgent(state_dim, action_space, lr_actor, lr_critic, gamma, gae_lambda, epsilon, policy_clip, epochs, entropy_coef)
num_episodes = 1000
max_timesteps = 100
# Train the agent
train(env, agent, num_episodes, max_timesteps)
# Load the trained model for testing
trained_state = load_training_state()
if trained_state:
agent.actor.load_state_dict(trained_state['actor_state_dict'])
agent.critic.load_state_dict(trained_state['critic_state_dict'])
test_targets = trained_state['test_targets'] # get the test_targets from saved state
# Test the agent on new targets and potentially different technology file
env_new_tech = CircuitEnvironment(bounds_low, bounds_high, technology_file="new_tech_file.json")
num_test_targets = 20
test(env_new_tech, agent, num_test_targets, test_targets)
This way, the training and testing functions are clearly separated, and each part properly saves and loads the necessary state for continuation across sessions. The test function checks if test targets were provided (from the saved state) and otherwise generates new ones. The train function consistently saves all state information, including the target metrics.