Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
387 lines (328 loc) · 13.4 KB
/
Copy pathutils.py
File metadata and controls
387 lines (328 loc) · 13.4 KB
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import torch
from sparse_modeling import SparseLinear
from model import GPT, GPTConfig
# from datasets import load_dataset
import tiktoken
import torch.nn as nn
import pickle
import os
@torch.no_grad()
def get_raw_model(model):
if hasattr(model, "module"):
if hasattr(model.module, "student"):
raw_model = model.module.student
else:
raw_model = model.module
else:
if hasattr(model, "student"):
raw_model = model.student
else:
raw_model = model
return raw_model
@torch.no_grad()
def update_model_grad_ema(model, update_hessian_with_grad2: bool = True):
model = get_raw_model(model)
for name, module in model.named_modules():
if isinstance(module, SparseLinear):
module.update_grad_ema(update_hessian=update_hessian_with_grad2)
def _rademacher_like(t: torch.Tensor) -> torch.Tensor:
return (torch.randint_like(t, low=0, high=2, dtype=torch.int8).float() * 2 - 1).to(dtype=t.dtype, device=t.device)
def update_hessian_hutchinson(model, loss):
"""Update per-layer Hessian diagonal using Hutchinson estimator.
diag(H) ≈ E[(H v) ⊙ v], where v ~ Rademacher. We use one sample per step.
Requires calling before .backward() so that the computation graph is alive.
"""
raw = get_raw_model(model)
# Collect target params (SparseLinear weights) and owning modules
params = []
owners = []
for name, module in raw.named_modules():
if isinstance(module, SparseLinear):
params.append(module.weight)
owners.append(module)
if not params:
return
try:
# First-order grads with graph for HVP
grads = torch.autograd.grad(loss, params, create_graph=True, retain_graph=True, allow_unused=True)
# Sample Rademacher vectors and build <g, v>
vs = []
dot = None
for g, p in zip(grads, params):
if g is None:
vs.append(None)
continue
v = _rademacher_like(p)
vs.append(v)
term = (g * v).sum()
dot = term if dot is None else dot + term
if dot is None:
return
# Hessian-vector products
hvps = torch.autograd.grad(dot, params, retain_graph=True, allow_unused=True)
except RuntimeError:
# Kernel may not support double backward; silently skip this update
return
# Update EMA of diag(H) per module: ReLU to ensure non-negativity
for module, hvp, v in zip(owners, hvps, vs):
if hvp is None or v is None:
continue
diag_est = (hvp * v).detach()
diag_est = torch.clamp(diag_est, min=0.0)
beta = getattr(module, 'beta', 0.99)
module.hessian_diag.mul_(beta).add_(diag_est, alpha=1 - beta)
@torch.no_grad()
def calculate_model_mask(model, step=0):
model = get_raw_model(model)
for name, module in model.named_modules():
if isinstance(module, SparseLinear):
module.update_mask(step)
@torch.no_grad()
def calculate_flip_rate(model):
model = get_raw_model(model)
flipped = 0
init_flipped = 0
total = 0
for name, module in model.named_modules():
if isinstance(module, SparseLinear):
flipped += module.weight.flipped_mask
init_flipped += module.weight.init_flipped_mask
total += module.weight.param_count
return flipped ,flipped / total, init_flipped, init_flipped / total
@torch.no_grad()
def init_mask(model, mask_type):
model = get_raw_model(model)
for name, module in model.named_modules():
if isinstance(module, SparseLinear):
module.init_mask(mask_type)
@torch.no_grad()
def set_model_mode(model, mode):
model = get_raw_model(model)
for name, module in model.named_modules():
if isinstance(module, SparseLinear):
module.mode = mode
@torch.no_grad()
def initialize_model(model):
model = get_raw_model(model)
for name, module in model.named_modules():
if isinstance(module, SparseLinear):
module.initialize()
if module.SLoRB:
module.init_SLoRB()
def sync_weight(model, device):
model = model.to(device)
model = get_raw_model(model)
for name, module in model.named_modules():
if isinstance(module, SparseLinear):
module.sync_weight()
@torch.no_grad()
def mid_penalty(model, lambda_mid: float = 0.0):
"""Penalty to push soft decisions away from 0.5 using metric_ema as proxy.
Note: original SparseLinear uses binary masks in forward; here we approximate
a continuous proxy via metric_ema -> sigmoid-normalization.
"""
if lambda_mid <= 0:
return torch.tensor(0.0, device=get_raw_model(model).device if hasattr(get_raw_model(model), 'device') else 'cpu')
raw_model = get_raw_model(model)
penalty = torch.tensor(0.0, device=next(raw_model.parameters()).device)
eps = 1e-8
for name, module in raw_model.named_modules():
if isinstance(module, SparseLinear):
score = module.metric_ema
mean = score.mean()
std = score.std() + eps
norm = (score - mean) / std
p = torch.sigmoid(norm)
penalty = penalty + (p * (1 - p)).mean()
return lambda_mid * penalty
@torch.no_grad()
def harden_fraction(model, fraction: float = 0.2, band_low: float = 0.4, band_high: float = 0.6):
"""Iteratively harden a fraction of near-boundary mask positions globally.
Select entries whose proxy prob p in (band_low, band_high) and closest to 0.5,
then mark them frozen and set current binary mask accordingly.
"""
raw_model = get_raw_model(model)
# Collect candidates across layers
candidates = []
devices = set()
for name, module in raw_model.named_modules():
if isinstance(module, SparseLinear):
score = module.metric_ema
mean = score.mean()
std = score.std() + 1e-8
norm = (score - mean) / std
p = torch.sigmoid(norm)
sel = (~module.frozen_mask_flags) & (p > band_low) & (p < band_high)
if sel.any():
diff = (p - 0.5).abs()
idx = torch.nonzero(sel, as_tuple=False)
candidates.append((module, idx, diff[sel]))
devices.add(score.device)
if not candidates:
return 0
# Global sorting by closeness to 0.5
all_scores = torch.cat([c[2] for c in candidates])
k = int(len(all_scores) * fraction)
if k <= 0:
return 0
threshold = torch.topk(all_scores, k, largest=False).values.max()
hardened = 0
for module, idx, diff in candidates:
sel_to_harden = diff <= threshold
if sel_to_harden.any():
harden_idx = idx[sel_to_harden]
module.frozen_mask_flags[harden_idx[:,0], harden_idx[:,1]] = True
# Fix current binary mask according to present selection rule (0.5 threshold)
# Reuse last computed mask or recompute locally
current_mask = module.weight.mask.int()
module.weight.mask[harden_idx[:,0], harden_idx[:,1]] = current_mask[harden_idx[:,0], harden_idx[:,1]]
hardened += sel_to_harden.sum().item()
return hardened
@torch.no_grad()
def eval_ppl(model, bs=2, device="cuda:0", block_size=1024):
# testdata = load_dataset('data/wikitext/wikitext-2-raw-v1', split='test',cache_dir=None)
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_dir, 'data', 'wikitext', 'wikitext-2-raw-v1', 'wiki.test.raw')
with open(file_path, 'r', encoding='utf-8') as f:
text = f.read()
tokenizer = tiktoken.get_encoding("gpt2")
testenc = tokenizer.encode_ordinary(text)
# from transformers import AutoTokenizer
# tokenizer = AutoTokenizer.from_pretrained('/root/autodl-tmp/opt-125m', use_fast=False, trust_remote_code=True)
# testenc = tokenizer.encode("\n\n".join(testdata['text']))
model.eval()
# transfrom list to tensor
testenc = torch.tensor(testenc, dtype=torch.long, device=device).unsqueeze(0)
# Calculate number of samples
nsamples = testenc.numel() // block_size
# List to store negative log likelihoods
nlls = []
print(f"nsamples {nsamples}")
# Loop through each batch
for i in range(0,nsamples,bs):
if i % 50 == 0:
print(f"sample {i}")
# Calculate end index
j = min(i+bs, nsamples)
# Prepare inputs and move to device
inputs = testenc[:,(i * block_size):(j * block_size)].to(device)
inputs = inputs.reshape(j-i, block_size)
# Forward pass through the model
lm_logits = model(inputs)[0]
# Shift logits and labels for next token prediction
shift_logits = lm_logits[:, :-1, :].contiguous()
shift_labels = inputs[:, 1:]
# Compute loss
loss_fct = nn.CrossEntropyLoss()
loss = loss_fct(shift_logits.reshape(-1, shift_logits.size(-1)), shift_labels.reshape(-1))
# Calculate negative log likelihood
neg_log_likelihood = loss.float() * block_size * (j-i)
# Append to list of negative log likelihoods
nlls.append(neg_log_likelihood)
# Compute perplexity
ppl = torch.exp(torch.stack(nlls).sum() / (nsamples * block_size))
# Empty CUDA cache to save memory
torch.cuda.empty_cache()
model.train()
return ppl.item()
def find_layers(module, layers=[nn.Linear], name=''):
"""
Recursively find the layers of a certain type in a module.
Args:
module (nn.Module): PyTorch module.
layers (list): List of layer types to find.
name (str): Name of the module.
Returns:
dict: Dictionary of layers of the given type(s) within the module.
"""
if type(module) in layers:
return {name: module}
res = {}
for name1, child in module.named_children():
res.update(find_layers(
child, layers=layers, name=name + '.' + name1 if name != '' else name1
))
return res
def prepare_calibration_input(model, dataloader, device, nsamples):
layers = model.transformer.h
model = model.to(device)
dtype = next(iter(model.parameters())).dtype
inps = torch.zeros((nsamples, model.config.block_size, model.config.n_embd), dtype=dtype, device=device)
inps.requires_grad = False
cache = {'i': 0, 'attention_mask': None, "position_ids": None}
class Catcher(nn.Module):
def __init__(self, module):
super().__init__()
self.module = module
def forward(self, inp, **kwargs):
inps[cache['i']] = inp
cache['i'] += 1
raise ValueError
layers[0] = Catcher(layers[0])
for batch in dataloader:
try:
model(batch.to(device))
except ValueError:
pass
layers[0] = layers[0].module
outs = torch.zeros_like(inps)
inps, outs = inps.to(device), outs.to(device)
return inps, outs
def add_calibration(model, nsamples=128, device="cuda"):
model = get_raw_model(model)
for name, module in model.named_modules():
if isinstance(module, SparseLinear):
in_features = module.weight.shape[1]
module.scaler_row = nn.Parameter(torch.ones(in_features, device=device))
base_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(base_dir, 'data', 'c4_dataset', 'calibration_dataset.pkl')
with open(file_path, 'rb') as f:
dataloader = pickle.load(f)
inps, outs = prepare_calibration_input(model, dataloader, device, nsamples)
layers = model.transformer.h
for i in range(len(layers)):
layer = layers[i]
subset = find_layers(layer, layers=[SparseLinear])
def add_batch(name):
def tmp(_, inp, out):
subset[name].add_batch(inp[0].data, out.data)
return tmp
handles = []
for name in subset:
handles.append(subset[name].register_forward_hook(add_batch(name)))
for j in range(nsamples):
with torch.no_grad():
outs[j] = layer(inps[j].unsqueeze(0))[0]
for h in handles:
h.remove()
inps, outs = outs, inps
torch.cuda.empty_cache()
if __name__ == "__main__":
n_layer = 12
n_head = 12
n_embd = 768
block_size = 1024
bias = True
dropout = 0.1
model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size,
bias=bias, vocab_size=None, dropout=dropout) # start with model_args from command line
model_args['vocab_size'] = 50304
# gptconf = GPTConfig(**model_args)
# model = GPT(gptconf)
init_from = "gpt2"
override_args = dict(dropout=dropout)
model = GPT.from_pretrained(init_from, override_args)
# read off the created config params, so we can store them into checkpoint correctly
for k in ['n_layer', 'n_head', 'n_embd', 'block_size', 'bias', 'vocab_size']:
model_args[k] = getattr(model.config, k)
if block_size < model.config.block_size:
model.crop_block_size(block_size)
model_args['block_size'] = block_size
device = torch.device("cuda:0")
model = model.to(device)
print(eval_ppl(model, bs=1, device=device, block_size=1024))
add_calibration(model, nsamples=128, device="cuda:0")
for n,p in model.named_parameters():
if hasattr(p, 'mask'):
p.mode = "2:4"
print(eval_ppl(model, bs=1, device=device, block_size=1024))