|
| 1 | +from tqdm import tqdm |
| 2 | +import pickle |
| 3 | +import os |
| 4 | +import argparse |
| 5 | + |
| 6 | +from transformers import AutoTokenizer, AutoModelForCausalLM |
| 7 | +from datasets import load_dataset |
| 8 | +import torch |
| 9 | + |
| 10 | +import modeling as M |
| 11 | +from utils import QFilters |
| 12 | + |
| 13 | + |
| 14 | +device = "cuda" if torch.cuda.is_available() else "cpu" |
| 15 | + |
| 16 | +parser = argparse.ArgumentParser() |
| 17 | + |
| 18 | +parser.add_argument("--model_name") |
| 19 | +parser.add_argument("--model_cls") |
| 20 | +parser.add_argument("--max_seq_len", type=int, default=2048) |
| 21 | +parser.add_argument("--num_sequences", type=int, default=20) |
| 22 | +parser.add_argument("--num_svd_samples", type=int, default=3000) |
| 23 | +parser.add_argument("--filter_suffix", default="") |
| 24 | +parser.add_argument("--torch_dtype", default="bfloat16") |
| 25 | + |
| 26 | +parser.add_argument("--dataset_name") |
| 27 | +parser.add_argument("--dataset_config", default="default") |
| 28 | +parser.add_argument("--dataset_split", default="train[:1000]") |
| 29 | + |
| 30 | +parser.add_argument("--save_mode", default="disk") |
| 31 | +parser.add_argument("--save_dir", default="") |
| 32 | +parser.add_argument("--hf_user_id", default="") |
| 33 | + |
| 34 | + |
| 35 | +args = parser.parse_args() |
| 36 | + |
| 37 | +model_name = args.model_name |
| 38 | +model_cls = getattr(M, args.model_cls) |
| 39 | +max_seq_len = args.max_seq_len |
| 40 | +num_sequences = args.num_sequences |
| 41 | +num_svd_samples = args.num_svd_samples |
| 42 | +filter_suffix = args.filter_suffix |
| 43 | +torch_dtype = args.torch_dtype |
| 44 | + |
| 45 | +dataset_name = args.dataset_name |
| 46 | +dataset_config = args.dataset_config |
| 47 | +dataset_split = args.dataset_split |
| 48 | + |
| 49 | +save_mode = args.save_mode |
| 50 | +save_dir = args.save_dir |
| 51 | +hf_user_id = args.hf_user_id |
| 52 | + |
| 53 | +if "disk" in save_mode and not save_dir: |
| 54 | + raise ValueError("In 'disk' or 'disk+hub' save modes, a '--save_dir' must be provided.") |
| 55 | + |
| 56 | +if "hub" in save_mode and not hf_user_id: |
| 57 | + raise ValueError("In 'hub' or 'disk+hub' save modes, a '--hf_user_id' must be provided.") |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | +tokenizer = AutoTokenizer.from_pretrained(model_name) |
| 62 | +model = model_cls.from_pretrained( |
| 63 | + model_name, attn_implementation="flash_attention_2", device_map="auto", low_cpu_mem_usage=True, torch_dtype=torch_dtype) |
| 64 | + |
| 65 | +model = model.eval() |
| 66 | + |
| 67 | +dataset = load_dataset(dataset_name, dataset_config, split=dataset_split) |
| 68 | + |
| 69 | + |
| 70 | +with torch.no_grad(): |
| 71 | + decoder = getattr(model, "gpt_neox", getattr(model, 'model', None)) |
| 72 | + svd_filters = [[] for _ in range(len(decoder.layers))] |
| 73 | + sample_count = 0 |
| 74 | + num_k_heads = None |
| 75 | + |
| 76 | + for i, sample in tqdm(enumerate(dataset)): |
| 77 | + |
| 78 | + tokens = tokenizer(sample["text"], return_tensors="pt") |
| 79 | + if tokens.input_ids.shape[-1] < max_seq_len: |
| 80 | + continue |
| 81 | + sample_count+=1 |
| 82 | + input_ids = tokens.input_ids[:, :max_seq_len].to(device) |
| 83 | + if sample_count < num_sequences: |
| 84 | + with torch.autocast(device_type=device, dtype=torch.bfloat16): |
| 85 | + out_repr = model(input_ids).past_key_values |
| 86 | + for j, (query, key) in enumerate(out_repr): |
| 87 | + num_k_heads = key.shape[1] |
| 88 | + svd_filters[j].append(query.flatten(0, 1).cpu()) |
| 89 | + else: |
| 90 | + break |
| 91 | + |
| 92 | + del model |
| 93 | + |
| 94 | + for f_id, el in enumerate(svd_filters): |
| 95 | + stacked_el = torch.stack(el, 1).flatten(1, 2) |
| 96 | + idx = torch.argsort(torch.rand(stacked_el.shape[1], device=stacked_el.device))[:num_svd_samples] |
| 97 | + stacked_el = stacked_el[:, idx].cuda() |
| 98 | + u,s,vh = torch.linalg.svd(stacked_el.float()) |
| 99 | + svd_sign = ((u[..., 0]>0).float().mean(-1) > 0.5).float()*2-1 |
| 100 | + svd_filter_q = -svd_sign[:, None] * vh[..., 0, :] |
| 101 | + svd_filters[f_id] = svd_filter_q.reshape(num_k_heads, -1, svd_filter_q.shape[-1]).mean(-2) |
| 102 | + |
| 103 | + svd_filters = torch.nn.Parameter(torch.stack(svd_filters)) |
| 104 | + q_filters = QFilters(*svd_filters.shape) |
| 105 | + q_filters.q_filters = svd_filters |
| 106 | + |
| 107 | + model_suffix = model_name.split("/")[-1] |
| 108 | + filter_savename = f"{model_suffix}_qfilt{'_' + filter_suffix if filter_suffix else ''}" |
| 109 | + if "disk" in save_mode: |
| 110 | + q_filters.save_pretrained(f"{save_dir}/{filter_savename}") |
| 111 | + if "hub" in save_mode: |
| 112 | + q_filters.push_to_hub(f"{hf_user_id}/{filter_savename}") |
0 commit comments