mcy98's picture
Upload folder using huggingface_hub
f2cf608 verified
Raw History Blame Contribute Delete
6.57 kB
# test_collect_grads.py
import os
import shutil
import tempfile
import unittest
# Import the canonical and generated collect_grads functions
from canonical import collect_grads as canonical_collect_grads
from collect_grad_reps import collect_grads as generated_collect_grads
import numpy as np
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
# Dummy output object with a .loss field (like HuggingFace model outputs)
class DummyOutput:
def __init__(self, loss):
self.loss = loss
# Simple transformer-style predictor for test use
class DummyModel(nn.Module):
def __init__(self, input_dim=2, seq_len=2, num_classes=10, d_model=8, nhead=2, num_layers=1):
super().__init__()
self.input_dim = input_dim
self.seq_len = seq_len
self.d_model = d_model
# Simple input embedding: project input_dim to d_model
self.embedding = nn.Linear(input_dim, d_model)
# One TransformerEncoderLayer (or a stack)
encoder_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=nhead, batch_first=True)
self.transformer = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
# Pooling and prediction head
self.head = nn.Linear(d_model, num_classes)
def forward(self, input, label):
"""
input: shape (batch_size, seq_len, input_dim)
label: shape (batch_size, seq_len) or (batch_size,)
"""
# Embed each input token
x = self.embedding(input) # (batch, seq_len, d_model)
# Transformer expects input as (batch, seq_len, d_model) if batch_first
x = self.transformer(x)
# Simple way: take mean over sequence (global average pooling)
x = x.mean(dim=1) # (batch, d_model)
logits = self.head(x) # (batch, num_classes)
# If label is (batch, seq_len), use just the first position for test
if label.dim() > 1:
label = label[:, 0]
label = label.long() % logits.shape[-1] # Ensure in correct class range
# Cross-entropy loss
loss = F.cross_entropy(logits, label)
return DummyOutput(loss=loss)
# Usage Example in Test Setup:
# self.model = DummyTransformerModel(input_dim=2, seq_len=2, num_classes=10)
def dummy_dataloader(num_batches=2, batch_size=2, seed=42):
rng = torch.Generator().manual_seed(seed)
for _ in range(num_batches):
yield {
'input': torch.randn(batch_size, 2, 2, generator=rng),
'label': torch.randint(0, 10, (batch_size, 2), generator=rng)
}
class TestCollectGradsFunctionalEquivalence(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp()
self.proj_dim = [512, 1024]
self.gradient_type = "sgd"
self.adam_optimizer_state = None
self.max_samples = None
self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# Ensure total determinism everywhere
self.seed = 12345
def tearDown(self):
shutil.rmtree(self.test_dir)
def set_all_seeds(self, seed):
torch.manual_seed(seed)
random.seed(seed)
np.random.seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
# For deterministic cuDNN behavior
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
def list_saved_files(self, output_dir, proj_dim):
all_files = {}
for d in proj_dim:
subdir = os.path.join(output_dir, f"dim{d}")
if not os.path.exists(subdir):
all_files[d] = []
continue
files = sorted(
[f for f in os.listdir(subdir) if f.startswith('grads-') and (f.endswith('.pt') or f.endswith('.npy') or f.endswith('.bin'))]
)
all_files[d] = files
return all_files
def compare_dirs(self, dir1, dir2, proj_dim):
files1 = self.list_saved_files(dir1, proj_dim)
files2 = self.list_saved_files(dir2, proj_dim)
self.assertEqual(files1, files2, "Mismatch in file lists per dimension")
for d in proj_dim:
subdir1 = os.path.join(dir1, f"dim{d}")
subdir2 = os.path.join(dir2, f"dim{d}")
for f in files1[d]:
path1 = os.path.join(subdir1, f)
path2 = os.path.join(subdir2, f)
t1 = torch.load(path1, map_location='cpu')
t2 = torch.load(path2, map_location='cpu')
try:
torch.testing.assert_close(t1, t2, rtol=1e-6, atol=1e-8)
except AssertionError as e:
self.fail(f"Tensor mismatch in file {f} for dim {d}: {e}")
def test_functional_equivalence_collect_grads(self):
# Set all seeds before everything else
self.set_all_seeds(self.seed)
# Create a single model and copy weights for both runs
model1 = DummyModel().to(self.device)
self.set_all_seeds(self.seed) # ensure model2 initialized the same way, just in case
model2 = DummyModel().to(self.device)
model2.load_state_dict(model1.state_dict())
# Pre-generate all batches for dataloader to avoid new randomness
dataloader_batches = list(dummy_dataloader(num_batches=2, batch_size=1, seed=self.seed))
# Canonical run
canon_dir = os.path.join(self.test_dir, "canon")
os.mkdir(canon_dir)
self.set_all_seeds(self.seed)
canonical_collect_grads(
dataloader=dataloader_batches,
model=model1,
output_dir=canon_dir,
proj_dim=self.proj_dim,
adam_optimizer_state=self.adam_optimizer_state,
gradient_type=self.gradient_type,
max_samples=self.max_samples
)
# Generated run (use same dataloader batches and model weights)
gen_dir = os.path.join(self.test_dir, "gen")
os.mkdir(gen_dir)
self.set_all_seeds(self.seed)
generated_collect_grads(
dataloader=dataloader_batches,
model=model2,
output_dir=gen_dir,
proj_dim=self.proj_dim,
adam_optimizer_state=self.adam_optimizer_state,
gradient_type=self.gradient_type,
max_samples=self.max_samples
)
# Compare saved files and their content for functional equivalence
self.compare_dirs(canon_dir, gen_dir, self.proj_dim)
if __name__ == '__main__':
unittest.main()