| |
| |
|
|
| |
|
|
|
|
| |
|
|
| import torch |
| from torch import nn |
| from matplotlib import pyplot as plt |
| import numpy as np |
| import os |
| from sklearn.datasets import make_swiss_roll |
| from sklearn.neighbors import kneighbors_graph |
| import networkx as nx |
| from sklearn.linear_model import LogisticRegression |
| from sklearn.metrics import accuracy_score |
|
|
|
|
| import os |
| import sys |
| import argparse |
| import torch |
| import numpy as np |
| import matplotlib.pyplot as plt |
| from torch.optim import AdamW |
|
|
|
|
| from models.joint_model import EndToEndLapPEICLTransformer |
| from models.transformer_rbf import Transformer_RBF |
| from models.transformer_e import Transformer_E |
| from models.icl import InContextClassifier |
| from data.swiss_roll import generate_small_swiss_roll_in_3d, cache_or_compute_test_data |
| from utils.training import TrainingLogger, train_logistic_regression, train_rkhs_classifier |
| from utils.plot import plot_multiple_losses, plot_multiple_accuracies |
| from train_lap import train_transformer_to_predict_laplacian |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| from config.default_config import DATA_CONFIG, LAP_MODEL_CONFIG, PE_MODEL_CONFIG, ICL_MODEL_CONFIG |
| from config.default_config import END_TO_END_CONFIG, MODEL_PATHS, RESULTS_PATHS, TEST_MODES, EVAL_CONFIG |
|
|
| torch.set_printoptions(precision=2, linewidth=160) |
|
|
| |
|
|
|
|
| |
|
|
|
|
| |
|
|
| if __name__ == "__main__": |
| |
| n_samples = 100 |
| batch_size = 750 |
| scale_rbf = 10 |
| k_nn = 10 |
| seed = 42 |
| n_layer = 1 |
| n_head = 1 |
| var = 0.1 |
| lr = 0.0005 |
| max_iters = 1 |
| stride = 10 |
| clip_r = 1.0 |
| k_feat = 4 |
| n_nodes = n_samples |
| |
| |
| model_path = "transformer_laplacian_model.pt" |
| |
| |
| if os.path.exists(model_path): |
| print(f">>> Loading existing model from {model_path}...") |
| model = Transformer_RBF(n_layer, n_head, n=n_samples, d=n_samples, k=k_feat, var=var).to(device) |
| |
| model.load_state_dict(torch.load(model_path)) |
| model = model.to(device) |
| |
| losses = [] |
| else: |
| print(">>> Training the Transformer to predict the Laplacian (using only point coords)...") |
| model, losses = train_transformer_to_predict_laplacian( |
| n_samples=n_samples, |
| batch_size=batch_size, |
| scale_rbf=scale_rbf, |
| k_nn=k_nn, |
| seed=seed, |
| n_layer=n_layer, |
| n_head=n_head, |
| var=var, |
| lr=lr, |
| max_iters=max_iters, |
| stride=stride, |
| clip_r=clip_r, |
| k_feat=k_feat |
| ) |
| |
| |
| torch.save(model.state_dict(), model_path) |
| print(f">>> Model saved to {model_path}") |
| |
| |
| plt.figure() |
| plt.plot(losses, label='Train Loss (Frobenius norm error)') |
| plt.xlabel('Iteration') |
| plt.ylabel('Loss') |
| plt.legend() |
| plt.title('Transformer Laplacian-Prediction Loss (Only Points as Input)') |
| plt.show() |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
|
|
| |
| |
|
|
| import torch.nn.functional as F |
| |
| |
|
|
| |
| device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") |
| torch.cuda.empty_cache() |
|
|
|
|
| import torch |
| from torch import nn |
| from matplotlib import pyplot as plt |
| import numpy as np |
| import os |
| from sklearn.datasets import make_swiss_roll |
| from sklearn.neighbors import kneighbors_graph |
| import networkx as nx |
| from sklearn.linear_model import LogisticRegression |
| from sklearn.metrics import accuracy_score |
|
|
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
|
|
|
|
| torch.set_printoptions(precision=2, linewidth=160) |
|
|
| |
|
|
| def adjacency_to_incidence(A, n_nodes, max_edges): |
| """ |
| Converts an adjacency matrix A to an incidence matrix B. |
| Pads the incidence matrix to have max_edges columns. |
| """ |
| edges = [] |
| for i in range(n_nodes): |
| for j in range(i+1, n_nodes): |
| if A[i, j] != 0: |
| edges.append((i, j)) |
| n_edges = len(edges) |
| B = torch.zeros(n_nodes, max_edges) |
| for idx, (i, j) in enumerate(edges): |
| B[i, idx] = 1 |
| B[j, idx] = -1 |
| return B, n_edges |
|
|
| def get_laplacian(B): |
| |
| return torch.einsum('ijk,ilk->ijl', B, B) |
|
|
| def L_ev_loss(model, Z, inds=None, k=-1, visualize=False, t=None): |
| """ |
| Loss function with visualization option |
| Args: |
| visualize: 是否可视化归一化过程 |
| t: 当前训练迭代次数(用于图标题) |
| """ |
| n = Z.shape[1] |
| d = Z.shape[2] - n - n |
| assert inds is not None |
|
|
| |
| lap = Z[:, :, :n] |
| eigenvals, target = torch.linalg.eigh(lap) |
| target = target.real |
| |
| output = model(Z) |
| predicted_ev = output[:, :, -k:] |
| if inds is not None: |
| predicted_ev = predicted_ev[:, :, inds] |
| target = target[:, :, inds] |
|
|
| |
| predicted_unnorm = predicted_ev.clone() |
| target_unnorm = target.clone() |
|
|
| |
| predicted_ev = predicted_ev / predicted_ev.norm(p=2, dim=1)[:, None, :] |
| target = target / target.norm(p=2, dim=1)[:, None, :] |
|
|
| if visualize: |
| plt.figure(figsize=(15, 3*len(inds))) |
| for idx, ev_idx in enumerate(inds): |
| |
| plt.subplot(len(inds), 2, 2*idx + 1) |
| plt.plot(predicted_unnorm[0, :, idx].cpu().detach(), 'b-', label='Before') |
| plt.plot(predicted_ev[0, :, idx].cpu().detach(), 'r-', label='After') |
| plt.title(f'Predicted EV{ev_idx+1} Normalization\nIter {t if t is not None else ""}') |
| plt.grid(True) |
| plt.legend() |
|
|
| |
| print(f"\nPredicted EV{ev_idx+1} statistics:") |
| print("Before normalization:") |
| print(f" Range: [{predicted_unnorm[0,:,idx].min():.3f}, {predicted_unnorm[0,:,idx].max():.3f}]") |
| print(f" Mean: {predicted_unnorm[0,:,idx].mean():.3f}") |
| print(f" Norm: {predicted_unnorm[0,:,idx].norm():.3f}") |
| print("After normalization:") |
| print(f" Range: [{predicted_ev[0,:,idx].min():.3f}, {predicted_ev[0,:,idx].max():.3f}]") |
| print(f" Mean: {predicted_ev[0,:,idx].mean():.3f}") |
| print(f" Norm: {predicted_ev[0,:,idx].norm():.3f}") |
|
|
| |
| plt.subplot(len(inds), 2, 2*idx + 2) |
| plt.plot(target_unnorm[0, :, idx].cpu().detach(), 'b-', label='Before') |
| plt.plot(target[0, :, idx].cpu().detach(), 'r-', label='After') |
| plt.title(f'Target EV{ev_idx+1} Normalization') |
| plt.grid(True) |
| plt.legend() |
|
|
| plt.tight_layout() |
| plt.show() |
|
|
| |
| loss_pos = ((predicted_ev - target).norm(p=2, dim=[1]) ** 2) |
| loss_neg = ((-predicted_ev - target).norm(p=2, dim=[1]) ** 2) |
| loss = torch.minimum(loss_pos, loss_neg).sum(dim=1).mean() |
| |
| return loss |
|
|
| def clip_and_step(allparam, optimizer, clip_r=None): |
| grad_all = allparam.grad |
| norm_p = grad_all.norm().item() |
| if norm_p > clip_r: |
| grad_all.mul_(clip_r / norm_p) |
| fraction = clip_r / norm_p |
| else: |
| fraction = 1.0 |
| optimizer.step() |
| return fraction |
| def gen_random_data(n_batch, n_samples, type='circles'): |
| if type=='circles': |
| n0 = int(n_samples/5) |
| r0 = 0.1 |
| r1 = 0.6 |
|
|
| t0 = torch.rand(size = (n_batch,2*n0)) |
| t1 = torch.rand(size = (n_batch,n0)) |
| t2 = torch.rand(size = (n_batch,2*n0)) |
| |
| t0, _ = torch.sort(t0) |
| t1, _ = torch.sort(t1) |
| t2, _ = torch.sort(t2) |
|
|
| t = torch.cat((t0,t1+1,t2+2),dim=1) |
| |
|
|
| x0 = r0*torch.cos(t0*2*torch.pi) |
| y0 = r0*torch.sin(t0*2*torch.pi) |
|
|
| x1 = torch.zeros_like(t1) |
| y1 = r0 + t1 * (r1-r0) |
|
|
| x2 = r1 * torch.cos(t2*2*torch.pi) |
| y2 = r1 * torch.sin(t2*2*torch.pi) |
|
|
| xs = torch.cat((x0,x1,x2),dim=1) |
| ys = torch.cat((y0,y1,y2),dim=1) |
|
|
| data = torch.cat((xs[:,:,None],ys[:,:,None]),dim=2) |
|
|
| if type=='swissroll': |
| n0 = int(n_samples) |
|
|
| t0 = torch.rand(size = (n_batch,n0)) |
| t0, _ = torch.sort(t0) |
| t=t0 |
|
|
| x0 = t0**2*torch.cos(t0*4*torch.pi) |
| y0 = t0**2*torch.sin(t0*4*torch.pi) |
|
|
| data = torch.cat((x0[:,:,None],y0[:,:,None]),dim=2) |
|
|
| if type=='line': |
| n0 = int(n_samples) |
|
|
| t0 = torch.rand(size = (n_batch,n0)) |
| t0, _ = torch.sort(t0) |
| t=t0 |
|
|
| x0 = torch.zeros_like(t0) |
| y0 = t0 |
|
|
| data = torch.cat((x0[:,:,None],y0[:,:,None]),dim=2) |
|
|
| return t, data |
|
|
| def random_data_to_adjacency(data, scale = 4): |
| |
| B, n, d = data.shape |
| |
| norms = torch.norm(data, p=2, dim=2)**2 |
|
|
| |
| euclidean_distances = norms[:,:,None] + norms[:,None,:] - 2 * torch.einsum('Bni,Bmi->Bnm',(data,data)) |
| inv_rbf_distances = torch.exp(-scale * euclidean_distances) |
|
|
| |
| |
|
|
| return inv_rbf_distances |
|
|
| def smallest_k_indices(inv_distance_matrix, k): |
| """ |
| Find the (i, j) indices for the smallest k distances in a symmetric distance matrix. |
| |
| Parameters: |
| distance_matrix (torch.Tensor): An (n x n) symmetric distance matrix. |
| k (int): The number of smallest distances to find. |
| |
| Returns: |
| torch.Tensor: A (k x 2) tensor of indices (i, j) for the smallest k distances. |
| """ |
| |
| n = inv_distance_matrix.size(0) |
| inv_distance_matrix = inv_distance_matrix.clone() |
| inv_distance_matrix.fill_diagonal_(float(-1)) |
| |
| |
| |
| |
| |
| indices = torch.topk(inv_distance_matrix, k, dim=-1).indices |
|
|
| return indices |
|
|
| def visualize_adjacency_matrix(adjacency_matrix, title="Adjacency Matrix"): |
| """ |
| Visualize an adjacency matrix as a heatmap. |
| |
| Parameters: |
| adjacency_matrix (torch.Tensor): A 2D tensor representing the adjacency matrix. |
| title (str): Title of the plot. |
| """ |
| plt.imshow(adjacency_matrix, cmap='viridis', interpolation='nearest') |
| plt.colorbar(label="Edge Weight") |
| plt.title(title) |
| plt.xlabel("Node Index") |
| plt.ylabel("Node Index") |
| plt.grid(False) |
| plt.show() |
|
|
| import torch |
| import numpy as np |
| import matplotlib.pyplot as plt |
| import networkx as nx |
| from mpl_toolkits.mplot3d import Axes3D |
| k_feat = 4 |
|
|
| def generate_weighted_swiss_roll_graph(n_samples=100, scale=10, k=6, seed=5, return_extra=False, model=None, use_predicted_laplacian=False, k_feat = 4): |
| """ |
| Generates a transformed Swiss Roll dataset, constructs a weighted adjacency matrix based on inverse distances, |
| computes the normalized Laplacian (real or predicted), and optionally plots and returns additional data for visualization. |
| |
| Parameters: |
| n_samples (int): Number of samples in the Swiss Roll. |
| scale (float): Scale parameter for the RBF kernel in adjacency. |
| k (int): Number of nearest neighbors for graph construction. |
| seed (int): Random seed for reproducibility. |
| return_extra (bool): If True, also return t and a_translated and plot the data. |
| Default: False (returns only adj, L_test, target_eigenvals, target_ev). |
| model (nn.Module): The trained Transformer model to predict the Laplacian. Only used if use_predicted_laplacian=True. |
| use_predicted_laplacian (bool): If True, the Laplacian will be predicted by the given model; otherwise, the real Laplacian is computed. |
| Default: False. |
| |
| Returns: |
| If return_extra=False: |
| adj (torch.Tensor): Weighted adjacency matrix (shape: [n_samples, n_samples]). |
| L_test (torch.Tensor): Normalized Laplacian matrix (shape: [n_samples, n_samples]). |
| target_eigenvals (torch.Tensor): Eigenvalues of the Laplacian (shape: [n_samples]). |
| target_ev (numpy.ndarray): Eigenvectors of the Laplacian (shape: [n_samples, n_samples]). |
| |
| If return_extra=True: |
| t (torch.Tensor): Parameter array for the Swiss Roll (shape: [1, n_samples]). |
| a_translated (torch.Tensor): The transformed coordinates of the Swiss Roll (shape: [1, n_samples, 3]). |
| adj (torch.Tensor) |
| L_test (torch.Tensor) |
| target_eigenvals (torch.Tensor) |
| target_ev (numpy.ndarray) |
| """ |
| |
| torch.manual_seed(seed) |
| np.random.seed(seed) |
|
|
| |
| t, a = gen_random_data(1, n_samples, type='swissroll') |
|
|
| |
| z_coords = torch.ones((1, n_samples, 1)) |
| a_translated = torch.cat([a, z_coords], dim=2) |
|
|
| |
| scale_factor = np.random.uniform(0.02, .1) |
| a_translated[:, :, :2] = a_translated[:, :, :2] * scale_factor |
|
|
| |
| theta = np.random.uniform(0, 2 * np.pi) |
| rotation_matrix = torch.tensor([[np.cos(theta), -np.sin(theta), 0], |
| [np.sin(theta), np.cos(theta), 0], |
| [0, 0, 1]], dtype=torch.float32) |
| a_rotated = torch.matmul(a_translated, rotation_matrix) |
|
|
| |
| translation_x = np.random.uniform(-1, 1) |
| translation_y = np.random.uniform(-1, 1) |
| translation_z = 0 |
| translation = torch.tensor([[[translation_x, translation_y, translation_z]]], dtype=torch.float32) |
| a_translated = a_rotated + translation |
| |
| |
| inv_distances = random_data_to_adjacency(a_translated[:, :, :2], scale=scale) |
| |
| |
| knn_indices = smallest_k_indices(inv_distances[0, :, :], k) |
| adj = torch.zeros((n_samples, n_samples), dtype=torch.float32) |
| for i in range(knn_indices.shape[0]): |
| for j in knn_indices[i, :]: |
| if j < n_samples: |
| |
| weight = inv_distances[0, i, j].item() |
| adj[i, j] = weight |
| adj[j, i] = weight |
| |
| |
| if use_predicted_laplacian: |
| |
| Z_input_for_model = torch.zeros(1, n_samples, 2 * n_samples + k_feat, device=device) |
| for row_idx in range(n_samples): |
| Z_input_for_model[0, row_idx, 0:3] = a_translated[0, row_idx, :] |
|
|
| |
| model.eval() |
| with torch.no_grad(): |
| predicted_laplacian_rows = model(Z_input_for_model)[:, :, n_samples:2*n_samples] |
| L_test = predicted_laplacian_rows[0].to(device) |
| else: |
| |
| degree = torch.sum(adj, dim=1) |
| degree[degree == 0] = 1.0 |
| D_inv_sqrt = torch.diag(degree.pow(-0.5)) |
| L_test = torch.eye(adj.size(0)) - D_inv_sqrt @ adj @ D_inv_sqrt |
|
|
| |
| target_eigenvals, target_ev_torch = torch.linalg.eigh(L_test) |
| target_ev = target_ev_torch.cpu().numpy() |
|
|
| if return_extra: |
| |
| data = a_translated[0].cpu().numpy() |
|
|
| |
| labels = np.where(t[0].cpu().numpy() < np.median(t[0].cpu().numpy()), 1, -1) |
|
|
| |
| fig = plt.figure(figsize=(8, 6)) |
| ax = fig.add_subplot(111, projection='3d') |
| scatter = ax.scatter(data[:, 0], data[:, 1], data[:, 2], c=labels, cmap=plt.cm.bwr, s=30) |
| ax.set_xlabel('x-axis') |
| ax.set_ylabel('y-axis') |
| ax.set_zlabel('z-axis') |
| ax.set_title('Labeled Swiss Roll Data (3D Projection)') |
| legend1 = ax.legend(*scatter.legend_elements(), title="Classes") |
| ax.add_artist(legend1) |
| plt.show() |
|
|
| |
| |
| |
| laplacian_np = L_test.cpu().numpy() |
|
|
| plt.figure(figsize=(8, 6)) |
| plt.imshow(laplacian_np, cmap='viridis', aspect='auto') |
| plt.colorbar(label="Laplacian Value") |
|
|
| if use_predicted_laplacian: |
| plt.title(f"Predicted Laplacian Heatmap (k={k})") |
| else: |
| plt.title(f"Real Laplacian Heatmap (k={k})") |
|
|
| plt.xlabel("Node Index") |
| plt.ylabel("Node Index") |
| plt.show() |
|
|
| return t, a_translated, adj, L_test, target_eigenvals, target_ev |
| else: |
| return adj, L_test, target_eigenvals, target_ev |
|
|
|
|
| |
|
|
| k = 10 |
|
|
| def generate_in_context_swiss_roll_graphs(Z, batch_size, n_samples, k_values, max_edges, noise=0.0, base_seed=0, k_feat=4, label_percent=100, context_size=0, model=None, use_exact_ev=False): |
| """ |
| Now we store: |
| - Normalized Laplacian in Z[:, :, :n] |
| - Adjacency in Z[:, :, n:2n] |
| - Eigenvectors in Z[:, :, 2n:] |
| """ |
| assert label_percent > 0 and label_percent <= 100 |
| n_labeled = int(n_samples * label_percent / 100) |
| |
| assert context_size < n_labeled |
| |
| if isinstance(k_values, int): |
| k_values = [k_values] |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| t, data = gen_random_data(batch_size, n_samples, type='swissroll') |
| data = data.to(device) |
| labels = torch.from_numpy(np.where(t.cpu().numpy() < np.median(t.cpu().numpy()), 1, 0)).to(device) |
| |
| |
| labeled_indices = torch.stack([torch.randperm(n_samples)[:n_labeled] for _ in range(batch_size)]).to(device) |
| labeled_data = labels.gather(-1, labeled_indices) |
| |
| |
| context_indices = torch.stack([torch.randperm(n_labeled)[:context_size] for _ in range(batch_size)]).to(device) |
| |
| all_indices = torch.arange(n_labeled).expand(batch_size, n_labeled).to(device) |
|
|
| |
| mask = torch.zeros(batch_size, n_labeled, dtype=torch.bool).to(device) |
| mask.scatter_(1, context_indices, True) |
| |
| |
| query_indices = all_indices[~mask].view(batch_size, n_labeled - context_size).to(device) |
| |
| return None , labeled_data, labeled_indices, context_indices, query_indices |
|
|
|
|
| |
|
|
|
|
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
| import numpy as np |
|
|
| import os |
| import torch |
| import numpy as np |
|
|
| def get_or_generate_data(epoch, batch_size, n_samples, scale_rbf, k_nn, device, label_percent, context_size, k_feat, data_dir="./cached_data",force=False): |
| """ |
| 检查是否有缓存数据,如果没有则生成新数据 |
| |
| Args: |
| epoch: 当前训练epoch |
| batch_size: 批次大小 |
| n_samples: 每个样本中的点数 |
| scale_rbf: RBF核函数的缩放参数 |
| k_nn: KNN参数 |
| device: 计算设备 |
| label_percent: 标签百分比 |
| context_size: 上下文大小 |
| k_feat: 特征维度 |
| data_dir: 数据缓存目录 |
| |
| Returns: |
| 所有数据张量和索引 |
| """ |
| |
| os.makedirs(data_dir, exist_ok=True) |
| |
| |
| file_path = os.path.join(data_dir, f"data_epoch_{epoch}.pt") |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| print(f"Generating new data for epoch {epoch}...") |
| |
| |
| raw_data_batch = [] |
| real_lap_batch = [] |
| labels_batch = [] |
| adjacency_batch = [] |
| |
| for b in range(batch_size): |
| L_true, xyz, labels_np, adjacency = generate_small_swiss_roll_in_3d( |
| n_samples=n_samples, |
| scale_rbf=scale_rbf, |
| k_nn=k_nn, |
| seed=epoch*batch_size+b, |
| device=device |
| ) |
| raw_data_batch.append(torch.from_numpy(xyz).float()) |
| real_lap_batch.append(L_true) |
| labels_batch.append(torch.from_numpy(labels_np)) |
| adjacency_batch.append(torch.from_numpy(adjacency).float()) |
| |
| raw_data = torch.stack(raw_data_batch, dim=0).to(device) |
| real_lap = torch.stack(real_lap_batch, dim=0).to(device) |
| labels_tensor = torch.stack(labels_batch, dim=0).to(device) |
| real_adj = torch.stack(adjacency_batch, dim=0).to(device) |
| |
| |
| n_labeled = int(n_samples * label_percent / 100) |
| labeled_indices = torch.stack([torch.randperm(n_samples)[:n_labeled] for _ in range(batch_size)], dim=0).to(device) |
| context_indices = torch.stack([torch.randperm(n_labeled)[:context_size] for _ in range(batch_size)], dim=0).to(device) |
| all_indices = torch.arange(n_labeled).expand(batch_size, n_labeled).to(device) |
| mask = torch.zeros(batch_size, n_labeled, dtype=torch.bool).to(device) |
| |
| for i in range(batch_size): |
| mask[i].scatter_(0, context_indices[i], True) |
| |
| |
| query_indices = all_indices[~mask].view(batch_size, n_labeled - context_size).to(device) |
| |
| |
| real_eigs = [] |
| for b in range(batch_size): |
| _, vecs = torch.linalg.eigh(real_lap[b]) |
| real_eigs.append(vecs[:, :k_feat]) |
| real_ev = torch.stack(real_eigs, dim=0) |
| |
|
|
| |
| Z = torch.zeros([batch_size, n_samples, 2*n_samples + k_feat], device=device) |
| max_edges = n_samples * 6 |
| import pdb |
| |
| |
| _, labels_tensor, labeled_indices, context_indices, query_indices = generate_in_context_swiss_roll_graphs( |
| Z=Z, |
| batch_size=batch_size, |
| n_samples=n_samples, |
| k_values=6, |
| max_edges=max_edges, |
| base_seed=epoch*batch_size, |
| k_feat=k_feat, |
| label_percent=label_percent, |
| context_size=context_size, |
| model=None, |
| use_exact_ev=True |
| ) |
| |
| |
| Z = torch.zeros([batch_size, n_samples, 2*n_samples + k_feat], device=device) |
| max_edges = n_samples * 6 |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| cached_data = { |
| 'raw_data': raw_data, |
| 'real_lap': real_lap, |
| 'labels_tensor': labels_tensor, |
| 'real_adj': real_adj, |
| 'labeled_indices': labeled_indices, |
| 'context_indices': context_indices, |
| 'query_indices': query_indices, |
| 'real_ev': real_ev |
| } |
| |
| torch.save(cached_data, file_path) |
| print(f"Saved data to {file_path}") |
| |
| return raw_data, real_lap, labels_tensor, real_adj, labeled_indices, context_indices, query_indices, real_ev |
|
|
|
|
| |
| |
| |
| def train_end_to_end_lap_pe_icl( |
| args=None, |
| n_samples=100, |
| batch_size=550, |
| raw_dim=3, |
| k_feat=4, |
| |
| lap_n_layer=4, lap_n_head=2, lap_var=0.1, |
| |
| pe_n_layer=6, pe_n_head=4, pe_var=0.1, |
| |
| n_layer_icl=2, kernel='linear', label_percent=100, context_size=99, |
| |
| lr=0.001, n_epochs=201, |
| |
| scale_rbf=10, |
| |
| lap_weight=1.0, pe_weight=1.0, icl_weight=1.0, |
| test_mode=0, |
| |
| data_cache_dir=DATA_CONFIG['data_cache_dir'] |
| ): |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| |
| |
| model = EndToEndLapPEICLTransformer( |
| n_samples=n_samples, |
| raw_dim=raw_dim, |
| lap_n_layer=lap_n_layer, lap_n_head=lap_n_head, lap_var=lap_var, |
| pe_n_layer=pe_n_layer, pe_n_head=pe_n_head, pe_var=pe_var, |
| n_layer_icl=n_layer_icl, kernel=kernel, n_categories=2, pe_dim=k_feat, |
| lap_weight=lap_weight, pe_weight=pe_weight, icl_weight=icl_weight |
| ).to(device) |
| |
| optimizer = torch.optim.AdamW(model.parameters(), lr=lr, betas=(0.9, 0.99), weight_decay=0.001) |
| |
| |
| losses_over_time = [] |
| lap_losses_log = [] |
| pe_losses_log = [] |
| icl_losses_log = [] |
| icl_acc_log = [] |
| from tqdm import tqdm |
| |
| stride = n_epochs // 1000 |
| start_epoch = args.slurm_id * stride |
| end_epoch = min(args.slurm_id * stride + stride, n_epochs) |
| for epoch in tqdm(range(start_epoch,end_epoch)): |
| if epoch % 1 == 0: |
| |
| raw_data, real_lap, labels_tensor, real_adj, labeled_indices, context_indices, query_indices, real_ev = get_or_generate_data( |
| epoch=epoch, |
| batch_size=batch_size, |
| n_samples=n_samples, |
| scale_rbf=scale_rbf, |
| k_nn=6, |
| device=device, |
| label_percent=label_percent, |
| context_size=context_size, |
| k_feat=k_feat, |
| data_dir=data_cache_dir |
| ) |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| return model, { |
| 'total_loss': losses_over_time, |
| 'lap_loss': lap_losses_log, |
| 'pe_loss': pe_losses_log, |
| 'icl_loss': icl_losses_log, |
| 'icl_acc': icl_acc_log |
| } |
|
|
|
|
| def test_end_to_end_lap_pe_icl( |
| model, |
| n_samples=100, |
| batch_size=550, |
| raw_dim=3, |
| k_feat=4, |
| |
| lap_n_layer=4, lap_n_head=2, lap_var=0.1, |
| |
| pe_n_layer=6, pe_n_head=4, pe_var=0.1, |
| |
| n_layer_icl=2, kernel='linear', label_percent=100, context_size=99, |
| |
| lr=0.001, n_epochs=201, |
| |
| scale_rbf=10, |
| |
| lap_weight=1.0, pe_weight=1.0, icl_weight=1.0, |
| test_mode=0, |
| ): |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| |
| |
| |
| losses_over_time = [] |
| lap_losses_log = [] |
| pe_losses_log = [] |
| icl_losses_log = [] |
| icl_acc_log = [] |
| |
| |
| lr_accs = [] |
| rkhs_accs = [] |
| context_sizes_list = [99] |
| |
| for context_size in context_sizes_list: |
| |
| raw_data_batch = [] |
| real_lap_batch = [] |
| labels_batch = [] |
| adjacency_batch = [] |
| for b in range(batch_size): |
| L_true, xyz, labels_np, adjacency = generate_small_swiss_roll_in_3d( |
| n_samples=n_samples, |
| scale_rbf=scale_rbf, |
| k_nn=6, |
| seed=epoch*batch_size+b, |
| device=device |
| ) |
| raw_data_batch.append(torch.from_numpy(xyz).float()) |
| real_lap_batch.append(L_true) |
| labels_batch.append(torch.from_numpy(labels_np)) |
| adjacency_batch.append(torch.from_numpy(adjacency).float()) |
| raw_data = torch.stack(raw_data_batch, dim=0).to(device) |
| real_lap = torch.stack(real_lap_batch, dim=0).to(device) |
| labels_tensor = torch.stack(labels_batch, dim=0).to(device) |
| real_adj = torch.stack(adjacency_batch, dim=0).to(device) |
| |
| |
| n_labeled = int(n_samples * label_percent / 100) |
| labeled_indices = torch.stack([torch.randperm(n_samples)[:n_labeled] for _ in range(batch_size)], dim=0).to(device) |
| context_indices = torch.stack([torch.randperm(n_labeled)[:context_size] for _ in range(batch_size)], dim=0).to(device) |
| all_indices = torch.arange(n_labeled).expand(batch_size, n_labeled).to(device) |
| mask = torch.zeros(batch_size, n_labeled, dtype=torch.bool).to(device) |
| for i in range(batch_size): |
| mask[i].scatter_(0, context_indices[i], True) |
| query_indices = all_indices[~mask].view(batch_size, n_labeled - context_size).to(device) |
| |
| |
| real_eigs = [] |
| for b in range(batch_size): |
| _, vecs = torch.linalg.eigh(real_lap[b]) |
| real_eigs.append(vecs[:, :k_feat]) |
| real_ev = torch.stack(real_eigs, dim=0) |
| |
| model.train() |
| total_loss, lap_loss, pe_loss, icl_query_loss, icl_query_acc, Z_lap_out, Z_pe_out = model.test_step( |
| raw_data=raw_data, |
| labels=labels_tensor, |
| labeled_indices=labeled_indices, |
| context_indices=context_indices, |
| query_indices=query_indices, |
| real_lap=real_lap, |
| real_ev=real_ev, |
| real_adj=real_adj, |
| test_mode=test_mode, |
| ) |
| print(icl_query_acc) |
| |
| |
| |
| |
| |
| |
| batch_size = Z_pe_out.shape[0] |
| |
| rkhs_acc = 0 |
| lr_acc = 0 |
| |
| |
| |
|
|
| from tqdm import tqdm |
| for b in tqdm(range(batch_size)): |
| |
| |
| |
|
|
| train_indice = context_indices[b].detach().cpu() |
| test_indice = query_indices[b].detach().cpu() |
| pred_ev_norm = Z_pe_out[b].detach().cpu() |
| pred_ev_norm = pred_ev_norm / (np.linalg.norm(pred_ev_norm, axis=1, keepdims=True) + 1e-10) |
| |
| |
| labels_test = labels_tensor[b].detach().cpu() |
| |
| X_train = pred_ev_norm[train_indice].float() |
| y_train = labels_test[train_indice].float() |
| X_test = pred_ev_norm[test_indice].float() |
| y_test = labels_test[test_indice].float() |
| |
| |
| |
| |
| lr_acc += train_logistic_regression(X_train, y_train, X_test, y_test, device='cpu') |
| |
| |
| |
| rkhs_acc += train_rkhs_classifier(X_train, y_train, X_test, y_test, device='cpu') |
| print(lr_acc,rkhs_acc) |
| |
| lr_acc = lr_acc / batch_size |
| rkhs_acc = rkhs_acc /batch_size |
| |
| lr_accs.append(lr_acc) |
| rkhs_accs.append(rkhs_acc) |
|
|
| |
| losses_over_time.append(total_loss.item()) |
| lap_losses_log.append(lap_loss.item()) |
| pe_losses_log.append(pe_loss.item()) |
| icl_losses_log.append(icl_query_loss.item()) |
| icl_acc_log.append(icl_query_acc.item()) |
| |
| print(f"Context {context_size}: Total: {total_loss.item():.4f} | Lap: {lap_loss.item():.4f} | " |
| f"PE: {pe_loss.item():.4f} | ICL: {icl_query_loss.item():.4f} | ICL Acc: {icl_query_acc.item():.3f} | " |
| f"LR Acc: {lr_acc:.3f} | RKHS Acc: {rkhs_acc:.3f}") |
|
|
| return model, { |
| 'total_loss': losses_over_time, |
| 'lap_loss': lap_losses_log, |
| 'pe_loss': pe_losses_log, |
| 'icl_loss': icl_losses_log, |
| 'icl_acc': icl_acc_log, |
| 'context_sizes': context_sizes_list, |
| 'lr_accs': lr_accs, |
| 'rkhs_accs': rkhs_accs |
| } |
|
|
|
|
| |
|
|
|
|
| |
|
|
| |
| |
| |
| n_epochs = 101 |
| |
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Train End-to-End Spectral Learning Model") |
| |
| |
| parser.add_argument("--n_samples", type=int, default=DATA_CONFIG["n_samples"], |
| help="Number of samples per graph") |
| parser.add_argument("--batch_size", type=int, default=DATA_CONFIG["batch_size"], |
| help="Number of graphs per batch") |
| parser.add_argument("--scale_rbf", type=float, default=DATA_CONFIG["scale_rbf"], |
| help="Scale parameter for RBF kernel") |
| parser.add_argument("--k_nn", type=int, default=DATA_CONFIG["k_nn"], |
| help="Number of nearest neighbors") |
| parser.add_argument("--seed", type=int, default=DATA_CONFIG["seed"], |
| help="Random seed for training") |
| parser.add_argument("--test_seed", type=int, default=DATA_CONFIG["test_seed"], |
| help="Random seed for testing") |
| parser.add_argument("--raw_dim", type=int, default=DATA_CONFIG["raw_dim"], |
| help="Dimension of raw input data") |
| parser.add_argument("--slurm_id", type=int, default=DATA_CONFIG["raw_dim"], |
| help="Dimension of raw input data") |
|
|
| |
| parser.add_argument("--lap_n_layer", type=int, default=END_TO_END_CONFIG["n_layer_lap"], |
| help="Number of Laplacian transformer layers") |
| parser.add_argument("--lap_n_head", type=int, default=END_TO_END_CONFIG["n_head_lap"], |
| help="Number of Laplacian transformer attention heads") |
| parser.add_argument("--lap_var", type=float, default=LAP_MODEL_CONFIG["var"], |
| help="Variance for Laplacian transformer initialization") |
| |
| |
| parser.add_argument("--pe_n_layer", type=int, default=END_TO_END_CONFIG["n_layer_pe"], |
| help="Number of PE transformer layers") |
| parser.add_argument("--pe_n_head", type=int, default=END_TO_END_CONFIG["n_head_pe"], |
| help="Number of PE transformer attention heads") |
| parser.add_argument("--pe_var", type=float, default=PE_MODEL_CONFIG["var"], |
| help="Variance for PE transformer initialization") |
| parser.add_argument("--k_feat", type=int, default=PE_MODEL_CONFIG["k_feat"], |
| help="Number of eigenvector features") |
| |
| |
| parser.add_argument("--n_layer_icl", type=int, default=END_TO_END_CONFIG["n_layer_icl"], |
| help="Number of ICL transformer layers") |
| parser.add_argument("--kernel", type=str, default=END_TO_END_CONFIG["kernel"], |
| choices=["linear", "rbf", "exp", "softmax"], |
| help="Kernel type for ICL") |
| parser.add_argument("--label_percent", type=int, default=END_TO_END_CONFIG["label_percent"], |
| help="Percentage of labeled nodes") |
| parser.add_argument("--context_size", type=int, default=END_TO_END_CONFIG["context_size"], |
| help="Number of context nodes") |
| |
| |
| parser.add_argument("--lr", type=float, default=END_TO_END_CONFIG["lr"], |
| help="Learning rate") |
| parser.add_argument("--n_epochs", type=int, default=END_TO_END_CONFIG["max_iters"], |
| help="Number of training epochs") |
| |
| |
| parser.add_argument("--lap_weight", type=float, default=END_TO_END_CONFIG["lap_weight"], |
| help="Weight for Laplacian loss") |
| parser.add_argument("--pe_weight", type=float, default=END_TO_END_CONFIG["pe_weight"], |
| help="Weight for PE loss") |
| parser.add_argument("--icl_weight", type=float, default=END_TO_END_CONFIG["icl_weight"], |
| help="Weight for ICL loss") |
| |
| |
| parser.add_argument("--test_mode", type=int, default=0, |
| help="Test mode (see config.TEST_MODES for details)") |
| |
| |
| parser.add_argument("--model_path", type=str, default=MODEL_PATHS["end_to_end_model"], |
| help="Path to save/load the model") |
| parser.add_argument("--pretrain_model_path", type=str, default=MODEL_PATHS["end_to_end_model"], |
| help="Path to save/load the model") |
| parser.add_argument("--log_dir", type=str, default=RESULTS_PATHS["log_dir"], |
| help="Directory to save logs") |
| parser.add_argument("--figure_dir", type=str, default=RESULTS_PATHS["figure_dir"], |
| help="Directory to save figures") |
| parser.add_argument("--cache_dir", type=str, default=RESULTS_PATHS["cache_dir"], |
| help="Directory to cache test data") |
| |
|
|
| parser.add_argument("--load_pretrain_model", type=int, default=-1, |
| help="Number of Laplacian transformer layers") |
| |
| parser.add_argument("--load_model", action="store_true", help="Load saved model instead of training") |
| parser.add_argument("--skip_test", action="store_true", help="Skip testing phase") |
| parser.add_argument("--skip_plot", action="store_true", help="Skip plotting results") |
| |
| args = parser.parse_args() |
| n_samples = 100 |
| batch_size = 450 |
| scale_rbf = 10 |
| n_epochs = args.n_epochs |
| raw_dim = 3 |
| k_feat = 4 |
|
|
| test_seed = DATA_CONFIG["test_seed"] |
| nn = DATA_CONFIG["k_nn"] |
| cache_dir = RESULTS_PATHS["cache_dir"] |
|
|
| test_mode = args.test_mode |
| lap_weight = args.lap_weight |
| pe_weight = args.pe_weight |
| icl_weight = args.icl_weight |
| label_percent = args.label_percent |
| context_size = args.context_size |
| save_path = args.model_path + '_'+str(test_mode)+ '_' +str(lap_weight)+ '_' +str(pe_weight)+ '_' +str(icl_weight)+ '_' +str(n_epochs) + '_' +str('finetune') |
| skip_plot=None |
| figure_dir = RESULTS_PATHS["figure_dir"] |
| load_model = args.load_model |
| load_pretrain_model = args.load_pretrain_model |
|
|
| print(args) |
| |
| if load_model and os.path.exists(save_path+ "_full.pth"): |
| print(f"Loading model from {save_path}") |
| model = EndToEndLapPEICLTransformer( |
| n_samples=n_samples, |
| raw_dim=raw_dim, |
| lap_n_layer=4, lap_n_head=2, lap_var=0.1, |
| pe_n_layer=6, pe_n_head=4, pe_var=0.1, |
| n_layer_icl=2, kernel='linear',n_categories=2, pe_dim=4, |
| lap_weight=1.0, pe_weight=1.0, icl_weight=icl_weight |
| ) |
| model.load_model(save_path, map_location=device) |
| else: |
| if load_pretrain_model>=0: |
| print(f"Loading pretrain model") |
| model = EndToEndLapPEICLTransformer( |
| n_samples=n_samples, |
| raw_dim=raw_dim, |
| lap_n_layer=4, lap_n_head=2, lap_var=0.1, |
| pe_n_layer=6, pe_n_head=4, pe_var=0.1, |
| n_layer_icl=2, kernel='linear',n_categories=2, pe_dim=4, |
| lap_weight=1.0, pe_weight=1.0, icl_weight=icl_weight |
| ) |
| if (load_pretrain_model<=5): |
| test_mode = load_pretrain_model |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_model(save_path, map_location=device) |
| elif (load_pretrain_model==6): |
| test_mode = 1 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_lap_model(save_path, map_location=device) |
| test_mode = 2 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_pe_model(save_path, map_location=device) |
| test_mode = 3 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_icl_tf(save_path, map_location=device) |
| elif (load_pretrain_model==7): |
| test_mode = 2 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_pe_model(save_path, map_location=device) |
| test_mode = 3 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_icl_tf(save_path, map_location=device) |
| elif (load_pretrain_model==8): |
| test_mode = 1 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_lap_model(save_path, map_location=device) |
| test_mode = 3 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_icl_tf(save_path, map_location=device) |
| elif (load_pretrain_model==9): |
| test_mode = 1 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_lap_model(save_path, map_location=device) |
| test_mode = 2 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_pe_model(save_path, map_location=device) |
| elif (load_pretrain_model==10): |
| test_mode = 4 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_model(save_path, map_location=device) |
| test_mode = 3 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_icl_tf(save_path, map_location=device) |
| elif (load_pretrain_model==11): |
| test_mode = 5 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_model(save_path, map_location=device) |
| test_mode = 1 |
| save_path = args.pretrain_model_path + '_'+str(test_mode)+ '_' +str(icl_weight)+ '_' +str(n_epochs) |
| model.load_lap_model(save_path, map_location=device) |
|
|
| test_mode = args.test_mode |
| model, logs = train_end_to_end_lap_pe_icl( |
| args=args, |
| model=model, |
| n_samples=n_samples, |
| batch_size=batch_size, |
| raw_dim=raw_dim, |
| k_feat=k_feat, |
| lap_n_layer=4, lap_n_head=2, lap_var=0.1, |
| pe_n_layer=6, pe_n_head=4, pe_var=0.1, |
| n_layer_icl=1, kernel='linear', label_percent=label_percent, context_size=context_size, |
| lr=0.001, n_epochs=n_epochs, |
| scale_rbf=scale_rbf, |
| lap_weight=lap_weight, pe_weight=pe_weight, icl_weight=icl_weight, |
| test_mode = test_mode, |
| ) |
| else: |
| print(">>> Training the End-to-End LAP+PE+ICL Transformer ...") |
| model, logs = train_end_to_end_lap_pe_icl( |
| args=args, |
| n_samples=n_samples, |
| batch_size=batch_size, |
| raw_dim=raw_dim, |
| k_feat=k_feat, |
| lap_n_layer=4, lap_n_head=2, lap_var=0.1, |
| pe_n_layer=6, pe_n_head=4, pe_var=0.1, |
| n_layer_icl=1, kernel='linear', label_percent=label_percent, context_size=context_size, |
| lr=0.001, n_epochs=n_epochs, |
| scale_rbf=scale_rbf, |
| lap_weight=lap_weight, pe_weight=pe_weight, icl_weight=icl_weight, |
| test_mode = test_mode, |
| ) |
| |
| if save_path is not None: |
| os.makedirs(os.path.dirname(save_path), exist_ok=True) |
| model.save_model(save_path) |
| print(f"Model saved to {save_path}") |
| n_epochs = 1 |
| |
| model, logs = test_end_to_end_lap_pe_icl( |
| model, |
| n_samples=n_samples, |
| batch_size=batch_size, |
| raw_dim=raw_dim, |
| k_feat=k_feat, |
| lap_n_layer=4, lap_n_head=2, lap_var=0.1, |
| pe_n_layer=6, pe_n_head=4, pe_var=0.1, |
| n_layer_icl=2, kernel='linear', label_percent=label_percent, context_size=context_size, |
| lr=0.001, n_epochs=n_epochs, |
| scale_rbf=scale_rbf, |
| lap_weight=lap_weight, pe_weight=pe_weight, icl_weight=icl_weight, |
| test_mode = test_mode, |
| ) |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| main() |
| |
|
|