class CustomGNN(torch.nn.Module):
def init(self, in_channels, intermediate_channels, out_channels):
super(CustomGNN, self).init()
self.gat1 = GATConv(in_channels, intermediate_channels, heads=8, dropout=0.2)
self.gat2 = GATConv(intermediate_channels * 8, intermediate_channels, heads=8, dropout=0.2)
self.gat3 = GATConv(intermediate_channels * 8, out_channels, heads=1, concat=False, dropout=0.2) # Final layer
def forward(self, x, edge_index):
print("x", x)
print("edge_index", 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)
# 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
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)
# 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
Above code is my GNN network, where it takes input of the 'node_features_tensor' and 'edge_index' from state input. below provided code is my updated critic network which utilize the same gnn_model which is used in the actor network, we use the same gnn_model for computing value function in the critic network, where it need the 'node_features_tensor' and 'edge_index' as inputs for computation.
But with in the function 'update_policy' present in the class 'PPOAgent' i am passing the flattened state of node_features_tensor alone in to the critic network which is not properly synchronized with the gnn_model required inputs states,
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
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"
and also with in the main training loop 'train', i am computing the value of "values.append(agent.critic(state[0]).item())" and "next_value = agent.critic(state[0]).item() if not done else 0" by simply passing the state[0] (node_features_tensor) alone to the critic network which also does not meet the requirement of inputs in the gnn_model. so i need you to modify the below code and provide me the updated code with properly synchronizing the gnn_model requirements and critic network requirements appropriately by modifying the critic network call function properly passing the required inputs to the critic network which is utilizing the implemented gnn_model appropriately,
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
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"
"values.append(agent.critic(state[0]).item())" and "next_value = agent.critic(state[0]).item() if not done else 0"
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):
# 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)
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
class PPOAgent:
def init(self, gnn_model, state_dim, action_space, lr_actor, lr_critic, gamma, gae_lambda, epsilon, policy_clip, epochs, entropy_coef):
self.actor = Actor(gnn_model)
self.critic = Critic(gnn_model)
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
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
def train(env, agent, num_episodes, max_timesteps, batch_size):
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)
for t in range(max_timesteps):
# Selecting action based on the current state
action, log_prob, perf_metrics = agent.select_action(state, performance_metrics)
next_node_features_tensor, next_edge_feature_tensor, next_edge_index, reward, done, previous_metrics = env.step(action, perf_metrics)
next_state = (next_node_features_tensor, next_edge_feature_tensor, next_edge_index)
episode_rewards.append(reward)
states.append(state)
actions.append(action)
log_probs.append(log_prob.item())
values.append(agent.critic(state[0]).item()) # Ensure Critic can handle state format
masks.append(1.0 - float(done))
perf_metrics_log.append(perf_metrics)
state = next_state
next_value = agent.critic(state[0]).item() if not done else 0