Initialize optimizer research workspace with official baselines and history-free coverage
Vendor pinned MeZO, AGZO, LOZO and LoREN sources with independent environments. Add direct in-place fix/adjust/node training, derived history-free basis gradients, development-best checkpoints and experiment tooling. Keep models, datasets, caches and credentials outside Git. Validation: 93 project tests passed; 521 vendored author files verified.
This commit is contained in:
commit
e0feabec8f
596 files changed
+87356
No files matched your search
@@ -0,0 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# @Author: pingzhili
|
||||
# @Time: 2024/1/17
|
||||
@@ -0,0 +1,71 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# @Author: pingzhili
|
||||
# @Time: 2024/1/18
|
||||
from typing import Dict
|
||||
|
||||
import torch
|
||||
from transformers import PreTrainedModel
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def random_mask_like(tensor, nonzero_ratio, generator=None):
|
||||
"""
|
||||
Return a random mask with the same shape as the input tensor, where the fraction of True is equal to the sparsity.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> random_mask_like(torch.randn(10, 10), 0.1).count_nonzero()
|
||||
tensor(10)
|
||||
"""
|
||||
mask = torch.zeros_like(tensor)
|
||||
mask.view(-1)[torch.randperm(mask.numel(), generator=generator)[:int(nonzero_ratio * mask.numel())]] = 1
|
||||
return mask.bool()
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def fast_random_mask_like(tensor, nonzero_ratio, generator=None):
|
||||
"""
|
||||
A much faster version of random_zero_mask_like, but the sparsity is not guaranteed.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> fast_random_mask_like(torch.randn(10, 10), 0.1).count_nonzero() < 20
|
||||
tensor(True)
|
||||
"""
|
||||
mask = torch.empty_like(tensor).normal_(generator=generator) < nonzero_ratio
|
||||
return mask.bool()
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def estimate_pretrained_model_magnitude_pruning_threshold(
|
||||
model: PreTrainedModel,
|
||||
global_sparsity: float,
|
||||
) -> float:
|
||||
"""
|
||||
Compute the magnitude threshold for pruning based on the global sparsity requirement.
|
||||
"""
|
||||
all_weights = []
|
||||
for param in model.parameters():
|
||||
all_weights.append(
|
||||
param.view(-1).abs().clone().detach().cpu()
|
||||
)
|
||||
all_weights = torch.cat(all_weights)
|
||||
# subsample 102400 elements to estimate the threshold
|
||||
sample_size = int(min(1e7, all_weights.numel()))
|
||||
print(f"[Sparse gradient] Subsampling {sample_size} elements to estimate the threshold.")
|
||||
sub_weights = all_weights[torch.randperm(all_weights.numel())[:sample_size]]
|
||||
return torch.quantile(sub_weights.float(), global_sparsity).item()
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def compute_named_parameters_to_sparsity(
|
||||
model: PreTrainedModel,
|
||||
threshold: float,
|
||||
) -> Dict[str, float]:
|
||||
"""
|
||||
Compute the sparsity of each named parameter in the model.
|
||||
"""
|
||||
named_parameters_to_sparsity = {}
|
||||
for name, param in model.named_parameters():
|
||||
named_parameters_to_sparsity[name] = param.abs().le(threshold).float().mean().item()
|
||||
return named_parameters_to_sparsity
|
||||
@@ -0,0 +1,60 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# @Author: pingzhili
|
||||
# @Time: 2024/1/17
|
||||
"""WANDA: Pruning by Weights and activations (https://arxiv.org/pdf/2306.11695.pdf)"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
import torch
|
||||
from transformers import PreTrainedModel
|
||||
|
||||
|
||||
@dataclass
|
||||
class WandaPruningConfig:
|
||||
sparsity: Optional[float] = 0.5
|
||||
comparison_group: Optional[str] = "model" # model, layer, linear
|
||||
scaler_device: Optional[str] = "cuda"
|
||||
|
||||
|
||||
class WandaPruner:
|
||||
def __init__(
|
||||
self,
|
||||
config: WandaPruningConfig,
|
||||
model: PreTrainedModel,
|
||||
):
|
||||
self.model = model
|
||||
self.config = config
|
||||
|
||||
self.linear_module_scaler_dict = {}
|
||||
self.linear_module_num_samples_dict = {}
|
||||
self.linear_module_hook_dict = {}
|
||||
self._init_hooks_and_scaler()
|
||||
|
||||
def _init_hooks_and_scaler(self):
|
||||
device = self.config.scaler_device
|
||||
|
||||
def _get_forward_hook(name, input_dim):
|
||||
|
||||
def _forward_hook(module, input, output):
|
||||
input = input.reshape(-1, input_dim)
|
||||
num_prev_samples = self.linear_module_num_samples_dict[name]
|
||||
num_curr_samples = input.shape[0]
|
||||
self.linear_module_scaler_dict[name] *= (num_prev_samples / (num_prev_samples + num_curr_samples))
|
||||
self.linear_module_num_samples_dict[name] += num_curr_samples
|
||||
self.linear_module_scaler_dict[name] += torch.norm(
|
||||
input, dim=0, p=2
|
||||
) / (num_prev_samples + num_curr_samples)
|
||||
|
||||
return _forward_hook
|
||||
|
||||
for name, module in self.model.named_modules():
|
||||
if isinstance(module, torch.nn.Linear):
|
||||
self.linear_module_num_samples_dict[name] = 0
|
||||
self.linear_module_scaler_dict[name] = torch.ones(module.weight.shape[1], device=device)
|
||||
_hook = module.register_forward_hook(_get_forward_hook(name, module.weight.shape[1]))
|
||||
self.linear_module_hook_dict[name] = _hook
|
||||
|
||||
def remove_hooks(self):
|
||||
for name, hook in self.linear_module_hook_dict.items():
|
||||
hook.remove()
|
||||
Reference in new issue
Block a user