I am getting the following error, please debug the error and modify the code,
RuntimeError: mat1 and mat2 shapes cannot be multiplied (8x13 and 24x64)
I also need you to verify the 'flattened_size = 20 * 24' present in the critic network.
Description of my process:
In my graph network(undirected bipartite), i have fixed topology of component nodes(11 nodes) on one side and net node(9 nodes) on another side(derived from the analog circuit netlist). where i have total 20 nodes and each nodes are having 24 node features and the 38 edges were connected between these 11 component nodes and 9 net nodes (this is my state representation the data from the environment for optimization process) and among the node features of each node where the 24th node represents its stability state. my environment need the action space of values for 13 variables from the actor network as input to the simulator circuit netlist. here few nodes [0, 3, 5, 7, 10, 13, 15, 16] are need to be check for its stability and during optimization process these nodes are need to be keep in stable state.
from my description please verify the 'in_channels', 'out_channels', 'state_dim', 'action_space'
Initialize Hyperparameters
in_channels = 24 # Number of input features
out_channels = 13 # Number of output actions or features
state_dim = 128 # Dimension of state representation, to match critic input
action_space = 13 # Environment’s action space
def forward(self, x, edge_index):
x = F.dropout(x, p=0.2, training=self.training) # p=0.6
x = F.elu(self.gat1(x, edge_index))
# After dropout and activation
#assert torch.equal(X1[:, 0], x[:, 0]), "Order mismatch after dropout/activation."
x = F.dropout(x, p=0.2, training=self.training) # p=0.6
x = self.gat2(x, edge_index)
return x
class Actor(torch.nn.Module):
def init(self, gnn_model):
super(Actor, self).init()
self.gnn = gnn_model
self.stability_head = nn.Sequential(
nn.Linear(24, 64), # Assuming 24 features from GNN’s processed features
nn.ReLU(),
nn.Linear(64, 1) # Outputs a single stability value per node
)
code
# Define bounds for action space scaling
self.bounds_low = torch.tensor([0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6,
0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6,
15e-6, 0.1e-12, 0.8], dtype=torch.float32)
self.bounds_high = torch.tensor([0.181e-6, 0.181e-6, 0.181e-6, 0.181e-6, 0.181e-6,
50e-6, 50e-6, 50e-6, 50e-6, 50e-6,
30e-6, 10e-12, 1.4], dtype=torch.float32)
def forward(self, state):
node_features_tensor, _, edge_index = state
# Processed features from the GNN
processed_features = self.gnn(node_features_tensor, edge_index)
# Example assertion (add after GNN processing)
#assert torch.all(node_features_tensor[:, 0] == processed_features[:, 0]), "Node order mismatch!"
# Initialize stability predictions - assume all nodes as stable
stability_pred = torch.ones(processed_features.size(0), device=processed_features.device)
# Define the indices of nodes that actually require stability prediction
# Given [0, 3, 5, 7, 10, 13, 15, 16] represent tunable/unstable nodes
unstable_nodes_idx = torch.tensor([0, 3, 5, 7, 10, 13, 15, 16], dtype=torch.long, device=processed_features.device)
# Fetch features for nodes requiring stability computation
features_for_stability = processed_features[unstable_nodes_idx]
# Compute stability predictions for these nodes
stability_pred_unstable = self.stability_head(features_for_stability).squeeze(-1)
# Update the overall stability predictions
stability_pred[unstable_nodes_idx] = stability_pred_unstable
# Normalize and scale the GNN outputs to the action bounds for usable actions
normalized_gnn_output = torch.tanh(processed_features)
action_means = self.bounds_low + (self.bounds_high - self.bounds_low) * ((normalized_gnn_output + 1) / 2)
# Define action variances (assuming a simple fixed form here for demonstration)
action_log_std = torch.zeros_like(action_means)
action_std = torch.exp(action_log_std)
return action_means, action_std, stability_pred
class Critic(torch.nn.Module):
def init(self):
super(Critic, self).init()
flattened_size = 20 * 24 # Number of nodes times features per node
self.network = torch.nn.Sequential(
torch.nn.Linear(flattened_size, 128),
torch.nn.ReLU(),
torch.nn.Linear(128, 1)
)
code
def forward(self, state):
# Directly use state as it is already what we referred to as state[0] in evaluate
flattened = state.view(-1) # Flatten to [480]
return self.network(flattened)
Assistant
To debug the error and verify the parameters, I'll break down the issue step by step and make the necessary adjustments.
Debug the RuntimeError: mat1 and mat2 shapes cannot be multiplied (8x13 and 24x64)
The error suggests a mismatch in tensor dimensions during multiplication. This typically happens when the dimensions of matrices in a linear layer don't conform to the expected input-output size relations defined in the model architecture.
Verifying flattened_size in the Critic Network
From the provided information:
20 nodes
24 node features
Hence, the flattened_size - 20 * 24 seems correct. However, let's make sure all tensor dimensions are correctly aligned throughout the architecture.
Evaluating in_channels, out_channels, state_dim, and action_space
in_channels = 24 is correct because each node has 24 features.
out_channels = 13 appears correct per the action space requirement.
state_dim = 128 is consistent with the intermediate dimension used in the critic network.
action_space = 13 is aligned with the 13 output actions needed.
Fixing the Model
I'll adjust the relevant sections to ensure proper input-output tensor dimensions.
Actor Class:
Handle tensors correctly post-GNN layer.
Critic Class:
Verify and correctly flatten tensors.
Modified Code with Debugging:
python
User
in this save and load functions, the dataset generated is saved and retrived during each time loading but the function 'pre_train_agent' is executing on each time loading it does not saved its values for after use on loading on next time.
save and load process for pretraining process(store the dataset and retrive in training phase)
def save_pretraining_state(dataset, pretrain_params, filepath='pretrain_state25_3.pkl'):
"""Save the pre-training state including dataset and generation parameters."""
state = {
'dataset': dataset,
'pretrain_params': pretrain_params
}
with open(filepath, 'wb') as f:
pickle.dump(state, f)
def load_pretraining_state(filepath='pretrain_state25_3.pkl'):
"""Load the pre-training state."""
if os.path.isfile(filepath):
with open(filepath, 'rb') as f:
state = pickle.load(f)
return state
else:
return None
def load_training_state(filepath='training_state25_3.pt'):
if os.path.isfile(filepath):
state = torch.load(filepath)
return state
else:
return None
save and load process for dataset generation
def save_progress(dataset, current_sample, raw_samples, required_samples, filename='progress.pkl'):
"""Save intermediate state to disk."""
with open(filename, 'wb') as f:
pickle.dump((dataset, current_sample, raw_samples, required_samples), f)
def load_progress(filename='progress.pkl'):
"""Load intermediate state from disk."""
if os.path.exists(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
return [], 0, [], 0
def sample_generator(bounds_low, bounds_high, num_samples):
"""Generate samples using Latin Hypercube Sampling."""
dim = len(bounds_low)
code
# Create a Latin Hypercube Sampler
sampler = qmc.LatinHypercube(d=dim)
# Generate normalized samples (0 to 1)
norm_samples = sampler.random(n=num_samples)
# Scale the samples to the given bounds
samples = qmc.scale(norm_samples, bounds_low, bounds_high)
return samples
def pre_training_dataset_generation(env, required_samples=1000, progress_filename='progress.pkl'):
"""Generate pre-training dataset with manual tuning data"""
env.connect_to_simulator() # Ensure simulator is connected before dataset generation
Assistant
Based on your requirements, it appears that although the dataset is saved and loaded correctly, the pre_train_agent function is still executing upon each load. This happens because the pre-trained state of the agent itself (i.e., the weights of the actor network) is not being saved and loaded. We need to ensure that the pre-trained model's weights are saved and restored so that the pre_train_agent function does not need to be re-executed.
Let's extend the save and load functions to include the agent's state after pre-training, followed by ensuring that when we load the dataset, we also check whether the pre-trained model weights are available. This way, we avoid re-running the pre-training phase if it has already been completed previously.
Here's how you can achieve this:
Modify the save_pretraining_state and load_pretraining_state functions to save and load the actor's state dictionary.
When loading the pretraining state, check if the actor's state dictionary exists and load it, skipping the pre-training phase if the actor's state is restored.
Modified Save and Load Functions
python
User
In this below code i expected 'action_means' from the actor network as one row with 13 column list, but i am getting 20 row with 13 column.
Description of my process:
In my graph network(undirected bipartite), i have fixed topology of component nodes(11 nodes) on one side and net node(9 nodes) on another side(derived from the analog circuit netlist). where i have total 20 nodes and each nodes are having 24 node features and the 38 edges were connected between these 11 component nodes and 9 net nodes (this is my state representation the data from the environment for optimization process) and among the node features of each node where the 24th node represents its stability state. my environment need the action space of values for 13 variables from the actor network as input to the simulator circuit netlist. here few nodes [0, 3, 5, 7, 10, 13, 15, 16] are need to be check for its stability and during optimization process these nodes are need to be keep in stable state.
Initialize Hyperparameters
in_channels = 24 # Number of input features
out_channels = 13 # Number of output actions or features
state_dim = 128 # Dimension of state representation, to match critic input
action_space = 13 # Environment’s action space
def forward(self, x, edge_index):
x = F.dropout(x, p=0.2, training=self.training) # p=0.6
x = F.elu(self.gat1(x, edge_index))
# After dropout and activation
#assert torch.equal(X1[:, 0], x[:, 0]), "Order mismatch after dropout/activation."
x = F.dropout(x, p=0.2, training=self.training) # p=0.6
x = self.gat2(x, edge_index)
return x
class Actor(torch.nn.Module):
def init(self, gnn_model):
super(Actor, self).init()
self.gnn = gnn_model
self.stability_head = nn.Sequential(
nn.Linear(out_channels, 64), # Adjusted input to match GNN output features
nn.ReLU(),
nn.Linear(64, 1) # Outputs a single stability value per node
)
code
Assistant
Your issue arises because the GNN is providing an output for each of the 20 nodes in your graph, which is what it's designed to do. Since your environment needs a single set of action values (one row with 13 columns) as input for the simulator, you need to aggregate these GNN node outputs appropriately.
The simplest approach is to apply a pooling operation like global pooling to aggregate node features into a single feature vector per graph. Common pooling strategies include taking the mean or the max of all node feature vectors.
Let's modify your Actor class by including a global pooling operation and then map that pooled vector to the action space.
Modified Code with Global Mean Pooling:
We will use the global mean pooling (averaging all node feature vectors) to aggregate node representations.
python
User
in the pre-training of my actor network in the function 'pre_train_agent', I train the actor network with 1000 data sets, for all the datas I am getting the loss as between 11.94 - 11.97. from the loss result, please describe the training were performed good or not.
def pre_train_agent(agent, dataset):
"""Pre-train the agent using the dataset"""
agent.actor.train()
pretrain_optimizer = optim.Adam(agent.actor.parameters(), lr=1e-4)
scheduler = torch.optim.lr_scheduler.StepLR(pretrain_optimizer, step_size=30, gamma=0.1)
code
for epoch in range(100): # Train for 100 epochs
total_loss = 0
for state, action in dataset:
pretrain_optimizer.zero_grad()
action_means, action_stds, _ = agent.actor(state)
dist = torch.distributions.Normal(action_means, action_stds)
log_probs = dist.log_prob(action).sum(axis=-1)
loss = -log_probs.mean() # Maximize log_probs -> minimize -log_probs
loss.backward()
# Gradient Clipping
torch.nn.utils.clip_grad_norm(agent.actor.parameters(), max_norm=1.0)
pretrain_optimizer.step()
total_loss += loss.item()
scheduler.step()
print(f"Epoch {epoch}, Loss: {total_loss / len(dataset)}")
def forward(self, x, edge_index):
x = F.dropout(x, p=0.2, training=self.training) # p=0.6
x = F.elu(self.gat1(x, edge_index))
# After dropout and activation
#assert torch.equal(X1[:, 0], x[:, 0]), "Order mismatch after dropout/activation."
x = F.dropout(x, p=0.2, training=self.training) # p=0.6
x = self.gat2(x, edge_index)
return x
Assistant
To determine if the training of your Actor network in the pre_train_agent function has been effective, we need to look at the learning process and the reported losses. There are a few considerations to understand the quality of your training:
Understand Log Probability Loss (log_probs):
The loss defined by negative log probability (-log_probs.mean()) should generally decrease over epochs if the model is learning well. This indicates that the predicted distribution is becoming more confident about the actions it outputs.
Consistency of Loss Values:
Seeing the loss values remain very close (11.94 - 11.97) across epochs suggests a few possibilities:
The learning rate might be too low, and hence, the weights are not updating sufficiently per epoch.
The model could be stuck in a local minimum, or the initial random weights might be leading to poor performance.
There might be an issue in the data or the model design that prevents it from learning effectively.
Loss Magnitude:
If the loss remains significantly high, it could indicate potential issues with how the dataset is structured or how the model interprets the data. Given that the loss is around 11.94 to 11.97, in terms of log probabilities, this is quite high and suggests that the model predictions are quite far from the actual distributions.
Steps to Debug and Improve Training
Check Data Quality:
Ensure that the dataset samples are representative and that the states and actions are correctly aligned.
Learning Rate Adjustment:
Try different learning rates. The current learning rate lr=1e-4 might be too small. Start with 1e-3 or even 1e-2 and observe if there are any improvements.
Model Architecture Tweaks:
Ensure that the CustomGNN and the Actor network are well-designed for the complexity of your task. Experiment with different layer sizes, dropout rates, or activation functions.
Loss Monitoring:
Print summary statistics or visual plots of loss over the epochs to better understand the learning dynamics.
Example of Additional Diagnostic Prints
User
in the below program, i am having little confusion on processing in the function 'pre_train_agent', here in the function 'pre_training_dataset_generation', saves the data sets with headers ['L1', 'L3', 'L5', 'L6', 'L7', 'W1', 'W3', 'W5', 'W6', 'W7', 'Ib', 'Cc', 'Vc', 'M1', 'M2', 'M3', 'M4', 'M5', 'M8', 'M6', 'M7', 'Area', 'PowerDissipation', 'SlewRate', 'Gain', 'Bandwidth3dB', 'UnityGainFreq', 'PhaseMargin']. but in the function 'pre_train_agent' in the line "for state, action in dataset", the 'state' is a tensor of node features, edge features and edge index how.
def pre_training_dataset_generation(env, required_samples=1000, progress_filename='progress.pkl'):
"""Generate pre-training dataset with manual tuning data"""
env.connect_to_simulator() # Ensure simulator is connected before dataset generation
code
Assistant
To clarify how the dataset is being processed in both functions and explain the transition from CSV data to training the actor with tensors, let's break down the operations step-by-step.
The function connects to the simulator and either loads previous progress or generates new samples using Latin Hypercube Sampling (LHS).
It initializes or appends to a CSV file where the data will be stored with headers like ['L1', 'L3', ... , 'Bandwidth3dB', 'UnityGainFreq', 'PhaseMargin'].
Data Generation and Storage:
It iterates through generated samples, runs simulations using the env.simulator.run_simulation(raw_actions) method, and records transistor regions and performance metrics.
Each sample (including raw actions and the corresponding simulation results) is written to the CSV file.
If the transistor regions satisfy a certain condition, the results are processed into graph representations (netlist_to_graph), which convert the data into tensor representations.
Graph Representation:
The netlist_to_graph function is likely responsible for converting the raw actions and transistor regions into a graph format suitable for GNN, resulting in node_features_tensor, edge_feature_tensor, and edge_index.
These tensors are stored in the dataset along with the corresponding action tensor.
Return:
The function returns the dataset, which is a list of tuples where each tuple is of the form (state, action).
state is a tuple containing (node_features_tensor, edge_feature_tensor, edge_index).
action is the tensor representation of the raw action values.
Pre-Training Agent (pre_train_agent)
Initializing Training:
The function initializes the training mode for the actor network and sets up the optimizer and learning rate scheduler.
Training Loop:
The function iterates over epochs. For each epoch, it goes through each example in the dataset.
For each (state, action) tuple, it performs the following:
User
yes as per your previous suggestion, I tries with modified lr=1e-3 from lr=1e-4, eventhough I get the Avg Loss between 11.94 to 11.97 and the values with in the Batch Losses were between 11 to 12. from this can I know the pre training the agent is effectively progressing or not.
def pre_train_agent(agent, dataset):
"""Pre-train the agent using the dataset"""
agent.actor.train()
pretrain_optimizer = optim.Adam(agent.actor.parameters(), lr=1e-3) #lr=1e-4
scheduler = torch.optim.lr_scheduler.StepLR(pretrain_optimizer, step_size=30, gamma=0.1)
To determine if the pre-training of your agent is effectively progressing, we need to consider multiple aspects of the training dynamics, particularly looking at the loss trend over epochs. Here are the key points to pay attention to:
Loss Trend: Over epochs, you should generally see a decreasing trend in the average loss. This indicates that the model is learning to predict actions more accurately (i.e., with higher probabilities for the correct actions).
Gradient Behavior: The loss should not be stuck in a narrow band across all epochs. If the loss is not decreasing and remains between a narrow range (11 to 12), it might suggest issues with the learning rate, model capacity, or possible issues with the dataset itself.
Understanding Loss Behavior:
Consistent High Loss: As you reported, if the average loss stays between 11.94 and 11.97 even after increasing the learning rate, it indicates that the model is not effectively optimizing.
A high and stagnant loss suggests that the predictions from the model are not improving significantly over time.
Possible Causes:
Learning Rate: If increasing the learning rate from 1e-4 to 1e-3 didn't help, you could try a slightly higher learning rate or other optimizers.
Model Complexity: The model might require additional layers or different architectures to better capture the patterns in your data.
Data Representation: Ensure the data being fed into the model is adequately representing the actions and states. Sometimes, feature engineering or transforming the data can help.
Next Steps and Diagnostics:
Plot the Loss: Visualize the loss over epochs to see if there's any subtle trend that you might miss in console logs.
Experiment with Hyperparameters:
Higher Learning Rate: Try 1e-2.
More Complex Architecture: Add additional layers or units in the GNN or the linear layers following it.
Verify Data Handling: Ensure that data batching and loading are done properly.
Example of Plotting Loss:
Use Matplotlib to visualize loss over epochs.
python
User
my action values are continuous action values between predefined bounds and the data sets values are also continuous in nature, will the Adam pre train optimizer will suits for my continuous action inputs and what will be the best optimizer will support to my process conditions and how can the model is redefined with additional layers
Assistant
The Adam optimizer is generally well-suited for continuous action spaces as it adapits the learning rate based on the first and second moments of the gradients and works well in most scenarios involving neural networks. However, depending on the specific characteristics of your problem, you might consider experimenting with other optimizers like SGD, RMSprop, or even more advanced optimizers like AdamW (Adam with weight decay).
Experimenting with Different Optimizers
You can start by trying different optimizers and see if they improve the performance. Here are a few options:
To give the model more capacity to learn from data, you can add additional layers to both the Graph Neural Network (GNN) and the actor's head.
Redefining the Model with Additional Layers
Here’s an example of adding more layers to your CustomGNN and Actor:
python
User
what should i give to this values 'in_channels, intermediate_channels, out_channels'
Assistant
To determine appropriate values for in_channels, intermediate_channels, and out_channels, you should consider the following:
in_channels: This should be the number of features each node in your input graph has.
intermediate_channels: This is a hyperparameter that you'll set to control the size of the hidden layers in the GNN. It can be tuned based on the complexity of the task.
out_channels: This should be the number of required output features from the GNN, which will eventually be used as inputs to the fully connected layers in the actor network.
Given the information from your previous code:
in_channels = 24: This was already set since you mentioned each node has 24 features.
out_channels = 13: This was set since your action space consists of 13 variables.
For intermediate_channels, you can start with a value such as 128 and tune it based on the performance.
Suggested Values
Let's assume:
in_channels = 24 (each node has 24 input features)
intermediate_channels = 128 (a good starting point for hidden layer size)
out_channels = 13 (the dimensions of your action space).
Here's how you can instantiate your GNN with these values:
python
User
do I need to change any thing in the critic network
class Critic(torch.nn.Module):
def init(self):
super(Critic, self).init()
flattened_size = 20 * 24 # Number of nodes times features per node
self.network = torch.nn.Sequential(
torch.nn.Linear(flattened_size, 128),
torch.nn.ReLU(),
torch.nn.Linear(128, 1)
)
code
def forward(self, state):
# Directly use state as it is already what we referred to as state[0] in evaluate
flattened = state.view(-1) # Flatten to [480]
#node_features_tensor, _, _ = state
#flattened = node_features_tensor.view(-1) # Flatten to [480]
return self.network(flattened)
Assistant
The Critic network in your implementation is designed to take a flattened tensor representing the entire state and pass it through a series of fully connected (dense) layers to produce a value. If the architecture of the Actor network has changed, particularly around how node features are aggregated, there may be some considerations for the Critic network as well.
Given the changes we discussed earlier, the Critic may benefit from a similar approach where node features are first processed through the GNN, pooled (using global mean pooling in our case), and then passed through the dense layers to produce the value estimate.
Here's an updated version of the Critic network to match the architectural improvements we discussed for the Actor:
Updated Critic Network
python
class Critic(torch.nn.Module):
def __init__(self, gnn):
super(Critic, self).__init__()
self.gnn = gnn # Reuse GNN model for feature processing
intermediate_channels = 128 # Use the same intermediate channels as in Actor
self.fc1 = nn.Linear(out_channels, intermediate_channels)
self.fc2 = nn.Linear(intermediate_channels, 1)
def forward(self, state):
# Unpack the state
node_features_tensor, edge_feature_tensor, edge_index = state
# Process node features through the GNN
processed_features = self.gnn(node_features_tensor, edge_index)
# Global mean pooling to aggregate node features into a single graph representation
graph_embedding = gmp(processed_features, batch=torch.zeros(processed_features.size(0), dtype=torch.long, device=processed_features.device))
# Pass through the dense layers
x = F.relu(self.fc1(graph_embedding))
value = self.fc2(x)
return value
# Define GNN Model
gnn_model = CustomGNN(in_channels, intermediate_channels, out_channels)
# Define Actor and Critic networks
actor = Actor(gnn_model)
critic = Critic(gnn_model)
# Example usage: ensure data fits the structures correctly
dummy_state = (torch.rand(20, 24), None, torch.randint(0, 20, (2, 38)))
action_means, action_std, stability_pred = actor(dummy_state)
critic_value = critic(dummy_state)
print("Action Means:", action_means)
print("Critic Value:", critic_value)
User
in my policy update I am executing the critic network as follows, and I donot want to disturb the existing below implementation.
code
for _ in range(self.epochs):
log_probs_batch, state_values_batch, entropies_batch, stability_losses_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
# Flattening the node_features_tensor for the critic, as your critic expects a flattened input.
flattened_state = node_features_tensor.view(-1) # Adjusted to flatten the state appropriately
# Extracting the 24th feature for stability; assuming indexing starts at 0, so it’s 23rd in 0-indexing.
stability_target = node_features_tensor[:, 23].unsqueeze(1) # For the stability target
action_means, action_stds, stability_pred = self.actor(state)
# Convert stability_pred to match the binary targets if not already
stability_pred = torch.sigmoid(stability_pred).unsqueeze(1)
# Getting the state value prediction from the critic using the flattened state
state_value = self.critic(flattened_state).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)
# Stability loss
stability_loss = F.binary_cross_entropy_with_logits(stability_pred, stability_target)
stability_losses_batch.append(stability_loss.unsqueeze(0))
entropy = dist.entropy().sum(axis=-1).unsqueeze(0)
entropies_batch.append(entropy)
state_values_batch.append(state_value)
Assistant
To synchronize your Critic implementation with the existing policy update implementation that expects a flattened state, you need to ensure that the Critic network can accept a flattened state as input and still use the GNN processing pipeline.
We can achieve this by modifying the Critic's forward method to handle both the flattened state and the full graph state. The idea is to reassemble the state when it is passed in as a flattened tensor.
Updated Critic Class
We'll update the Critic class to check if the input state is flattened or structured, process it accordingly, and still fit into the existing training loop.
Here is the updated Critic network:
python
class Critic(torch.nn.Module):
def __init__(self, gnn):
super(Critic, self).__init__()
self.gnn = gnn # Reuse GNN model for feature processing
intermediate_channels = 128 # Use the same intermediate channels as in Actor
self.fc1 = nn.Linear(out_channels, intermediate_channels)
self.fc2 = nn.Linear(intermediate_channels, 1)
def forward(self, state):
if isinstance(state, tuple) and len(state) == 3:
# Assume state is a tuple (node_features_tensor, edge_feature_tensor, edge_index)
node_features_tensor, edge_feature_tensor, edge_index = state
processed_features = self.gnn(node_features_tensor, edge_index)
graph_embedding = gmp(processed_features, batch=torch.zeros(processed_features.size(0), dtype=torch.long, device=processed_features.device))
else:
# Assume state is a flattened state tensor
node_count = 20 # Assuming you have 20 nodes
feature_count = 24 # Assuming 24 features per node
node_features_tensor = state.view(node_count, feature_count)
# Assuming edge_feature_tensor and edge_index are known or can be recomputed if needed
processed_features = self.gnn(node_features_tensor, None)
graph_embedding = gmp(processed_features, batch=torch.zeros(processed_features.size(0), dtype=torch.long, device=processed_features.device))
x = F.relu(self.fc1(graph_embedding))
value = self.fc2(x)
return value
total_samples=1000
progress_filename='progress.pkl'
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
dataset = None
pretrain_params = None
# 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}")
# Check if a previous pre-training state (dataset) exists and load it
pretraining_state = load_pretraining_state()
if pretraining_state:
dataset = pretraining_state['dataset']
pretrain_params = pretraining_state['pretrain_params']
print("Resuming pre-training from saved state.")
# If no pretraining state found, generate dataset and pre-train agent
if not dataset:
pretrain_params = {
'bounds_low': env.bounds_low,
'bounds_high': env.bounds_high,
# Add other relevant parameters here
}
dataset = pre_training_dataset_generation(env, total_samples, progress_filename)
pre_train_agent(agent, dataset)
save_pretraining_state(dataset, pretrain_params)
else:
# Pre-training using existing dataset
pre_train_agent(agent, dataset)
for episode in range(start_episode, num_episodes):
node_features_tensor, edge_feature_tensor, edge_index, performance_metrics = env.reset()
state = (node_features_tensor, edge_feature_tensor, edge_index)
import os
import pickle
import torch
import torch.optim as optim
from torch_geometric.nn import GATConv
from scipy.stats import qmc
def save_pretraining_state(dataset, pretrain_params, agent, filepath='pretrain_state25_3.pkl'):
"""Save the pre-training state including dataset, generation parameters, and agent state."""
state = {
'dataset': dataset,
'pretrain_params': pretrain_params,
'actor_state_dict': agent.actor.state_dict()
}
with open(filepath, 'wb') as f:
pickle.dump(state, f)
def load_pretraining_state(filepath='pretrain_state25_3.pkl'):
"""Load the pre-training state including dataset, parameters, and agent state."""
if os.path.isfile(filepath):
with open(filepath, 'rb') as f:
state = pickle.load(f)
return state
else:
return None
def save_training_state(agent, episode, rewards_log, losses_log, metrics_log, filepath='training_state25_3.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_state25_3.pt'):
if os.path.isfile(filepath):
state = torch.load(filepath)
return state
else:
return None
def save_progress(dataset, current_sample, raw_samples, required_samples, filename='progress.pkl'):
"""Save intermediate state to disk."""
with open(filename, 'wb') as f:
pickle.dump((dataset, current_sample, raw_samples, required_samples), f)
def load_progress(filename='progress.pkl'):
"""Load intermediate state from disk."""
if os.path.exists(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
return [], 0, [], 0
def sample_generator(bounds_low, bounds_high, num_samples):
"""Generate samples using Latin Hypercube Sampling."""
dim = len(bounds_low)
# Create a Latin Hypercube Sampler
sampler = qmc.LatinHypercube(d=dim)
# Generate normalized samples (0 to 1)
norm_samples = sampler.random(n=num_samples)
# Scale the samples to the given bounds
samples = qmc.scale(norm_samples, bounds_low, bounds_high)
return samples
def pre_training_dataset_generation(env, required_samples=1000, progress_filename='progress.pkl'):
"""Generate pre-training dataset with manual tuning data"""
env.connect_to_simulator() # Ensure simulator is connected before dataset generation
dataset, start_sample, raw_samples, saved_required_samples = load_progress(progress_filename)
print("resume from the sample", start_sample)
# Check if required_samples is updated, if so, regenerate samples
if saved_required_samples != required_samples:
# Generate samples using LHS
raw_samples = sample_generator(env.bounds_low, env.bounds_high, required_samples)
start_sample = 0 # restart if required_samples changed
dataset = []
current_sample = start_sample
while current_sample < required_samples:
sample_idx = current_sample % len(raw_samples)
raw_actions = raw_samples[sample_idx]
valid_sample_found = False
while not valid_sample_found:
iteration = 0
while iteration < env.max_iteration:
transistor_regions, saturation_condition, performance_metrics = env.simulator.run_simulation(raw_actions)
if all(region == 2 for region in transistor_regions.values()):
node_features_tensor, edge_feature_tensor, edge_index = netlist_to_graph(env.netlist_content, raw_actions, transistor_regions)
state = (torch.tensor(node_features_tensor, dtype=torch.float32), torch.tensor(edge_feature_tensor, dtype=torch.float32), torch.tensor(edge_index, dtype=torch.long))
actions = torch.tensor(raw_actions, dtype=torch.float32)
dataset.append((state, actions))
valid_sample_found = True
break
# Try adjusting raw actions and continue iterations
raw_actions = env.adjust_raw_actions_value(raw_actions, transistor_regions)
if not valid_sample_found:
new_raw_action = sample_generator(env.bounds_low, env.bounds_high, 1)
raw_actions = new_raw_action.flatten()
save_progress(dataset, current_sample, raw_samples, required_samples, progress_filename)
print("sample count", current_sample)
current_sample += 1
env.disconnect_from_simulator() # Optionally disconnect after dataset generation
return dataset
def pre_train_agent(agent, dataset):
"""Pre-train the agent using the dataset"""
agent.actor.train()
pretrain_optimizer = optim.Adam(agent.actor.parameters(), lr=1e-4)
scheduler = torch.optim.lr_scheduler.StepLR(pretrain_optimizer, step_size=30, gamma=0.1)
for epoch in range(100): # Train for 10 epochs
total_loss = 0
for state, action in dataset:
pretrain_optimizer.zero_grad()
action_means, action_stds, _ = agent.actor(state)
dist = torch.distributions.Normal(action_means, action_stds)
log_probs = dist.log_prob(action).sum(axis=-1)
loss = -log_probs.mean() # Maximize log_probs -> minimize -log_probs
loss.backward()
# Gradient Clipping
torch.nn.utils.clip_grad_norm(agent.actor.parameters(), max_norm=1.0)
pretrain_optimizer.step()
total_loss += loss.item()
scheduler.step()
print(f"Epoch {epoch}, Loss: {total_loss / len(dataset)}")
def train(env, agent, num_episodes, max_timesteps, batch_size):
# Ensure simulator connection
env.connect_to_simulator()
total_samples = 1000
progress_filename = 'progress.pkl'
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
dataset = None
pretrain_params = None
# 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}")
# Check if a previous pre-training state (dataset) exists and load it
pretraining_state = load_pretraining_state()
if pretraining_state:
dataset = pretraining_state['dataset']
pretrain_params = pretraining_state['pretrain_params']
agent.actor.load_state_dict(pretraining_state['actor_state_dict'])
print("Resuming pre-training from saved state.")
# If no pretraining state found or no actor state, generate dataset and pre-train agent
if not dataset or 'actor_state_dict' not in pretraining_state:
pretrain_params = {
'bounds_low': env.bounds_low,
'bounds_high': env.bounds_high,
# Add other relevant parameters here
}
dataset = pre_training_dataset_generation(env, total_samples, progress_filename)
pre_train_agent(agent, dataset)
save_pretraining_state(dataset, pretrain_params, agent)
for episode in range(start_episode, num_episodes):
node_features_tensor, edge_feature_tensor, edge_index, performance_metrics = env.reset()
state = (torch.tensor(node_features_tensor, dtype=torch.float32),
torch.tensor(edge_feature_tensor, dtype=torch.float32),
torch.tensor(edge_index, dtype=torch.long))
# Training logic here...
Explanation:
save_pretraining_state and load_pretraining_state Functions:
Now include 'actor_state_dict': agent.actor.state_dict() in the state dictionary to save the pre-trained weights of the actor model.
Later load the actor_state_dict and initialize the actor model with these weights if they exist. This avoids re-training the agent on subsequent runs.
Training Function Modifications:
Added check to determine if the actor_state_dict exists in the pretraining state, and if it does, load it.
If no dataset or actor_state_dict is found, generate the required dataset and pre-train the agent.
This approach ensures that the pre-trained state of the actor network is stored and re-used, thus preventing redundant execution of the pre_train_agent function on subsequent loads.
# Define bounds for action space scaling
self.bounds_low = torch.tensor([0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6,
0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6,
15e-6, 0.1e-12, 0.8], dtype=torch.float32)
self.bounds_high = torch.tensor([0.181e-6, 0.181e-6, 0.181e-6, 0.181e-6, 0.181e-6,
50e-6, 50e-6, 50e-6, 50e-6, 50e-6,
30e-6, 10e-12, 1.4], dtype=torch.float32)
def forward(self, state):
node_features_tensor, _, edge_index = state
# Processed features from the GNN
processed_features = self.gnn(node_features_tensor, edge_index)
# Example assertion (add after GNN processing)
#assert torch.all(node_features_tensor[:, 0] == processed_features[:, 0]), "Node order mismatch!"
# Initialize stability predictions - assume all nodes as stable
stability_pred = torch.ones(processed_features.size(0), device=processed_features.device)
# Define the indices of nodes that actually require stability prediction
# Given [0, 3, 5, 7, 10, 13, 15, 16] represent tunable/unstable nodes
unstable_nodes_idx = torch.tensor([0, 3, 5, 7, 10, 13, 15, 16], dtype=torch.long, device=processed_features.device)
# Fetch features for nodes requiring stability computation
features_for_stability = processed_features[unstable_nodes_idx]
# Compute stability predictions for these nodes
stability_pred_unstable = self.stability_head(features_for_stability).squeeze(-1)
# Update the overall stability predictions
stability_pred[unstable_nodes_idx] = stability_pred_unstable
# Normalize and scale the GNN outputs to the action bounds for usable actions
normalized_gnn_output = torch.tanh(processed_features)
action_means = self.bounds_low + (self.bounds_high - self.bounds_low) * ((normalized_gnn_output + 1) / 2)
print("action_means", action_means)
# Define action variances (assuming a simple fixed form here for demonstration)
action_log_std = torch.zeros_like(action_means)
action_std = torch.exp(action_log_std)
return action_means, action_std, stability_pred
class Critic(torch.nn.Module):
def init(self):
super(Critic, self).init()
flattened_size = 20 * 24 # Number of nodes times features per node
self.network = torch.nn.Sequential(
torch.nn.Linear(flattened_size, 128),
torch.nn.ReLU(),
torch.nn.Linear(128, 1)
)
code
def forward(self, state):
# Directly use state as it is already what we referred to as state[0] in evaluate
#flattened = state.view(-1) # Flatten to [480]
node_features_tensor, _, _ = state
flattened = node_features_tensor.view(-1) # Flatten to [480]
return self.network(flattened)
import os
import pickle
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch_geometric.nn import GATConv, global_mean_pool as gmp
from scipy.stats import qmc
# Initialize Hyperparameters
in_channels = 24 # Number of input features
out_channels = 13 # Number of output actions or features
state_dim = 128 # Dimension of state representation, to match critic input
action_space = 13 # Environment’s action space
class CustomGNN(torch.nn.Module):
def __init__(self, in_channels, out_channels):
super(CustomGNN, self).__init__()
self.gat1 = GATConv(in_channels, 8, heads=8, dropout=0.2) # dropout=0.6
self.gat2 = GATConv(64, out_channels, heads=1, concat=False, dropout=0.2) # 8*8 is 64 dropout=0.6
def forward(self, x, edge_index):
x = F.dropout(x, p=0.2, training=self.training) # p=0.6
x = F.elu(self.gat1(x, edge_index))
x = F.dropout(x, p=0.2, training=self.training) # p=0.6
x = self.gat2(x, edge_index)
return x
class Actor(torch.nn.Module):
def __init__(self, gnn_model):
super(Actor, self).__init__()
self.gnn = gnn_model
self.stability_head = nn.Sequential(
nn.Linear(out_channels, 64), # Adjusted input to match GNN output features
nn.ReLU(),
nn.Linear(64, 1) # Outputs a single stability value per node
)
self.action_head = nn.Linear(out_channels, action_space) # Map to action space
# Define bounds for action space scaling
self.bounds_low = torch.tensor([0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6,
0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6,
15e-6, 0.1e-12, 0.8], dtype=torch.float32)
self.bounds_high = torch.tensor([0.181e-6, 0.181e-6, 0.181e-6, 0.181e-6, 0.181e-6,
50e-6, 50e-6, 50e-6, 50e-6, 50e-6,
30e-6, 10e-12, 1.4], dtype=torch.float32)
def forward(self, state):
node_features_tensor, _, edge_index = state
# Processed features from the GNN
processed_features = self.gnn(node_features_tensor, edge_index)
# Global mean pooling to aggregate node features
graph_embedding = gmp(processed_features, batch=torch.zeros(processed_features.size(0), dtype=torch.long, device=processed_features.device))
# Initialize stability predictions - assume all nodes as stable
stability_pred = torch.ones(processed_features.size(0), device=processed_features.device)
# Define the indices of nodes that actually require stability prediction
# Given [0, 3, 5, 7, 10, 13, 15, 16] represent tunable/unstable nodes
unstable_nodes_idx = torch.tensor([0, 3, 5, 7, 10, 13, 15, 16], dtype=torch.long, device=processed_features.device)
# Fetch features for nodes requiring stability computation
features_for_stability = processed_features[unstable_nodes_idx]
# Compute stability predictions for these nodes
stability_pred_unstable = self.stability_head(features_for_stability).squeeze(-1)
# Update the overall stability predictions
stability_pred[unstable_nodes_idx] = stability_pred_unstable
# Pass through action head to get final action means
action_means = self.action_head(graph_embedding)
# Normalize and scale the action means to the action bounds for usable actions
normalized_gnn_output = torch.tanh(action_means)
action_means = self.bounds_low + (self.bounds_high - self.bounds_low) * ((normalized_gnn_output + 1) / 2)
print("action_means", action_means)
# Define action variances (assuming a simple fixed form here for demonstration)
action_log_std = torch.zeros_like(action_means)
action_std = torch.exp(action_log_std)
return action_means, action_std, stability_pred
class Critic(torch.nn.Module):
def __init__(self):
super(Critic, self).__init__()
flattened_size = 20 * 24 # Number of nodes times features per node
self.network = torch.nn.Sequential(
torch.nn.Linear(flattened_size, 128),
torch.nn.ReLU(),
torch.nn.Linear(128, 1)
)
def forward(self, state):
# Directly use state as it is already what we referred to as state[0] in evaluate
node_features_tensor, _, _ = state
flattened = node_features_tensor.view(-1) # Flatten to [480]
return self.network(flattened)
# Example initialization and forward pass
gnn_model = CustomGNN(in_channels, out_channels)
actor = Actor(gnn_model)
critic = Critic()
# Dummy data according to the structure
dummy_state = (torch.rand(20, 24), None, torch.randint(0, 20, (2, 38)))
action_means, action_std, stability_pred = actor(dummy_state)
critic_value = critic(dummy_state)
print(action_means, action_std, stability_pred, critic_value)
Explanation:
Global Mean Pooling:
Added global_mean_pool function to aggregate node features into a single graph-level feature vector. This vector is then used to create the action output.
Graph Embedding and Action Head:
Added a linear layer (action_head) that maps the pooled graph representation to the desired action space size (13).
Normalization and Scaling of Actions:
Adjusted to ensure the actions (action_means) are a single row with 13 columns.
This setup will allow the Actor to output a single set of 13 actions after aggregating the node features using global mean pooling, which aligns with your requirement to provide this output to your simulator.
class Actor(torch.nn.Module):
def init(self, gnn_model):
super(Actor, self).init()
self.gnn = gnn_model
self.stability_head = nn.Sequential(
nn.Linear(out_channels, 64), # Adjusted input to match GNN output features
nn.ReLU(),
nn.Linear(64, 1) # Outputs a single stability value per node
)
self.action_head = nn.Linear(out_channels, action_space) # Map to action space
code
# Define bounds for action space scaling
self.bounds_low = torch.tensor([0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6,
0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6,
15e-6, 0.1e-12, 0.8], dtype=torch.float32)
self.bounds_high = torch.tensor([0.181e-6, 0.181e-6, 0.181e-6, 0.181e-6, 0.181e-6,
50e-6, 50e-6, 50e-6, 50e-6, 50e-6,
30e-6, 10e-12, 1.4], dtype=torch.float32)
def forward(self, state):
node_features_tensor, _, edge_index = state
# Processed features from the GNN
processed_features = self.gnn(node_features_tensor, edge_index)
# Example assertion (add after GNN processing)
#assert torch.all(node_features_tensor[:, 0] == processed_features[:, 0]), "Node order mismatch!"
# Global mean pooling to aggregate node features
graph_embedding = gmp(processed_features, batch=torch.zeros(processed_features.size(0), dtype=torch.long, device=processed_features.device))
# Initialize stability predictions - assume all nodes as stable
stability_pred = torch.ones(processed_features.size(0), device=processed_features.device)
# Define the indices of nodes that actually require stability prediction
# Given [0, 3, 5, 7, 10, 13, 15, 16] represent tunable/unstable nodes
unstable_nodes_idx = torch.tensor([0, 3, 5, 7, 10, 13, 15, 16], dtype=torch.long, device=processed_features.device)
# Fetch features for nodes requiring stability computation
features_for_stability = processed_features[unstable_nodes_idx]
# Compute stability predictions for these nodes
stability_pred_unstable = self.stability_head(features_for_stability).squeeze(-1)
# Update the overall stability predictions
stability_pred[unstable_nodes_idx] = stability_pred_unstable
# Pass through action head to get final action means
action_means = self.action_head(graph_embedding)
# Normalize and scale the GNN outputs to the action bounds for usable actions
normalized_gnn_output = torch.tanh(action_means)
action_means = self.bounds_low + (self.bounds_high - self.bounds_low) * ((normalized_gnn_output + 1) / 2)
# Define action variances (assuming a simple fixed form here for demonstration)
action_log_std = torch.zeros_like(action_means)
action_std = torch.exp(action_log_std)
return action_means, action_std, stability_pred
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, stability_losses_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
# Flattening the node_features_tensor for the critic, as your critic expects a flattened input.
flattened_state = node_features_tensor.view(-1) # Adjusted to flatten the state appropriately
# Extracting the 24th feature for stability; assuming indexing starts at 0, so it’s 23rd in 0-indexing.
stability_target = node_features_tensor[:, 23].unsqueeze(1) # For the stability target
action_means, action_stds, stability_pred = self.actor(state)
# Convert stability_pred to match the binary targets if not already
stability_pred = torch.sigmoid(stability_pred).unsqueeze(1)
# Getting the state value prediction from the critic using the flattened state
state_value = self.critic(flattened_state).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)
# Stability loss
stability_loss = F.binary_cross_entropy_with_logits(stability_pred, stability_target)
stability_losses_batch.append(stability_loss.unsqueeze(0))
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
stability_losses = torch.cat(stability_losses_batch)
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() + stability_losses.mean()
critic_loss = F.mse_loss(state_values, returns)
# Update actor
self.optimizer_actor.zero_grad()
actor_loss.backward()
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
Adding more logging can help in diagnosing where the issues might be. For example, print out per-epoch and batch-wise losses:
python
def pre_train_agent(agent, dataset):
"""Pre-train the agent using the dataset"""
agent.actor.train()
pretrain_optimizer = optim.Adam(agent.actor.parameters(), lr=1e-4)
scheduler = torch.optim.lr_scheduler.StepLR(pretrain_optimizer, step_size=30, gamma=0.1)
for epoch in range(100): # Train for 100 epochs
total_loss = 0
batch_losses = []
for state, action in dataset:
pretrain_optimizer.zero_grad()
action_means, action_stds, _ = agent.actor(state)
dist = torch.distributions.Normal(action_means, action_stds)
log_probs = dist.log_prob(action).sum(axis=-1)
loss = -log_probs.mean() # Maximize log_probs -> minimize -log_probs
loss.backward()
# Gradient Clipping
torch.nn.utils.clip_grad_norm(agent.actor.parameters(), max_norm=1.0)
pretrain_optimizer.step()
total_loss += loss.item()
batch_losses.append(loss.item())
scheduler.step()
avg_loss = total_loss / len(dataset)
print(f"Epoch {epoch}, Avg Loss: {avg_loss}, Batch Losses: {batch_losses}")
Additional Measures for Better Diagnosis:
Visualizing Loss Trends:
Plot the loss over epochs to visually inspect if the loss is decreasing, plateauing, or fluctuating wildly.
Variance of Predictions:
Track the variance of action_means and action_stds. Large variances can indicate instability, while too small variances can indicate overconfidence.
Hyperparameter Tuning:
Experiment with different optimizers (SGD, Adam with different betas).
Change the number of epochs for the pre-training phase.
Visualizing Loss with Matplotlib:
python
import matplotlib.pyplot as plt
def pre_train_agent(agent, dataset):
"""Pre-train the agent using the dataset"""
agent.actor.train()
pretrain_optimizer = optim.Adam(agent.actor.parameters(), lr=1e-4)
scheduler = torch.optim.lr_scheduler.StepLR(pretrain_optimizer, step_size=30, gamma=0.1)
losses = []
for epoch in range(100): # Train for 100 epochs
total_loss = 0
for state, action in dataset:
pretrain_optimizer.zero_grad()
action_means, action_stds, _ = agent.actor(state)
dist = torch.distributions.Normal(action_means, action_stds)
log_probs = dist.log_prob(action).sum(axis=-1)
loss = -log_probs.mean() # Maximize log_probs -> minimize -log_probs
loss.backward()
# Gradient Clipping
torch.nn.utils.clip_grad_norm(agent.actor.parameters(), max_norm=1.0)
pretrain_optimizer.step()
total_loss += loss.item()
scheduler.step()
avg_loss = total_loss / len(dataset)
losses.append(avg_loss)
print(f"Epoch {epoch}, Avg Loss: {avg_loss}")
# Plot the loss over epochs
plt.plot(range(100), losses)
plt.xlabel('Epoch')
plt.ylabel('Average Loss')
plt.title('Pre-training Loss over Epochs')
plt.show()
By incorporating these diagnostics, you can get a clearer picture of how well your model is learning and adjust accordingly. If the loss is not decreasing and remains high, it's a sign that the model architecture, data distribution, or training procedure may need adjustments.
total_samples=1000
progress_filename='progress.pkl'
start_episode = 0
rewards_log = []
losses_log = []
metrics_log = []
episode_lengths = []
dataset = None
pretrain_params = None
# 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}")
# Check if a previous pre-training state (dataset) exists and load it
pretraining_state = load_pretraining_state()
if pretraining_state:
dataset = pretraining_state['dataset']
pretrain_params = pretraining_state['pretrain_params']
print("Resuming pre-training from saved state.")
# If no pretraining state found, generate dataset and pre-train agent
if not dataset:
pretrain_params = {
'bounds_low': env.bounds_low,
'bounds_high': env.bounds_high,
# Add other relevant parameters here
}
dataset = pre_training_dataset_generation(env, total_samples, progress_filename)
pre_train_agent(agent, dataset)
save_pretraining_state(dataset, pretrain_params)
else:
# Pre-training using existing dataset
pre_train_agent(agent, dataset)
Forward Pass: The actor model processes the state to predict action distribution parameters (action_means and action_stds).
Loss Calculation: It calculates the log probability of the given action under the predicted distribution and computes the loss as the negative log probability (so higher probability of the correct action results in lower loss).
Backpropagation: The gradients are computed and the model parameters are updated accordingly.
Explanation of the Transition
The detailed headers in CSV (['L1', 'L3', ... , 'PhaseMargin']) are initially processed into a specification suitable for a tabular format. Only after that, these values are transformed into a graph structure that can be processed by the GNN.
State Representation (node_features_tensor, edge_feature_tensor, edge_index)
node_features_tensor: Contains features for each node in the graph.
edge_feature_tensor: Contains features for each edge in the graph.
edge_index: Defines the connections (edges) in the graph, typically in COO format for PyTorch Geometric.
How Data Flows:
From CSV to Graph Representation:
Values like L1, L3, etc., are first stored in CSV, then converted to tensors representing nodes and edges.
netlist_to_graph function does this conversion by leveraging the structure of the circuit and the properties of the transistors to form a graph of nodes and edges.
Training with Tensor Data:
pre_train_agent uses these tensor representations (state) along with the action tensor to train the actor using the pre-defined loss function.
Sample Trace in Code
The trace from CSV data to tensor can be visualized with added debug prints to understand how each sample is processed. This can ensure state and action are correctly formed:
python
def pre_training_dataset_generation(env, required_samples=1000, progress_filename='progress.pkl'):
"""Generate pre-training dataset with manual tuning data"""
...
while current_sample < required_samples:
sample_idx = current_sample % len(raw_samples)
raw_actions = raw_samples[sample_idx]
valid_sample_found = False
while not valid_sample_found:
...
transistor_regions, saturation_condition, performance_metrics = env.simulator.run_simulation(raw_actions)
# Debug print to check values before CSV write
print(f"Sample {current_sample}: raw_actions = {raw_actions}, transistor_regions = {transistor_regions}, performance_metrics = {performance_metrics}")
writer.writerow({
'L1': raw_actions[0], 'L3': raw_actions[1], 'L5': raw_actions[2], 'L6': raw_actions[3], 'L7': raw_actions[4],
...
})
if all(region == 2 for region in transistor_regions.values()):
node_features_tensor, edge_feature_tensor, edge_index = netlist_to_graph(env.netlist_content, raw_actions, transistor_regions)
# Debug print to check graph conversion
print(f"Graph Conversion: node_features_tensor = {node_features_tensor}, edge_feature_tensor = {edge_feature_tensor}, edge_index = {edge_index}")
state = (torch.tensor(node_features_tensor, dtype=torch.float32), torch.tensor(edge_feature_tensor, dtype=torch.float32), torch.tensor(edge_index, dtype=torch.long))
actions = torch.tensor(raw_actions, dtype=torch.float32)
dataset.append((state, actions))
valid_sample_found = True
break
...
current_sample += 1
...
return dataset
def pre_train_agent(agent, dataset):
"""Pre-train the agent using the dataset"""
...
for epoch in range(100):
total_loss = 0
for state, action in dataset:
pretrain_optimizer.zero_grad()
# Debug print to ensure data flow into actor model
print(f"Training state: node_features_tensor = {state[0]}, action = {action}")
action_means, action_stds, _ = agent.actor(state)
...
loss.backward()
...
print(f"Epoch {epoch}, Loss: {total_loss / len(dataset)}")
By ensuring that each step from CSV data writing to tensor conversion is correctly happening, we can diagnose and affirm the state transformations across functions. This should address any confusion regarding how the state in the pre_train_agent function corresponds with the CSV data generated in pre_training_dataset_generation.
import matplotlib.pyplot as plt
def pre_train_agent(agent, dataset):
"""Pre-train the agent using the dataset"""
agent.actor.train()
pretrain_optimizer = optim.Adam(agent.actor.parameters(), lr=1e-3) # lr=1e-4
scheduler = torch.optim.lr_scheduler.StepLR(pretrain_optimizer, step_size=30, gamma=0.1)
avg_losses = []
for epoch in range(100): # Train for 100 epochs
total_loss = 0
batch_losses = []
for state, action in dataset:
pretrain_optimizer.zero_grad()
action_means, action_stds, _ = agent.actor(state)
dist = torch.distributions.Normal(action_means, action_stds)
log_probs = dist.log_prob(action).sum(axis=-1)
loss = -log_probs.mean() # Maximize log_probs -> minimize -log_probs
loss.backward()
# Gradient Clipping
torch.nn.utils.clip_grad_norm(agent.actor.parameters(), max_norm=1.0)
pretrain_optimizer.step()
total_loss += loss.item()
batch_losses.append(loss.item())
scheduler.step()
avg_loss = total_loss / len(dataset)
avg_losses.append(avg_loss)
print(f"Epoch {epoch}, Avg Loss: {avg_loss}, Batch Losses: {batch_losses}")
# Plot the loss over epochs
plt.plot(range(100), avg_losses)
plt.xlabel('Epoch')
plt.ylabel('Average Loss')
plt.title('Pre-training Loss over Epochs')
plt.show()
def pre_training_dataset_generation(env, required_samples=1000, progress_filename='progress.pkl'):
"""Generate pre-training dataset with manual tuning data"""
env.connect_to_simulator() # Ensure simulator is connected before dataset generation
dataset, start_sample, raw_samples, saved_required_samples = load_progress(progress_filename)
print("resume from the sample", start_sample)
# Check if required_samples is updated, if so, regenerate samples
if saved_required_samples != required_samples:
# Generate samples using LHS
raw_samples = sample_generator(env.bounds_low, env.bounds_high, required_samples)
start_sample = 0 # restart if required_samples changed
dataset = []
# Initialize or append CSV file
csv_file_mode = 'a' if start_sample > 0 else 'w'
with open('transistor_data.csv', mode=csv_file_mode, newline='') as csvfile:
fieldnames = ['L1', 'L3', 'L5', 'L6', 'L7', 'W1', 'W3', 'W5', 'W6', 'W7',
'Ib', 'Cc', 'Vc', 'M1', 'M2', 'M3', 'M4', 'M5', 'M8', 'M6',
'M7', 'Area', 'PowerDissipation', 'SlewRate', 'Gain', 'Bandwidth3dB',
'UnityGainFreq', 'PhaseMargin']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if start_sample == 0:
writer.writeheader()
current_sample = start_sample
while current_sample < required_samples:
sample_idx = current_sample % len(raw_samples)
raw_actions = raw_samples[sample_idx]
valid_sample_found = False
while not valid_sample_found:
iteration = 0
while iteration < env.max_iteration:
# Print raw actions and validate the output
print(f"Raw Actions: {raw_actions}")
transistor_regions, saturation_condition, performance_metrics = env.simulator.run_simulation(raw_actions)
print(f"Transistor Regions: {transistor_regions}, Performance Metrics: {performance_metrics}")
writer.writerow({
'L1': raw_actions[0], 'L3': raw_actions[1], 'L5': raw_actions[2], 'L6': raw_actions[3], 'L7': raw_actions[4],
'W1': raw_actions[5], 'W3': raw_actions[6], 'W5': raw_actions[7], 'W6': raw_actions[8], 'W7': raw_actions[9],
'Ib': raw_actions[10], 'Cc': raw_actions[11], 'Vc': raw_actions[12],
'M1': transistor_regions.get('M1'), 'M2': transistor_regions.get('M2'), 'M3': transistor_regions.get('M3'),
'M4': transistor_regions.get('M4'), 'M5': transistor_regions.get('M5'), 'M8': transistor_regions.get('M8'),
'M6': transistor_regions.get('M6'), 'M7': transistor_regions.get('M7'),
'Area': performance_metrics.get('Area'), 'PowerDissipation': performance_metrics.get('PowerDissipation'),
'SlewRate': performance_metrics.get('SlewRate'), 'Gain': performance_metrics.get('Gain'),
'Bandwidth3dB': performance_metrics.get('Bandwidth3dB'), 'UnityGainFreq': performance_metrics.get('UnityGainFreq'),
'PhaseMargin': performance_metrics.get('PhaseMargin')
})
if all(region == 2 for region in transistor_regions.values()):
node_features_tensor, edge_feature_tensor, edge_index = netlist_to_graph(env.netlist_content, raw_actions, transistor_regions)
state = (torch.tensor(node_features_tensor, dtype=torch.float32), torch.tensor(edge_feature_tensor, dtype=torch.float32), torch.tensor(edge_index, dtype=torch.long))
actions = torch.tensor(raw_actions, dtype=torch.float32)
dataset.append((state, actions))
valid_sample_found = True
break
raw_actions = env.adjust_raw_actions_value(raw_actions, transistor_regions)
print("iteration count", iteration)
iteration += 1
if not valid_sample_found:
new_raw_action = sample_generator(env.bounds_low, env.bounds_high, 1)
raw_actions = new_raw_action.flatten()
save_progress(dataset, current_sample, raw_samples, required_samples, progress_filename)
print("sample count", current_sample)
current_sample += 1
env.disconnect_from_simulator() # Optionally disconnect after dataset generation
return dataset
# Example usage with environment and agent
env = YourEnvironmentClass()
agent = YourAgentClass()
dataset = pre_training_dataset_generation(env, 1000) # Generate or load pre-training dataset
pre_train_agent(agent, dataset) # Pre-train the actor network
Summary
Check Avg Loss Trend: The average loss over epochs should ideally show a decreasing trend. If it's stable but high, this is an indicator of tuning problems.
Hyperparameter Tuning: Continue experimenting with different learning rates and optimizer parameters to see their effect on the loss.
Dataset Generation and Preprocessing: Ensure that the data being fed into the model is properly processed and represents the real-world scenario adequately.
Model Complexity: If necessary, experiment with additional layers or units within the network to give it more capacity to learn from the data.
By carefully watching these details and making iterative adjustments, you should be able to determine if the pre-training of the agent is effectively progressing or identify the areas that need improvement.
Added an additional GATConv layer (gat2) to increase the network depth.
Actor:
Added an additional fully connected layer (fc1) with an intermediate dimension.
Modified the action_head to be fc2, which now takes the output of the fc1 layer.
Added a ReLU activation after fc1 to introduce non-linearity.
Experiment with Different Optimizers in Pre-Training
You can switch optimizers and inspect their effect on training:
python
def pre_train_agent(agent, dataset):
"""Pre-train the agent using the dataset"""
# Try different optimizers
pretrain_optimizer = optim.AdamW(agent.actor.parameters(), lr=1e-3, weight_decay=1e-2)
agent.actor.train()
scheduler = torch.optim.lr_scheduler.StepLR(pretrain_optimizer, step_size=30, gamma=0.1)
avg_losses = []
for epoch in range(100): # Train for 100 epochs
total_loss = 0
batch_losses = []
for state, action in dataset:
pretrain_optimizer.zero_grad()
action_means, action_stds, _ = agent.actor(state)
dist = torch.distributions.Normal(action_means, action_stds)
log_probs = dist.log_prob(action).sum(axis=-1)
loss = -log_probs.mean() # Maximize log_probs -> minimize -log_probs
loss.backward()
# Gradient Clipping
torch.nn.utils.clip_grad_norm(agent.actor.parameters(), max_norm=1.0)
pretrain_optimizer.step()
total_loss += loss.item()
batch_losses.append(loss.item())
scheduler.step()
avg_loss = total_loss / len(dataset)
avg_losses.append(avg_loss)
print(f"Epoch {epoch}, Avg Loss: {avg_loss}, Batch Losses: {batch_losses}")
# Plot the loss over epochs
plt.plot(range(100), avg_losses)
plt.xlabel('Epoch')
plt.ylabel('Average Loss')
plt.title('Pre-training Loss over Epochs')
plt.show()
By experimenting with different optimizers, tuning hyperparameters, and adjusting the model architecture, you’ll be able to identify an optimal configuration for your specific task involving continuous actions and their respective boundaries.
# Initialize Hyperparameters
in_channels = 24 # Number of input features per node
intermediate_channels = 128 # Number of intermediate hidden units
out_channels = 13 # Number of output features from GNN and size of action space
class CustomGNN(torch.nn.Module):
def __init__(self, in_channels, intermediate_channels, out_channels):
super(CustomGNN, self).__init__()
self.gat1 = GATConv(in_channels, 8, heads=8, dropout=0.2) # 24 -> 64
self.gat2 = GATConv(64, intermediate_channels, heads=8, dropout=0.2) # 64 -> 1024
self.gat3 = GATConv(intermediate_channels * 8, out_channels, heads=1, concat=False, dropout=0.2) # 1024 -> 13
def forward(self, x, edge_index):
x = F.dropout(x, p=0.2, training=self.training)
x = F.elu(self.gat1(x, edge_index))
x = F.dropout(x, p=0.2, training=self.training)
x = F.elu(self.gat2(x, edge_index))
x = F.dropout(x, p=0.2, training=self.training)
x = self.gat3(x, edge_index)
return x
class Actor(torch.nn.Module):
def __init__(self, gnn_model):
super(Actor, self).__init__()
self.gnn = gnn_model
self.fc1 = nn.Linear(out_channels, intermediate_channels) # Additional fully connected layer
self.fc2 = nn.Linear(intermediate_channels, action_space) # Original action head modified to second FC layer
self.stability_head = nn.Sequential(
nn.Linear(out_channels, 64),
nn.ReLU(),
nn.Linear(64, 1)
)
# Define bounds for action space scaling
self.bounds_low = torch.tensor([0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6,
0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6,
15e-6, 0.1e-12, 0.8], dtype=torch.float32)
self.bounds_high = torch.tensor([0.181e-6, 0.181e-6, 0.181e-6, 0.181e-6, 0.181e-6,
50e-6, 50e-6, 50e-6, 50e-6, 50e-6,
30e-6, 10e-12, 1.4], dtype=torch.float32)
def forward(self, state):
node_features_tensor, _, edge_index = state
# Processed features from the GNN
processed_features = self.gnn(node_features_tensor, edge_index)
# Global mean pooling to aggregate node features
graph_embedding = gmp(processed_features, batch=torch.zeros(processed_features.size(0), dtype=torch.long, device=processed_features.device))
# Initialize stability predictions - assume all nodes as stable
stability_pred = torch.ones(processed_features.size(0), device=processed_features.device)
# Define the indices of nodes that actually require stability prediction
unstable_nodes_idx = torch.tensor([0, 3, 5, 7, 10, 13, 15, 16], dtype=torch.long, device=processed_features.device)
# Fetch features for nodes requiring stability computation
features_for_stability = processed_features[unstable_nodes_idx]
# Compute stability predictions for these nodes
stability_pred_unstable = self.stability_head(features_for_stability).squeeze(-1)
# Update the overall stability predictions
stability_pred[unstable_nodes_idx] = stability_pred_unstable
# Fully connected network for action processing
x = F.relu(self.fc1(graph_embedding)) # Additional ReLU activation for better non-linearity
action_means = self.fc2(x) # Final action means
# Normalize and scale the GNN outputs to the action bounds for usable actions
normalized_gnn_output = torch.tanh(action_means)
action_means = self.bounds_low + (self.bounds_high - self.bounds_low) * ((normalized_gnn_output + 1) / 2)
action_log_std = torch.zeros_like(action_means)
action_std = torch.exp(action_log_std)
return action_means, action_std, stability_pred
# Example initialization
gnn_model = CustomGNN(in_channels, intermediate_channels, out_channels)
actor = Actor(gnn_model)
# Train with your dataset using pre_train_agent function
dataset = pre_training_dataset_generation(env, 1000)
pre_train_agent(actor, dataset)
CustomGNN:
Three GATConv layers are defined:
First layer: in_channels (24) to 64.
Second layer: 64 to intermediate_channels (128) with 8 heads, resulting in intermediate_channels * 8 (1024).
Third layer: intermediate_channels * 8 (1024) to out_channels (13).
Actor:
It has an additional fully connected layer (fc1) with ReLU activation.
The final layer maps the intermediate dimension (128) to the action_space (13).
You can tune the intermediate_channels to see what best suits your problem. Generally, using powers of 2 (e.g., 64, 128, 256) is a good starting point for hidden layer sizes.
Key Changes:
Use GNN in Critic:
The Critic now uses the same CustomGNN model as the Actor to process node features. This ensures the consistency of feature extraction from the state representation.
Global Mean Pooling:
After processing node features with the GNN, global mean pooling is applied to aggregate the node features into a single graph feature vector. This is similar to what we did in the Actor.
Dense Layers:
The pooled graph feature vector is then passed through two dense layers (fc1 and fc2). This setup ensures that the graph representation is properly transformed to output the single value required by the Critic.
Ensure Data Flow Consistency
Given this new design, both Actor and Critic should now use consistent data flows, making the model more robust and aligned in terms of how states are processed.
Example Training Code Integration
Integrate the Critic network into the training loop, ensuring that both actors' mean actions and critic value estimates are appropriately learned and updated:
This structure ensures that not only the Actor but also the Critic benefits from the complex feature representations extracted by the GNN, leading to more coherent and potentially more effective training.
to synchronize with the existing call function
Flattening the node_features_tensor for the critic, as your critic expects a flattened input.
how can I modify the below code in critic network to be synchronized,
class Critic(torch.nn.Module):
def init(self, gnn):
super(Critic, self).init()
self.gnn = gnn # Reuse GNN model for feature processing
intermediate_channels = 128 # Use the same intermediate channels as in Actor
code
self.fc1 = nn.Linear(out_channels, intermediate_channels)
self.fc2 = nn.Linear(intermediate_channels, 1)
def forward(self, state):
# Unpack the state
node_features_tensor, edge_feature_tensor, edge_index = state
# Process node features through the GNN
processed_features = self.gnn(node_features_tensor, edge_index)
# Global mean pooling to aggregate node features into a single graph representation
graph_embedding = gmp(processed_features, batch=torch.zeros(processed_features.size(0), dtype=torch.long, device=processed_features.device))
# Pass through the dense layers
x = F.relu(self.fc1(graph_embedding))
value = self.fc2(x)
return value
Explanation:
Dual Input Handling:
The Critic can now handle both structured state tuples (node_features_tensor, edge_feature_tensor, edge_index) and flattened state tensors.
If the input is recognized as a tuple of length 3, it processes it as a structured state.
Otherwise, it treats the input as a flattened state tensor and reshapes it into the expected node feature dimensions. If edge_feature_tensor and edge_index are needed, those should be handled or recomputed as required.
Global Mean Pooling:
Just like before, global mean pooling is used to convert node features into a single graph embedding, which is then passed through dense layers to predict the value.
Using the Critic in the Training Loop
Your existing code to calculate state_value will remain unchanged and will now be compatible with the updated Critic definition:
python
for _ in range(self.epochs):
log_probs_batch, state_values_batch, entropies_batch, stability_losses_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
# Flattening the node_features_tensor for the critic, as your critic expects a flattened input.
flattened_state = node_features_tensor.view(-1) # Adjusted to flatten the state appropriately
# Extracting the 24th feature for stability; assuming indexing starts at 0, so it’s 23rd in 0-indexing.
stability_target = node_features_tensor[:, 23].unsqueeze(1) # For the stability target
action_means, action_stds, stability_pred = self.actor(state)
# Convert stability_pred to match the binary targets if not already
stability_pred = torch.sigmoid(stability_pred).unsqueeze(1)
# Getting the state value prediction from the critic using the flattened state
state_value = self.critic(flattened_state).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)
# Stability loss
stability_loss = F.binary_cross_entropy_with_logits(stability_pred, stability_target)
stability_losses_batch.append(stability_loss.unsqueeze(0))
entropy = dist.entropy().sum(axis=-1).unsqueeze(0)
entropies_batch.append(entropy)
state_values_batch.append(state_value)
By ensuring the Critic network can handle both types of inputs, you maintain compatibility with your existing training loop, thereby avoiding disturbances in the current policy update implementation. This approach provides flexibility and improved functionality without altering the essential workflow.