RameshArvind commited on
Commit
eefc84e
·
verified ·
1 Parent(s): 1c29bf1

Upload iterative_pagerank.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. iterative_pagerank.py +691 -0
iterative_pagerank.py ADDED
@@ -0,0 +1,691 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Non-autoregressive iterative PageRank model.
3
+
4
+ PageRank IS power iteration — the same linear operation applied repeatedly
5
+ until convergence. This maps perfectly to shared-weight iterative transformers.
6
+
7
+ Architecture:
8
+ - Input: N nodes, each gets its adjacency row (directed graph)
9
+ - Shared transformer body (bidirectional attention)
10
+ - Output: each node predicts its PageRank value (regression)
11
+ - Iterative refinement mirrors power iteration
12
+ - Train with K=16, eval with K=16..256+
13
+
14
+ Difficulty knobs:
15
+ - Damping factor d: higher d → more structure-dependent → harder
16
+ - Graph type: random (easy) → power-law/hub (hard)
17
+ - Edge density: affects spectral gap → convergence rate
18
+
19
+ Usage:
20
+ python scripts/iterative_pagerank.py --device cpu --steps 500 --batch 64 --n-nodes 16
21
+ python scripts/iterative_pagerank.py --device cuda --steps 50000 --batch 2048 --compile
22
+ """
23
+
24
+ import argparse
25
+ import math
26
+ import time
27
+ from contextlib import nullcontext
28
+ from dataclasses import dataclass
29
+
30
+ import torch
31
+ import torch.nn as nn
32
+ import torch.nn.functional as F
33
+
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # Config
37
+ # ---------------------------------------------------------------------------
38
+
39
+ @dataclass
40
+ class PageRankConfig:
41
+ n_nodes: int = 64
42
+ d_model: int = 128
43
+ n_heads: int = 4
44
+ n_layers: int = 4
45
+ d_ff: int = 512
46
+ dropout: float = 0.1
47
+ train_iters: int = 16
48
+ rope_base: float = 10.0
49
+ damping: float = 0.85 # PageRank damping factor
50
+
51
+ # Reverse curriculum: hard mixed graphs from start (sotaku-style)
52
+ # graph_type_weights: [random, preferential_attachment, hub_spoke]
53
+ curriculum: tuple = (
54
+ (0.0, 0.08, (0.2, 0.5, 0.3)),
55
+ (1.0, 0.08, (0.2, 0.5, 0.3)),
56
+ )
57
+
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # RoPE
61
+ # ---------------------------------------------------------------------------
62
+
63
+ def build_rope_cache(seq_len, head_dim, base=10.0, device="cpu"):
64
+ theta = 1.0 / (base ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim))
65
+ positions = torch.arange(seq_len, device=device).float()
66
+ freqs = torch.outer(positions, theta)
67
+ return freqs.cos(), freqs.sin()
68
+
69
+
70
+ def apply_rope(x, cos, sin):
71
+ d2 = x.shape[-1] // 2
72
+ x1, x2 = x[..., :d2], x[..., d2:]
73
+ cos, sin = cos[:x.shape[2], :], sin[:x.shape[2], :]
74
+ return torch.cat([x1 * cos - x2 * sin, x2 * cos + x1 * sin], dim=-1)
75
+
76
+
77
+ # ---------------------------------------------------------------------------
78
+ # Transformer layers
79
+ # ---------------------------------------------------------------------------
80
+
81
+ class MultiHeadAttention(nn.Module):
82
+ def __init__(self, d_model, n_heads, dropout=0.1):
83
+ super().__init__()
84
+ self.n_heads = n_heads
85
+ self.head_dim = d_model // n_heads
86
+ self.wq = nn.Linear(d_model, d_model, bias=False)
87
+ self.wk = nn.Linear(d_model, d_model, bias=False)
88
+ self.wv = nn.Linear(d_model, d_model, bias=False)
89
+ self.wo = nn.Linear(d_model, d_model, bias=False)
90
+ self.dropout = nn.Dropout(dropout)
91
+
92
+ def forward(self, x, cos, sin, adj_bias=None):
93
+ B, N, D = x.shape
94
+ q = self.wq(x).view(B, N, self.n_heads, self.head_dim).transpose(1, 2)
95
+ k = self.wk(x).view(B, N, self.n_heads, self.head_dim).transpose(1, 2)
96
+ v = self.wv(x).view(B, N, self.n_heads, self.head_dim).transpose(1, 2)
97
+ q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
98
+ attn = F.scaled_dot_product_attention(
99
+ q, k, v, attn_mask=adj_bias,
100
+ dropout_p=self.dropout.p if self.training else 0.0,
101
+ )
102
+ return self.wo(attn.transpose(1, 2).contiguous().view(B, N, D))
103
+
104
+
105
+ class TransformerBlock(nn.Module):
106
+ def __init__(self, d_model, n_heads, d_ff, dropout=0.1):
107
+ super().__init__()
108
+ self.norm1 = nn.RMSNorm(d_model)
109
+ self.attn = MultiHeadAttention(d_model, n_heads, dropout)
110
+ self.norm2 = nn.RMSNorm(d_model)
111
+ self.ff = nn.Sequential(
112
+ nn.Linear(d_model, d_ff, bias=False),
113
+ nn.ReLU(),
114
+ nn.Linear(d_ff, d_model, bias=False),
115
+ nn.Dropout(dropout),
116
+ )
117
+
118
+ def forward(self, x, cos, sin, adj_bias=None):
119
+ x = x + self.attn(self.norm1(x), cos, sin, adj_bias)
120
+ x = x + self.ff(self.norm2(x))
121
+ return x
122
+
123
+
124
+ # ---------------------------------------------------------------------------
125
+ # PageRank Model
126
+ # ---------------------------------------------------------------------------
127
+
128
+ class IterativePageRankModel(nn.Module):
129
+ def __init__(self, config: PageRankConfig):
130
+ super().__init__()
131
+ self.config = config
132
+ d = config.d_model
133
+ N = config.n_nodes
134
+
135
+ # Input: adjacency row (N) → d_model
136
+ self.input_proj = nn.Linear(N, d, bias=False)
137
+
138
+ # Prediction feedback: previous PR estimate (1 scalar per node) → d_model
139
+ self.pred_proj = nn.Linear(1, d, bias=False)
140
+
141
+ # Shared transformer
142
+ self.layers = nn.ModuleList([
143
+ TransformerBlock(d, config.n_heads, config.d_ff, config.dropout)
144
+ for _ in range(config.n_layers)
145
+ ])
146
+ self.final_norm = nn.RMSNorm(d)
147
+
148
+ # Output: d_model → 1 (PageRank logit per node)
149
+ self.output_head = nn.Linear(d, 1, bias=False)
150
+
151
+ cos, sin = build_rope_cache(N, d // config.n_heads, config.rope_base)
152
+ self.register_buffer("rope_cos", cos)
153
+ self.register_buffer("rope_sin", sin)
154
+
155
+ def _transformer_step(self, h_input, cos, sin, adj_bias):
156
+ x = h_input
157
+ for layer in self.layers:
158
+ x = layer(x, cos, sin, adj_bias)
159
+ x = self.final_norm(x)
160
+ return self.output_head(x)
161
+
162
+ def forward(self, adj, n_iters=None):
163
+ """
164
+ adj: (B, N, N) directed adjacency matrix
165
+ Returns: list of PR predictions (B, N), one per iteration
166
+ """
167
+ if n_iters is None:
168
+ n_iters = self.config.train_iters
169
+
170
+ B, N, _ = adj.shape
171
+ device = adj.device
172
+
173
+ # Adjacency bias for attention: edges get a boost
174
+ adj_bias = adj * 2.0
175
+ adj_bias = adj_bias.unsqueeze(1) # (B, 1, N, N)
176
+
177
+ # Encode graph structure
178
+ h = self.input_proj(adj) # (B, N, d)
179
+
180
+ all_prs = []
181
+ # Initial PR estimate: uniform
182
+ pr_pred = torch.full((B, N, 1), 1.0 / N, device=device)
183
+
184
+ for _ in range(n_iters):
185
+ h_input = h + self.pred_proj(pr_pred)
186
+ logits = self._transformer_step(h_input, self.rope_cos, self.rope_sin, adj_bias)
187
+ # logits: (B, N, 1) → softmax across nodes to get PR distribution
188
+ pr = F.softmax(logits.squeeze(-1), dim=-1) # (B, N)
189
+ all_prs.append(pr)
190
+ pr_pred = pr.unsqueeze(-1).detach()
191
+
192
+ return all_prs
193
+
194
+
195
+ # ---------------------------------------------------------------------------
196
+ # Ground truth PageRank (power iteration)
197
+ # ---------------------------------------------------------------------------
198
+
199
+ def compute_pagerank(adj: torch.Tensor, damping: float = 0.85, n_iters: int = 30, tol: float = 1e-8):
200
+ """Compute PageRank via power iteration.
201
+
202
+ adj: (B, N, N) directed adjacency (adj[i,j]=1 means edge from i to j)
203
+ Returns: (B, N) PageRank values summing to 1
204
+ """
205
+ B, N, _ = adj.shape
206
+ device = adj.device
207
+
208
+ # Out-degree per node
209
+ out_deg = adj.sum(dim=-1, keepdim=True).clamp(min=1) # (B, N, 1)
210
+
211
+ # Transition matrix: M[j,i] = adj[i,j] / out_deg[i]
212
+ # (probability of going from i to j)
213
+ M = (adj / out_deg).transpose(1, 2) # (B, N, N)
214
+
215
+ # Power iteration
216
+ pr = torch.full((B, N), 1.0 / N, device=device)
217
+ teleport = (1 - damping) / N
218
+
219
+ for _ in range(n_iters):
220
+ pr_new = teleport + damping * (M @ pr.unsqueeze(-1)).squeeze(-1)
221
+ # Handle dangling nodes (no outgoing edges): redistribute their mass
222
+ dangling_mass = pr * (adj.sum(dim=-1) == 0).float()
223
+ pr_new = pr_new + damping * dangling_mass.sum(dim=-1, keepdim=True) / N
224
+ # Normalize
225
+ pr_new = pr_new / pr_new.sum(dim=-1, keepdim=True)
226
+
227
+ if (pr_new - pr).abs().max() < tol:
228
+ break
229
+ pr = pr_new
230
+
231
+ return pr
232
+
233
+
234
+ # ---------------------------------------------------------------------------
235
+ # Graph generation
236
+ # ---------------------------------------------------------------------------
237
+
238
+ def generate_random_graph(batch_size, n_nodes, edge_prob, device):
239
+ """Erdos-Renyi directed random graph."""
240
+ adj = (torch.rand(batch_size, n_nodes, n_nodes, device=device) < edge_prob).float()
241
+ adj[:, range(n_nodes), range(n_nodes)] = 0 # no self-loops
242
+ return adj
243
+
244
+
245
+ def generate_preferential_attachment(batch_size, n_nodes, n_edges_per_node, device):
246
+ """Barabasi-Albert: sequential node addition with degree-proportional attachment.
247
+ Creates true power-law degree distribution. Uses CPU for generation, moves to device.
248
+ """
249
+ adj = torch.zeros(batch_size, n_nodes, n_nodes)
250
+ m = max(1, n_edges_per_node)
251
+
252
+ # Start with a small clique
253
+ for i in range(min(m + 1, n_nodes)):
254
+ for j in range(i + 1, min(m + 1, n_nodes)):
255
+ adj[:, i, j] = 1
256
+
257
+ for new_node in range(m + 1, n_nodes):
258
+ deg = adj[:, :new_node, :new_node].sum(dim=-1) + adj[:, :new_node, :new_node].sum(dim=-2)
259
+ deg = deg + 1
260
+ probs = deg / deg.sum(dim=-1, keepdim=True)
261
+
262
+ for _ in range(m):
263
+ targets = torch.multinomial(probs, 1).squeeze(-1)
264
+ adj[torch.arange(batch_size), new_node, targets] = 1
265
+ reverse = torch.rand(batch_size) < 0.5
266
+ adj[torch.arange(batch_size)[reverse], targets[reverse], new_node] = 1
267
+
268
+ return adj.to(device)
269
+
270
+
271
+ def generate_hub_spoke(batch_size, n_nodes, n_hubs, device):
272
+ """Hub-spoke graphs: few hub nodes connected to many spokes.
273
+ Uses CPU for generation, moves to device.
274
+ """
275
+ adj = torch.zeros(batch_size, n_nodes, n_nodes)
276
+
277
+ hub_indices = torch.randint(0, n_nodes, (batch_size, n_hubs))
278
+
279
+ for i in range(n_nodes):
280
+ for h in range(n_hubs):
281
+ connect = torch.rand(batch_size) < 0.6
282
+ hub = hub_indices[:, h]
283
+ adj[connect, i, hub[connect]] = 1
284
+ back = connect & (torch.rand(batch_size) < 0.3)
285
+ adj[back, hub[back], i] = 1
286
+
287
+ for h1 in range(n_hubs):
288
+ for h2 in range(h1 + 1, n_hubs):
289
+ connect = torch.rand(batch_size) < 0.8
290
+ adj[connect, hub_indices[connect, h1], hub_indices[connect, h2]] = 1
291
+ adj[connect, hub_indices[connect, h2], hub_indices[connect, h1]] = 1
292
+
293
+ noise = (torch.rand(batch_size, n_nodes, n_nodes) < 0.02).float()
294
+ adj = (adj + noise).clamp(max=1)
295
+ adj[:, range(n_nodes), range(n_nodes)] = 0
296
+
297
+ return adj.to(device)
298
+
299
+
300
+ def generate_batch(batch_size, config, edge_prob, graph_weights, device):
301
+ """Generate mixed batch of graph types."""
302
+ N = config.n_nodes
303
+ w_random, w_pref, w_hub = graph_weights
304
+
305
+ # Determine count per type
306
+ n_random = int(batch_size * w_random)
307
+ n_pref = int(batch_size * w_pref)
308
+ n_hub = batch_size - n_random - n_pref
309
+
310
+ adjs = []
311
+ if n_random > 0:
312
+ adjs.append(generate_random_graph(n_random, N, edge_prob, device))
313
+ if n_pref > 0:
314
+ n_edges = max(1, int(edge_prob * N * 0.5))
315
+ adjs.append(generate_preferential_attachment(n_pref, N, n_edges, device))
316
+ if n_hub > 0:
317
+ n_hubs = max(2, N // 16)
318
+ adjs.append(generate_hub_spoke(n_hub, N, n_hubs, device))
319
+
320
+ adj = torch.cat(adjs, dim=0) if len(adjs) > 1 else adjs[0]
321
+
322
+ # Shuffle
323
+ perm = torch.randperm(batch_size, device=device)
324
+ adj = adj[perm]
325
+
326
+ # Compute ground truth PageRank
327
+ targets = compute_pagerank(adj, damping=config.damping)
328
+
329
+ # Stats
330
+ with torch.no_grad():
331
+ entropy = -(targets * (targets + 1e-10).log()).sum(dim=-1).mean().item()
332
+ max_pr = targets.max(dim=-1).values.mean().item()
333
+ gini = _gini(targets)
334
+
335
+ metadata = {
336
+ "edge_prob": edge_prob,
337
+ "entropy": entropy,
338
+ "max_pr": max_pr,
339
+ "gini": gini,
340
+ }
341
+
342
+ return adj, targets, metadata
343
+
344
+
345
+ def _gini(pr):
346
+ """Gini coefficient of PageRank distribution. 0=uniform, 1=concentrated."""
347
+ sorted_pr, _ = pr.sort(dim=-1)
348
+ N = pr.shape[-1]
349
+ index = torch.arange(1, N + 1, device=pr.device).float()
350
+ return (2 * (index * sorted_pr).sum(dim=-1) / (N * sorted_pr.sum(dim=-1)) - (N + 1) / N).mean().item()
351
+
352
+
353
+ def get_curriculum_params(step, total_steps, curriculum):
354
+ """Get current edge_prob and graph_weights from curriculum."""
355
+ frac = step / max(1, total_steps)
356
+ for i in range(len(curriculum) - 1):
357
+ f0, p0, w0 = curriculum[i]
358
+ f1, p1, w1 = curriculum[i + 1]
359
+ if f0 <= frac <= f1:
360
+ if f1 == f0:
361
+ return p0, w0
362
+ t = (frac - f0) / (f1 - f0)
363
+ p = p0 + t * (p1 - p0)
364
+ w = tuple(a + t * (b - a) for a, b in zip(w0, w1))
365
+ return p, w
366
+ return curriculum[-1][1], curriculum[-1][2]
367
+
368
+
369
+ # ---------------------------------------------------------------------------
370
+ # Training
371
+ # ---------------------------------------------------------------------------
372
+
373
+ def train(config, args):
374
+ device = args.device
375
+
376
+ if device == "cuda":
377
+ torch.set_float32_matmul_precision('high')
378
+ torch.backends.cuda.matmul.allow_tf32 = True
379
+ torch.backends.cudnn.allow_tf32 = True
380
+
381
+ model = IterativePageRankModel(config).to(device)
382
+ n_params = sum(p.numel() for p in model.parameters())
383
+ print(f"Model params: {n_params:,} ({n_params/1e6:.2f}M)")
384
+ print(f"Config: {config.n_layers}L, d={config.d_model}, h={config.n_heads}, "
385
+ f"ff={config.d_ff}, iters={config.train_iters}, N={config.n_nodes}")
386
+ print(f"Damping: {config.damping}")
387
+ print(f"Device: {device}")
388
+ print()
389
+
390
+ optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, betas=(0.9, 0.95), weight_decay=0.01)
391
+
392
+ def lr_schedule(step):
393
+ if step < args.warmup:
394
+ return step / args.warmup
395
+ progress = (step - args.warmup) / max(1, args.steps - args.warmup)
396
+ return 0.01 + 0.99 * 0.5 * (1 + math.cos(math.pi * progress))
397
+
398
+ scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_schedule)
399
+
400
+ if args.compile and device == "cuda":
401
+ print("Compiling transformer step...")
402
+ model._transformer_step = torch.compile(model._transformer_step)
403
+ print("Compile done.")
404
+
405
+ use_amp = device == "cuda"
406
+ scaler = torch.amp.GradScaler('cuda', enabled=use_amp)
407
+ autocast_ctx = torch.amp.autocast('cuda', dtype=torch.bfloat16) if use_amp else nullcontext()
408
+
409
+ # Pre-generate graph pool for fast sampling during training
410
+ pool_size = min(args.steps * args.batch, 100_000) # cap at 100K graphs
411
+ print(f"Pre-generating {pool_size:,} graphs...")
412
+ edge_prob, graph_weights = get_curriculum_params(0, args.steps, config.curriculum)
413
+ pool_adj, pool_targets, pool_meta = generate_batch(pool_size, config, edge_prob, graph_weights, device)
414
+ print(f"Pool ready. Gini={pool_meta['gini']:.2f}, max_pr={pool_meta['max_pr']:.4f}")
415
+
416
+ t0 = time.time()
417
+
418
+ for step in range(args.steps + 1):
419
+ model.train()
420
+
421
+ # Sample batch from pre-generated pool
422
+ idx = torch.randint(0, pool_size, (args.batch,), device=device)
423
+ adj = pool_adj[idx]
424
+ targets = pool_targets[idx]
425
+ meta = pool_meta
426
+
427
+ with autocast_ctx:
428
+ all_prs = model(adj)
429
+
430
+ # Loss: KL divergence at every iteration (intermediate supervision)
431
+ # targets is the true PR distribution, all_prs[i] is predicted distribution
432
+ loss = 0.0
433
+ for pr_pred in all_prs:
434
+ # KL(target || pred) = sum(target * log(target/pred))
435
+ loss += F.kl_div(
436
+ (pr_pred + 1e-10).log(),
437
+ targets,
438
+ reduction='batchmean',
439
+ )
440
+ loss /= len(all_prs)
441
+
442
+ optimizer.zero_grad()
443
+ scaler.scale(loss).backward()
444
+ scaler.unscale_(optimizer)
445
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
446
+ scaler.step(optimizer)
447
+ scaler.update()
448
+ scheduler.step()
449
+
450
+ if step % args.log_interval == 0:
451
+ elapsed = time.time() - t0
452
+ with torch.no_grad():
453
+ final_pr = all_prs[-1]
454
+ mse = ((final_pr - targets) ** 2).mean().item()
455
+ # Ranking accuracy: Kendall tau correlation
456
+ rank_acc = _ranking_accuracy(final_pr, targets)
457
+ # Top-5 accuracy
458
+ top5_acc = _topk_accuracy(final_pr, targets, k=5)
459
+
460
+ print(f"Step {step:5d} | KL: {loss.item():.4f} | MSE: {mse:.6f} | "
461
+ f"Rank: {rank_acc:.1%} | Top5: {top5_acc:.1%} | "
462
+ f"Gini: {meta['gini']:.2f} | {elapsed:.1f}s")
463
+
464
+ if step > 0 and step % args.eval_interval == 0:
465
+ evaluate(model, config, device, args.eval_batch)
466
+
467
+ print("\n" + "=" * 70)
468
+ print("FINAL EVALUATION")
469
+ print("=" * 70)
470
+ evaluate(model, config, device, args.eval_batch, verbose=True)
471
+
472
+ if args.save_path:
473
+ save_checkpoint(model, config, args)
474
+
475
+ return model
476
+
477
+
478
+ def _ranking_accuracy(pred_pr, true_pr):
479
+ """Fraction of pairwise orderings that match."""
480
+ pred_rank = pred_pr.argsort(dim=-1, descending=True).argsort(dim=-1)
481
+ true_rank = true_pr.argsort(dim=-1, descending=True).argsort(dim=-1)
482
+ # Pairwise concordance (simplified Kendall tau)
483
+ B, N = pred_pr.shape
484
+ correct = 0
485
+ total = 0
486
+ # Sample pairs for efficiency
487
+ n_pairs = min(100, N * (N - 1) // 2)
488
+ for _ in range(n_pairs):
489
+ i, j = torch.randint(0, N, (2,))
490
+ if i == j:
491
+ continue
492
+ pred_order = pred_pr[:, i] > pred_pr[:, j]
493
+ true_order = true_pr[:, i] > true_pr[:, j]
494
+ correct += (pred_order == true_order).float().sum().item()
495
+ total += B
496
+ return correct / max(1, total)
497
+
498
+
499
+ def _topk_accuracy(pred_pr, true_pr, k=5):
500
+ """Fraction of true top-k nodes that appear in predicted top-k."""
501
+ pred_topk = pred_pr.topk(k, dim=-1).indices # (B, k)
502
+ true_topk = true_pr.topk(k, dim=-1).indices # (B, k)
503
+ # Check overlap
504
+ hits = 0
505
+ for i in range(k):
506
+ hits += (pred_topk == true_topk[:, i:i+1]).any(dim=-1).float().sum().item()
507
+ return hits / (pred_pr.shape[0] * k)
508
+
509
+
510
+ def evaluate(model, config, device, eval_batch=1024, verbose=False):
511
+ """Evaluate across graph types and iteration counts."""
512
+ model.eval()
513
+
514
+ graph_configs = [
515
+ ("Random p=0.15", 0.15, (1.0, 0.0, 0.0)),
516
+ ("Preferential", 0.10, (0.0, 1.0, 0.0)),
517
+ ("Hub-spoke", 0.10, (0.0, 0.0, 1.0)),
518
+ ("Mixed (hard)", 0.08, (0.2, 0.5, 0.3)),
519
+ ]
520
+ iter_counts = [config.train_iters, 32, 64, 128, 256]
521
+
522
+ for name, ep, gw in graph_configs:
523
+ adj, targets, meta = generate_batch(eval_batch, config, ep, gw, device)
524
+
525
+ print(f"\n {name} (gini={meta['gini']:.2f}, max_pr={meta['max_pr']:.4f})")
526
+ print(f" {'Iters':>6s} | {'KL':>8s} | {'MSE':>10s} | {'Rank':>6s} | {'Top5':>6s}")
527
+ print(f" {'-'*6} | {'-'*8} | {'-'*10} | {'-'*6} | {'-'*6}")
528
+
529
+ for n_iters in iter_counts:
530
+ with torch.no_grad():
531
+ all_prs = model(adj, n_iters=n_iters)
532
+ final_pr = all_prs[-1]
533
+ kl = F.kl_div((final_pr + 1e-10).log(), targets, reduction='batchmean').item()
534
+ mse = ((final_pr - targets) ** 2).mean().item()
535
+ rank_acc = _ranking_accuracy(final_pr, targets)
536
+ top5_acc = _topk_accuracy(final_pr, targets, k=5)
537
+
538
+ print(f" {n_iters:6d} | {kl:8.4f} | {mse:10.6f} | {rank_acc:5.1%} | {top5_acc:5.1%}")
539
+
540
+ if verbose:
541
+ # Show examples from hub-spoke (most non-uniform PR)
542
+ adj, targets, _ = generate_batch(4, config, 0.10, (0.0, 0.0, 1.0), device)
543
+ with torch.no_grad():
544
+ all_prs = model(adj, n_iters=256)
545
+ final_pr = all_prs[-1]
546
+
547
+ print(f"\n Sample predictions (hub-spoke, 256 iters):")
548
+ for i in range(min(4, len(adj))):
549
+ true_topk = targets[i].topk(5)
550
+ pred_topk = final_pr[i].topk(5)
551
+ true_str = ", ".join(f"n{idx}={val:.3f}" for val, idx in zip(true_topk.values, true_topk.indices))
552
+ pred_str = ", ".join(f"n{idx}={val:.3f}" for val, idx in zip(pred_topk.values, pred_topk.indices))
553
+ mse_i = ((final_pr[i] - targets[i]) ** 2).mean().item()
554
+ print(f" MSE={mse_i:.6f}")
555
+ print(f" True top5: {true_str}")
556
+ print(f" Pred top5: {pred_str}")
557
+
558
+
559
+ def save_checkpoint(model, config, args):
560
+ import json, os, tempfile
561
+
562
+ raw_model = model._orig_mod if hasattr(model, '_orig_mod') else model
563
+ checkpoint = {
564
+ "model_state_dict": raw_model.state_dict(),
565
+ "config": {
566
+ "n_nodes": config.n_nodes,
567
+ "d_model": config.d_model,
568
+ "n_heads": config.n_heads,
569
+ "n_layers": config.n_layers,
570
+ "d_ff": config.d_ff,
571
+ "dropout": config.dropout,
572
+ "train_iters": config.train_iters,
573
+ "rope_base": config.rope_base,
574
+ "damping": config.damping,
575
+ },
576
+ }
577
+ torch.save(checkpoint, args.save_path)
578
+ print(f"\nCheckpoint saved to {args.save_path}")
579
+
580
+ if args.upload_hf:
581
+ from huggingface_hub import HfApi
582
+ api = HfApi()
583
+ try:
584
+ api.create_repo(args.upload_hf, exist_ok=True)
585
+ except Exception as e:
586
+ print(f"Warning: {e}")
587
+
588
+ api.upload_file(path_or_fileobj=args.save_path, path_in_repo="model.pt", repo_id=args.upload_hf)
589
+ api.upload_file(path_or_fileobj=os.path.abspath(__file__), path_in_repo="iterative_pagerank.py", repo_id=args.upload_hf)
590
+
591
+ config_json = json.dumps(checkpoint["config"], indent=2)
592
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
593
+ f.write(config_json)
594
+ cfg_path = f.name
595
+ api.upload_file(path_or_fileobj=cfg_path, path_in_repo="config.json", repo_id=args.upload_hf)
596
+ os.unlink(cfg_path)
597
+
598
+ n_params = sum(p.numel() for p in raw_model.parameters())
599
+ card = f"""# Iterative PageRank Model
600
+
601
+ Non-autoregressive iterative transformer that learns PageRank via shared-weight refinement.
602
+
603
+ ## Architecture
604
+ - **Params:** {n_params:,}
605
+ - **Layers:** {config.n_layers} (shared across {config.train_iters} iterations)
606
+ - **Width:** {config.d_model}, **Heads:** {config.n_heads}
607
+ - **Graph size:** {config.n_nodes} nodes (directed)
608
+ - **Damping:** {config.damping}
609
+
610
+ ## Task
611
+ Given a directed graph's adjacency matrix, predict each node's PageRank value.
612
+ The model learns power iteration implicitly through iterative refinement.
613
+
614
+ ## Metrics
615
+ - **KL divergence:** between predicted and true PR distribution
616
+ - **Ranking accuracy:** pairwise ordering correctness
617
+ - **Top-k accuracy:** overlap of predicted vs true top-k important nodes
618
+
619
+ ## Usage
620
+ ```python
621
+ import torch
622
+ from iterative_pagerank import IterativePageRankModel, PageRankConfig, generate_batch
623
+
624
+ ckpt = torch.load("model.pt", weights_only=True)
625
+ config = PageRankConfig(**ckpt["config"])
626
+ model = IterativePageRankModel(config)
627
+ model.load_state_dict(ckpt["model_state_dict"])
628
+ model.eval()
629
+
630
+ adj, targets, meta = generate_batch(1, config, edge_prob=0.1,
631
+ graph_weights=(0.0, 0.0, 1.0), device="cpu")
632
+ with torch.no_grad():
633
+ all_prs = model(adj, n_iters=64)
634
+ print(f"Predicted: {{all_prs[-1][0].topk(5)}}")
635
+ print(f"True: {{targets[0].topk(5)}}")
636
+ ```
637
+ """
638
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False) as f:
639
+ f.write(card)
640
+ card_path = f.name
641
+ api.upload_file(path_or_fileobj=card_path, path_in_repo="README.md", repo_id=args.upload_hf)
642
+ os.unlink(card_path)
643
+
644
+ print(f"Uploaded to https://huggingface.co/{args.upload_hf}")
645
+
646
+
647
+ # ---------------------------------------------------------------------------
648
+ # Entry point
649
+ # ---------------------------------------------------------------------------
650
+
651
+ def main():
652
+ parser = argparse.ArgumentParser(description="Iterative PageRank model")
653
+ parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
654
+ parser.add_argument("--steps", type=int, default=50000)
655
+ parser.add_argument("--batch", type=int, default=2048)
656
+ parser.add_argument("--eval-batch", type=int, default=1024)
657
+ parser.add_argument("--lr", type=float, default=2e-3)
658
+ parser.add_argument("--warmup", type=int, default=1400)
659
+ parser.add_argument("--log-interval", type=int, default=100)
660
+ parser.add_argument("--eval-interval", type=int, default=5000)
661
+ parser.add_argument("--compile", action="store_true")
662
+ parser.add_argument("--save-path", type=str, default=None)
663
+ parser.add_argument("--upload-hf", type=str, default=None)
664
+
665
+ parser.add_argument("--d-model", type=int, default=128)
666
+ parser.add_argument("--n-layers", type=int, default=4)
667
+ parser.add_argument("--n-heads", type=int, default=4)
668
+ parser.add_argument("--d-ff", type=int, default=512)
669
+ parser.add_argument("--train-iters", type=int, default=16)
670
+ parser.add_argument("--n-nodes", type=int, default=64)
671
+ parser.add_argument("--damping", type=float, default=0.85)
672
+ parser.add_argument("--dropout", type=float, default=0.1)
673
+
674
+ args = parser.parse_args()
675
+
676
+ config = PageRankConfig(
677
+ n_nodes=args.n_nodes,
678
+ d_model=args.d_model,
679
+ n_heads=args.n_heads,
680
+ n_layers=args.n_layers,
681
+ d_ff=args.d_ff,
682
+ dropout=args.dropout,
683
+ train_iters=args.train_iters,
684
+ damping=args.damping,
685
+ )
686
+
687
+ train(config, args)
688
+
689
+
690
+ if __name__ == "__main__":
691
+ main()