carin-jf381-data / ICL_code /ICL_Jay_final /data_generation.py
jasonfan's picture
2026-03-19: ICL code
64bce2a verified
#!/usr/bin/env python
# coding: utf-8
# In[1]:
# Cell 1: Import Libraries and Define Helper Functions
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)
# Cell 4: Training Function to Predict the Laplacian using the RBF–activated Transformer
# # In[ ]:
# # Cell 5: Main Training Loop
if __name__ == "__main__":
# Hyperparameters
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 # Set k_feat here
n_nodes = n_samples
# Define model path for saving/loading
model_path = "transformer_laplacian_model.pt"
# Check if model exists
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 = create_transformer_model(n_samples, k_feat, n_layer, n_head)
model.load_state_dict(torch.load(model_path))
model = model.to(device)
# No losses available for loaded model
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 # Pass k_feat to the training function
)
# Save the trained model
torch.save(model.state_dict(), model_path)
print(f">>> Model saved to {model_path}")
# Plot the training curve
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()
# # >>> Test on one set of sampled points
# test_seed = 999
# print(f"\n>>> Testing on a new Swiss roll (seed={test_seed}) ...")
# L_test, xyz_test, labels_test = generate_small_swiss_roll_in_3d(
# n_samples=n_samples,
# scale_rbf=scale_rbf,
# k_nn=k_nn,
# seed=test_seed,
# device=device
# )
# # Build a single-sample Z the same way: first half is xyz, second half is L, third part is k_feat features
# Z_test = torch.zeros(1, n_samples, 2 * n_samples + k_feat, device=device)
# for row_idx in range(n_samples):
# Z_test[0, row_idx, 0:3] = torch.from_numpy(xyz_test[row_idx, :])
# Z_test[0, row_idx, n_samples:2 * n_samples] = L_test[row_idx, :]
# Z_test[0, row_idx, 2 * n_samples:2 * n_samples + k_feat] = 0.0 # Initialize additional features
# # Zero out Laplacian and additional features from input, ask model to predict
# Z_in_test = Z_test.clone()
# Z_in_test[:, :, n_samples:2 * n_samples] = 0.0
# Z_in_test[:, :, 2 * n_samples:2 * n_samples + k_feat] = 0.0
# model.eval()
# with torch.no_grad():
# Z_out_test = model(Z_in_test)
# pred_test_rows = Z_out_test[:, :, n_samples:2 * n_samples] # predicted Laplacian
# real_test_rows = Z_test[:, :, n_samples:2 * n_samples] # true Laplacian
# diff_test = pred_test_rows - real_test_rows
# frob_test = diff_test.pow(2).sum(dim=[1, 2]).sqrt().mean().item()
# print(f"Frobenius error on test Laplacian = {frob_test:.6f}")
# # Also plot the 3D Swiss roll used in the test, color-coded by "labels_test"
# fig = plt.figure(figsize=(8,6))
# ax = fig.add_subplot(111, projection='3d')
# ax.scatter(
# xyz_test[:,0],
# xyz_test[:,1],
# xyz_test[:,2],
# c=labels_test,
# cmap='bwr',
# s=35
# )
# ax.set_xlabel("x")
# ax.set_ylabel("y")
# ax.set_zlabel("z")
# ax.set_title(f"Test Swiss Roll in 3D (z=1 plane), seed={test_seed}")
# plt.show()
# In[ ]:
# model.load
import torch.nn.functional as F
# Train the ICL Transformer with Embeddings from a PE Transformer with Fixed Weights.
# Ensure GPU usage if available
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)
# Helper functions
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):
# B is of shape [batch_size, n_nodes, n_edges]
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
# Get Laplacian and compute eigendecomposition
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]
# Store unnormalized versions
predicted_unnorm = predicted_ev.clone()
target_unnorm = target.clone()
# Normalize
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):
# Plot predicted eigenvector
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 statistics
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}")
# Plot target eigenvector
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()
# Compute loss
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)
#t = torch.cat((t0,t2+1),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):
# data has shape B x n_sample x dim
B, n, d = data.shape
# distance(vi, vj) = ||vi - vj||^2 = ||vi||^2 + ||vj||^2 - 2<vi,vj>
norms = torch.norm(data, p=2, dim=2)**2
#euclidean_distances = torch.zeros((B,n,n))
euclidean_distances = norms[:,:,None] + norms[:,None,:] - 2 * torch.einsum('Bni,Bmi->Bnm',(data,data))
inv_rbf_distances = torch.exp(-scale * euclidean_distances)
#normalization_diag = inv_rbf_distances.sum(dim=-2)**0.5
#inv_rbf_distances = inv_rbf_distances/normalization_diag[:,:,None]/normalization_diag[:,None,:]
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.
"""
# Mask the diagonal to exclude self-loops
n = inv_distance_matrix.size(0)
inv_distance_matrix = inv_distance_matrix.clone() # Avoid modifying the original
inv_distance_matrix.fill_diagonal_(float(-1)) # Set diagonal to a large value
# Flatten the distance matrix
# flattened_distances = distance_matrix.flatten()
# Find the indices of the smallest k distances
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) # Disable grid for clarity
plt.show()
import torch
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from mpl_toolkits.mplot3d import Axes3D # Import for 3D plotting
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)
"""
# Set seeds for reproducibility
torch.manual_seed(seed)
np.random.seed(seed)
# Generate Swiss Roll data in 2D
t, a = gen_random_data(1, n_samples, type='swissroll') # t: [1, n_samples], a: [1, n_samples, 2]
# Embed in R^3 with z = 1
z_coords = torch.ones((1, n_samples, 1))
a_translated = torch.cat([a, z_coords], dim=2) # Shape: [1, n_samples, 3]
# Apply random scaling (only on x and y)
scale_factor = np.random.uniform(0.02, .1) # Scaling
a_translated[:, :, :2] = a_translated[:, :, :2] * scale_factor
# Apply random rotation (only on x and y)
theta = np.random.uniform(0, 2 * np.pi) # Rotation angle between 0 and 2π radians
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) # Shape: [1, n_samples, 3]
# Apply random translation (only on x and y)
translation_x = np.random.uniform(-1, 1) # Translation between -1 and 1 units on X-axis
translation_y = np.random.uniform(-1, 1) # Translation between -1 and 1 units on Y-axis
translation_z = 0
translation = torch.tensor([[[translation_x, translation_y, translation_z]]], dtype=torch.float32)
a_translated = a_rotated + translation # Shape: [1, n_samples, 3]
# Compute weighted adjacency matrix using inverse RBF distances
inv_distances = random_data_to_adjacency(a_translated[:, :, :2], scale=scale) # Shape: [1, n_samples, n_samples]
# Construct k-NN adjacency matrix based on smallest inverse distances
knn_indices = smallest_k_indices(inv_distances[0, :, :], k) # Shape: [n_samples, 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:
# Use weighted edges
weight = inv_distances[0, i, j].item()
adj[i, j] = weight
adj[j, i] = weight # Ensure symmetry
# Either compute or predict Laplacian
if use_predicted_laplacian:
# Prepare input for the model in the same format as the training data
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, :] # Store (x, y, z)
# Predict Laplacian rows
model.eval()
with torch.no_grad():
predicted_laplacian_rows = model(Z_input_for_model)[:, :, n_samples:2*n_samples] # [1, n, n]
L_test = predicted_laplacian_rows[0].to(device) # [n, n]
else:
# Compute normalized Laplacian
degree = torch.sum(adj, dim=1)
degree[degree == 0] = 1.0 # Avoid division by zero
D_inv_sqrt = torch.diag(degree.pow(-0.5))
L_test = torch.eye(adj.size(0)) - D_inv_sqrt @ adj @ D_inv_sqrt
# Compute eigenvalues and eigenvectors
target_eigenvals, target_ev_torch = torch.linalg.eigh(L_test)
target_ev = target_ev_torch.cpu().numpy() # Convert to NumPy for consistency
if return_extra:
# Perform plotting
data = a_translated[0].cpu().numpy() # Shape: [n_samples, 3]
# Assign labels based on the median of t
labels = np.where(t[0].cpu().numpy() < np.median(t[0].cpu().numpy()), 1, -1)
# Plot the labeled Swiss Roll data (3D Projection) - unchanged
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()
# Plot the Laplacian as a heatmap.
# If 'use_predicted_laplacian' is True, this is the predicted Laplacian.
# Otherwise, it is the real (normalized) Laplacian.
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
# ---------------- Example usage and comparison of Real vs. Predicted Laplacians ----------------
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]
# if use_exact_ev:
# embedding = torch.zeros([batch_size, n_samples, k_feat], device=device)
# for i in range(batch_size):
# # Use the iteration number or base_seed + i as the seed
# seed = base_seed + i # Ensures different seeds for each graph
# adj, L_test, eigenvals, eigenvecs = generate_weighted_swiss_roll_graph(
# n_samples=n_samples,
# scale=10,
# k=k_values[0] if isinstance(k_values, list) else k_values,
# seed=seed, # Use the seed based on iteration number
# return_extra=False
# )
# # Use the normalized Laplacian directly
# lap = L_test.to(device) # L_test is the normalized Laplacian
# # Select and normalize eigenvectors
# eigenvecs_selected = eigenvecs[:, :k_feat]
# eigenvecs_selected /= (np.linalg.norm(eigenvecs_selected, axis=1, keepdims=True) + 1e-10)
# eigenvecs_selected = torch.from_numpy(eigenvecs_selected).float().to(device)
# # Fill Z
# Z[i, :, :n_nodes] = lap # [n, n], normalized Laplacian
# Z[i, :, n_nodes:2*n_nodes] = adj.to(device) # [n, n]
# Z[i, :, 2*n_nodes:] = eigenvecs_selected # [n, k_feat]
# if use_exact_ev:
# actual_embedding = eigenvecs[:, :k_feat] # [n_samples, k_feat]
# embedding[i, :, :] = torch.from_numpy(actual_embedding / (np.linalg.norm(actual_embedding, axis=1, keepdims=True) + 1e-10)).float().to(device)
# if not use_exact_ev:
# # Make predictions with PE transformer
# model.eval()
# with torch.no_grad():
# output = model(Z) # Shape: [batch_size, n_samples, n + (n+k)]
# # Extract predicted eigenvectors
# predicted_ev = output[:, :, -k_feat:].cpu().numpy() # [batch_size, n_samples, k_feat]
# # Predicted embedding
# embedding = predicted_ev / (np.linalg.norm(predicted_ev, axis=1, keepdims=True) + 1e-10)
# embedding = torch.from_numpy(embedding).float().to(device)
# Assign labels based on t for visualization
# We have 't' from Cell 6 or we can re-generate t using the same seed and n_samples
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)
# Get labeled indices
labeled_indices = torch.stack([torch.randperm(n_samples)[:n_labeled] for _ in range(batch_size)]).to(device)
labeled_data = labels.gather(-1, labeled_indices)
# Get context 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) # Shape [B, n_labeled]
# Create a mask for indices present in the input tensor
mask = torch.zeros(batch_size, n_labeled, dtype=torch.bool).to(device)
mask.scatter_(1, context_indices, True)
# Invert the mask to get query indices
query_indices = all_indices[~mask].view(batch_size, n_labeled - context_size).to(device) # Shape [B, n_labeled - context_size]
return None , labeled_data, labeled_indices, context_indices, query_indices
# In[ ]:
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")
# if (not force):
# # 检查文件是否存在
# if os.path.exists(file_path):
# print(f"Loading cached data for epoch {epoch}...")
# cached_data = torch.load(file_path)
# return (
# cached_data['raw_data'],
# cached_data['real_lap'],
# cached_data['labels_tensor'],
# cached_data['real_adj'],
# cached_data['labeled_indices'],
# cached_data['context_indices'],
# cached_data['query_indices'],
# cached_data['real_ev']
# )
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)
# import pdb
# pdb.set_trace()
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)
# Setup Z for generate_in_context_swiss_roll_graphs
Z = torch.zeros([batch_size, n_samples, 2*n_samples + k_feat], device=device)
max_edges = n_samples * 6 # Using k_nn=6
import pdb
# pdb.set_trace()
# Generate in-context data - this is the key part we'll use for ICL training
_, 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, # No model needed for initial generation
use_exact_ev=True # Use exact eigenvectors
)
# pdb.set_trace()
# Setup Z for generate_in_context_swiss_roll_graphs
Z = torch.zeros([batch_size, n_samples, 2*n_samples + k_feat], device=device)
max_edges = n_samples * 6 # Using k_nn=6
# # Compute eigenvectors from real Laplacian for PE loss
# real_eigs = []
# for b in range(batch_size):
# _, vecs = torch.linalg.eigh(real_lap[b])
# eigvecs = vecs[:, :k_feat]
# # Normalize the eigenvectors
# eigvecs = eigvecs / (torch.linalg.norm(eigvecs, axis=0, keepdims=True) + 1e-10)
# real_eigs.append(eigvecs)
# real_ev = torch.stack(real_eigs, dim=0)
# 保存所有数据到磁盘
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
###############################################################################
# End-to-End Training Function (with the fixed Lap extraction)
###############################################################################
def train_end_to_end_lap_pe_icl(
args=None,
n_samples=100,
batch_size=550,
raw_dim=3,
k_feat=4,
# Lap model parameters:
lap_n_layer=4, lap_n_head=2, lap_var=0.1,
# PE model parameters:
pe_n_layer=6, pe_n_head=4, pe_var=0.1,
# ICL parameters:
n_layer_icl=2, kernel='linear', label_percent=100, context_size=99,
# Optimizer settings:
lr=0.001, n_epochs=201,
# RBF adjacency scale:
scale_rbf=10,
# Loss weights:py
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
# 计算当前进程需要训练的epoch范围
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, # 每10个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
)
# model.train()
# optimizer.zero_grad()
# total_loss, lap_loss, pe_loss, icl_query_loss, icl_query_acc = model.train_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,
# )
# total_loss.backward()
# optimizer.step()
# 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())
# if epoch % 10 == 9:
# print(f"Epoch {epoch:03d} | Total: {total_loss.item():.4f} | Lap: {lap_loss.item():.4f} | "
# f"PE: {pe_loss.item():.4f} | ICL: {icl_query_loss.item():.4f} | Acc: {icl_query_acc.item():.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
}
def test_end_to_end_lap_pe_icl(
model,
n_samples=100,
batch_size=550,
raw_dim=3,
k_feat=4,
# Lap model parameters:
lap_n_layer=4, lap_n_head=2, lap_var=0.1,
# PE model parameters:
pe_n_layer=6, pe_n_head=4, pe_var=0.1,
# ICL parameters:
n_layer_icl=2, kernel='linear', label_percent=100, context_size=99,
# Optimizer settings:
lr=0.001, n_epochs=201,
# RBF adjacency scale:
scale_rbf=10,
# Loss weights:py
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")
# Logs for monitoring
losses_over_time = []
lap_losses_log = []
pe_losses_log = []
icl_losses_log = []
icl_acc_log = []
# New tracking for classification performance
lr_accs = []
rkhs_accs = []
context_sizes_list = [99]
# batch_size =225
for context_size in context_sizes_list:
# Generate a batch of data: raw 3D coords, real Lap, and labels
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)
# Build labeled vs. unlabeled sets for ICL
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)
# Ground-truth eigenvectors from real Lap
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)
# import pdb//
# pdb.set_trace()
# Z_pe_out.reshape( condesne the first two diemnsion into 1)
# Z_pe_out = Z_pe_out.reshape(-1, 204) # Resulting shape: [45000, 204]
# labels_tensor = labels_tensor.reshape(-1,204)
# Call the existing classifier training functions with Z_pe_out
batch_size = Z_pe_out.shape[0]
# for batch in
rkhs_acc = 0
lr_acc = 0
# 评估逻辑回归
# log_reg_acc = train_logistic_regression(X_train, y_train, X_test, y_test)
from tqdm import tqdm
for b in tqdm(range(batch_size)):
# import pdb
# pdb.set_trace()
# Z_pe_out[]
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)
# import pdb
# pdb.set_trace()
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()
# import pdb
# pdb.set_trace()
# 评估逻辑回归
lr_acc += train_logistic_regression(X_train, y_train, X_test, y_test, device='cpu')
# log_reg_accs.append(log_reg_acc)
# 评估RKHS分类器
rkhs_acc += train_rkhs_classifier(X_train, y_train, X_test, y_test, device='cpu')
print(lr_acc,rkhs_acc)
# break
lr_acc = lr_acc / batch_size
rkhs_acc = rkhs_acc /batch_size
# Store the accuracy results
lr_accs.append(lr_acc)
rkhs_accs.append(rkhs_acc)
# Continue with existing logging
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
}
# usage
# n_samples = 100
# batch_size = 450
# scale_rbf = 10
n_epochs = 101
# raw_dim = 3
# k_feat = 4
def main():
parser = argparse.ArgumentParser(description="Train End-to-End Spectral Learning Model")
# Data generation parameters
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")
# Laplacian model parameters
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")
# PE model parameters
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")
# ICL parameters
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")
# Training parameters
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")
# Loss weights
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")
# Test mode
parser.add_argument("--test_mode", type=int, default=0,
help="Test mode (see config.TEST_MODES for details)")
# File paths
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")
# Action flags
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)
# Either load or train the model
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,
)
# Save the model if a path is provided
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
# batch_size = 450
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,
)
# metrics, visuals = test_end_to_end_model(
# model=model,
# n_samples=n_samples,
# scale_rbf=scale_rbf,
# k_nn=k_nn,
# k_feat=k_feat,
# test_seed=test_seed,
# test_mode=test_mode,
# raw_dim=raw_dim,
# device=device,
# cache_dir=cache_dir
# )
# print(metrics)
main()
# %%