Update core/graph_mamba.py
Browse files- core/graph_mamba.py +60 -20
core/graph_mamba.py
CHANGED
@@ -6,7 +6,7 @@ from .graph_sequencer import GraphSequencer, PositionalEncoder
|
|
6 |
class GraphMamba(nn.Module):
|
7 |
"""
|
8 |
Production Graph-Mamba model
|
9 |
-
|
10 |
"""
|
11 |
|
12 |
def __init__(self, config):
|
@@ -48,14 +48,22 @@ class GraphMamba(nn.Module):
|
|
48 |
# Graph sequencer
|
49 |
self.sequencer = GraphSequencer()
|
50 |
|
51 |
-
|
|
|
|
|
|
|
52 |
"""Initialize input projection dynamically"""
|
53 |
if self.input_proj is None:
|
54 |
-
self.input_proj = nn.Linear(input_dim, self.d_model)
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
def forward(self, x, edge_index, batch=None):
|
57 |
"""
|
58 |
-
Forward pass with
|
59 |
|
60 |
Args:
|
61 |
x: Node features (num_nodes, input_dim)
|
@@ -64,9 +72,13 @@ class GraphMamba(nn.Module):
|
|
64 |
"""
|
65 |
num_nodes = x.size(0)
|
66 |
input_dim = x.size(1)
|
|
|
|
|
|
|
|
|
67 |
|
68 |
# Initialize input projection if needed
|
69 |
-
self._init_input_proj(input_dim)
|
70 |
|
71 |
# Project input features
|
72 |
h = self.input_proj(x) # (num_nodes, d_model)
|
@@ -81,22 +93,31 @@ class GraphMamba(nn.Module):
|
|
81 |
return h
|
82 |
|
83 |
def _process_single_graph(self, h, edge_index):
|
84 |
-
"""Process a single graph"""
|
85 |
num_nodes = h.size(0)
|
|
|
|
|
|
|
|
|
86 |
|
87 |
# Get ordering
|
88 |
-
if self.ordering_strategy == "
|
89 |
-
# Use BFS as primary for now (can be extended)
|
90 |
-
order = self.sequencer.bfs_ordering(edge_index, num_nodes)
|
91 |
-
elif self.ordering_strategy == "spectral":
|
92 |
order = self.sequencer.spectral_ordering(edge_index, num_nodes)
|
93 |
elif self.ordering_strategy == "degree":
|
94 |
order = self.sequencer.degree_ordering(edge_index, num_nodes)
|
|
|
|
|
95 |
else: # default to BFS
|
96 |
order = self.sequencer.bfs_ordering(edge_index, num_nodes)
|
97 |
|
|
|
|
|
|
|
98 |
# Add positional encoding
|
99 |
seq_pos, distances = self.pos_encoder.encode_positions(h, edge_index, order)
|
|
|
|
|
|
|
100 |
pos_features = torch.cat([seq_pos, distances], dim=1) # (num_nodes, 11)
|
101 |
pos_embed = self.pos_embed(pos_features)
|
102 |
|
@@ -119,7 +140,11 @@ class GraphMamba(nn.Module):
|
|
119 |
return h_final
|
120 |
|
121 |
def _process_batch(self, h, edge_index, batch):
|
122 |
-
"""Process batched graphs"""
|
|
|
|
|
|
|
|
|
123 |
batch_size = batch.max().item() + 1
|
124 |
outputs = []
|
125 |
|
@@ -132,11 +157,15 @@ class GraphMamba(nn.Module):
|
|
132 |
edge_mask = mask[edge_index[0]] & mask[edge_index[1]]
|
133 |
batch_edges = edge_index[:, edge_mask]
|
134 |
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
|
|
140 |
|
141 |
# Process subgraph
|
142 |
batch_output = self._process_single_graph(batch_h, batch_edges_local)
|
@@ -144,7 +173,6 @@ class GraphMamba(nn.Module):
|
|
144 |
|
145 |
# Reconstruct full batch
|
146 |
h_out = torch.zeros_like(h)
|
147 |
-
start_idx = 0
|
148 |
for b, output in enumerate(outputs):
|
149 |
mask = batch == b
|
150 |
h_out[mask] = output
|
@@ -157,6 +185,18 @@ class GraphMamba(nn.Module):
|
|
157 |
# Single graph - mean pooling
|
158 |
return h.mean(dim=0, keepdim=True)
|
159 |
else:
|
160 |
-
# Batched graphs
|
161 |
-
|
162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
6 |
class GraphMamba(nn.Module):
|
7 |
"""
|
8 |
Production Graph-Mamba model
|
9 |
+
Device-safe implementation with dynamic handling
|
10 |
"""
|
11 |
|
12 |
def __init__(self, config):
|
|
|
48 |
# Graph sequencer
|
49 |
self.sequencer = GraphSequencer()
|
50 |
|
51 |
+
# Classification head (for demo)
|
52 |
+
self.classifier = None
|
53 |
+
|
54 |
+
def _init_input_proj(self, input_dim, device):
|
55 |
"""Initialize input projection dynamically"""
|
56 |
if self.input_proj is None:
|
57 |
+
self.input_proj = nn.Linear(input_dim, self.d_model).to(device)
|
58 |
+
|
59 |
+
def _init_classifier(self, num_classes, device):
|
60 |
+
"""Initialize classifier dynamically"""
|
61 |
+
if self.classifier is None:
|
62 |
+
self.classifier = nn.Linear(self.d_model, num_classes).to(device)
|
63 |
|
64 |
def forward(self, x, edge_index, batch=None):
|
65 |
"""
|
66 |
+
Forward pass with device-safe handling
|
67 |
|
68 |
Args:
|
69 |
x: Node features (num_nodes, input_dim)
|
|
|
72 |
"""
|
73 |
num_nodes = x.size(0)
|
74 |
input_dim = x.size(1)
|
75 |
+
device = x.device
|
76 |
+
|
77 |
+
# Move all components to correct device
|
78 |
+
self.to(device)
|
79 |
|
80 |
# Initialize input projection if needed
|
81 |
+
self._init_input_proj(input_dim, device)
|
82 |
|
83 |
# Project input features
|
84 |
h = self.input_proj(x) # (num_nodes, d_model)
|
|
|
93 |
return h
|
94 |
|
95 |
def _process_single_graph(self, h, edge_index):
|
96 |
+
"""Process a single graph - device safe"""
|
97 |
num_nodes = h.size(0)
|
98 |
+
device = h.device
|
99 |
+
|
100 |
+
# Ensure edge_index is on correct device
|
101 |
+
edge_index = edge_index.to(device)
|
102 |
|
103 |
# Get ordering
|
104 |
+
if self.ordering_strategy == "spectral":
|
|
|
|
|
|
|
105 |
order = self.sequencer.spectral_ordering(edge_index, num_nodes)
|
106 |
elif self.ordering_strategy == "degree":
|
107 |
order = self.sequencer.degree_ordering(edge_index, num_nodes)
|
108 |
+
elif self.ordering_strategy == "community":
|
109 |
+
order = self.sequencer.community_ordering(edge_index, num_nodes)
|
110 |
else: # default to BFS
|
111 |
order = self.sequencer.bfs_ordering(edge_index, num_nodes)
|
112 |
|
113 |
+
# Ensure order is on correct device
|
114 |
+
order = order.to(device)
|
115 |
+
|
116 |
# Add positional encoding
|
117 |
seq_pos, distances = self.pos_encoder.encode_positions(h, edge_index, order)
|
118 |
+
seq_pos = seq_pos.to(device)
|
119 |
+
distances = distances.to(device)
|
120 |
+
|
121 |
pos_features = torch.cat([seq_pos, distances], dim=1) # (num_nodes, 11)
|
122 |
pos_embed = self.pos_embed(pos_features)
|
123 |
|
|
|
140 |
return h_final
|
141 |
|
142 |
def _process_batch(self, h, edge_index, batch):
|
143 |
+
"""Process batched graphs - device safe"""
|
144 |
+
device = h.device
|
145 |
+
batch = batch.to(device)
|
146 |
+
edge_index = edge_index.to(device)
|
147 |
+
|
148 |
batch_size = batch.max().item() + 1
|
149 |
outputs = []
|
150 |
|
|
|
157 |
edge_mask = mask[edge_index[0]] & mask[edge_index[1]]
|
158 |
batch_edges = edge_index[:, edge_mask]
|
159 |
|
160 |
+
if batch_edges.shape[1] > 0:
|
161 |
+
# Reindex edges to local indices
|
162 |
+
node_indices = torch.where(mask)[0]
|
163 |
+
node_map = torch.zeros(h.size(0), dtype=torch.long, device=device)
|
164 |
+
node_map[node_indices] = torch.arange(batch_h.size(0), device=device)
|
165 |
+
batch_edges_local = node_map[batch_edges]
|
166 |
+
else:
|
167 |
+
# Empty graph
|
168 |
+
batch_edges_local = torch.empty((2, 0), dtype=torch.long, device=device)
|
169 |
|
170 |
# Process subgraph
|
171 |
batch_output = self._process_single_graph(batch_h, batch_edges_local)
|
|
|
173 |
|
174 |
# Reconstruct full batch
|
175 |
h_out = torch.zeros_like(h)
|
|
|
176 |
for b, output in enumerate(outputs):
|
177 |
mask = batch == b
|
178 |
h_out[mask] = output
|
|
|
185 |
# Single graph - mean pooling
|
186 |
return h.mean(dim=0, keepdim=True)
|
187 |
else:
|
188 |
+
# Batched graphs - manual pooling to avoid dependencies
|
189 |
+
device = h.device
|
190 |
+
batch = batch.to(device)
|
191 |
+
batch_size = batch.max().item() + 1
|
192 |
+
|
193 |
+
graph_embeddings = []
|
194 |
+
for b in range(batch_size):
|
195 |
+
mask = batch == b
|
196 |
+
if mask.any():
|
197 |
+
graph_emb = h[mask].mean(dim=0)
|
198 |
+
graph_embeddings.append(graph_emb)
|
199 |
+
else:
|
200 |
+
graph_embeddings.append(torch.zeros(h.size(1), device=device))
|
201 |
+
|
202 |
+
return torch.stack(graph_embeddings)
|