File size: 6,572 Bytes
f2cf608 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | # 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()
|