select_headmask/static.py SHA256 973abb75ba4f04bea61e9bdb80ad951ac4d025ea255afce4676660e11a2cb543
1: import os
2: import random
3: import numpy as np
4: import pandas as pd
5: 
6: def generate_final_matrices(
7:     main_dir='path/to/main_dir',
8:     output_dir='/path/to/output',
9:     alphas=[0.3],
10:     files_per_subfolder=50,
11:     seed=None
12: ):
13:     """
14:     Randomly select a specified number of CSV files from each subfolder,
15:     calculate the frequency of 1s at each position, and generate final
16:     binary (0-1) matrices for multiple alpha parameters. Each resulting
17:     matrix is saved as a separate file.
18: 
19:     Parameters:
20:     - main_dir (str): The main directory containing multiple subfolders.
21:       Each subfolder should contain multiple CSV files.
22:     - output_dir (str): The main directory where the final matrices will be saved.
23:     - alphas (list of float): A list of values between 0 and 1 used to determine
24:       the top proportion of positions to set as 1.
25:     - files_per_subfolder (int): The number of CSV files to randomly select from
26:       each subfolder.
27:     - seed (int, optional): Random seed for reproducibility.
28:     """
29: 
30:     if seed is not None:
31:         random.seed(seed)
32:         np.random.seed(seed)
33: 
34:     # Get all subfolders under the main directory
35:     subfolders = [os.path.join(main_dir, d) for d in os.listdir(main_dir)
36:                  if os.path.isdir(os.path.join(main_dir, d))]
37: 
38:     if len(subfolders) == 0:
39:         raise ValueError(f"No subfolders found under main directory {main_dir}.")
40: 
41:     for subfolder in subfolders:
42:         selected_matrices = []
43:         sub_name = subfolder.split("/")[-1]
44:         # Get all CSV files in the subfolder
45:         csv_files = [f for f in os.listdir(subfolder) if f.endswith('.csv')]
46:         
47:         if len(csv_files) < files_per_subfolder:
48:             raise ValueError(f"Subfolder {subfolder} contains fewer than {files_per_subfolder} CSV files.")
49: 
50:         save_dir = os.path.join(output_dir, sub_name)
51:         # Ensure that the output directory exists
52:         os.makedirs(save_dir, exist_ok=True)
53:     
54:         # Randomly select the specified number of CSV files
55:         selected_files = random.sample(csv_files, files_per_subfolder)
56:         
57:         for alpha in alphas:
58:             if not (0 < alpha < 1):
59:                 raise ValueError(f"Alpha value {alpha} must be between (0, 1).")
60:             for file in selected_files:
61:                 file_path = os.path.join(subfolder, file)
62:                 # Read the CSV file and convert it to float values
63:                 matrix = pd.read_csv(file_path, header=None).values.astype(float)
64:                 threshold = np.quantile(matrix, alpha)
65:                 matrix = (matrix <= threshold).astype(int)
66:                 selected_matrices.append(matrix)
67: 
68:             # Sum all selected matrices to get the frequency of 1s at each position
69:             sum_matrix = np.sum(selected_matrices, axis=0)
70:    
71:             # Compute the threshold: the top alpha proportion of highest values
72:             flat_sum = sum_matrix.flatten()
73:             num_elements = flat_sum.size
74:             num_top = int(np.ceil(alpha * num_elements))
75:             
76:             # Find the smallest value among the top num_top largest elements as the threshold
77:             threshold = np.partition(flat_sum, -num_top)[-num_top]
78:             
79:             # Generate the final 0-1 matrix
80:             final_matrix = (sum_matrix >= threshold).astype(int)
81:             
82:             # Define the output file path, including the alpha value
83:             output_file_path = os.path.join(save_dir, f"head_type_p{int(alpha*100)}.csv")
84:             
85:             # Save the final matrix as a CSV file
86:             pd.DataFrame(final_matrix).to_csv(output_file_path, header=False, index=False)
87:             
88:             print(f"The 0-1 matrix for alpha={alpha} has been saved to: {output_file_path}")
89: 
90: if __name__ == "__main__":
91:     # Example usage with multiple alpha values
92:     alphas = [0.05,0.1,0.15,0.2,0.25,0.3,0.4,0.5,0.6,0.7,0.8,0.9]  # Adjust as needed
93:     generate_final_matrices(
94:         main_dir='/select_headmask/headmask_newckpt/Llama-3-8B-Instruct-Gradient-1048k/vt_fraction0.998_top1.0_lastq64',
95:         output_dir='/select_headmask/headmask_newckpt/Llama-3-8B-Instruct-Gradient-1048k/vt_fraction0.998_top1.0_lastq64/final_metric',
96:         alphas=alphas,
97:         files_per_subfolder=50,
98:         seed=42  # Optional, set a random seed for reproducibility
99:     )
models/kv_cache.py SHA256 31bc956f4ac1f3f181176070e348bcdd4acd8267ed1285fa12d051da7a3c2c46
640:         q_last = query[:,:,-self.last_q:,:]
641:         k_trans = repeat_kv(new_k_cache[:,:,self.init_tokens:self.chunk_end-self.recent_tokens,:],self.num_key_value_groups).transpose(2,3)
642:         attn_last_ori = torch.matmul(q_last, k_trans) / math.sqrt(self.head_dim)
643:         attn_last_ori = torch.softmax(attn_last_ori,dim=-1).squeeze()
644:         attn_last_gqa = attn_last_ori.view(self.num_key_value_heads,self.num_key_value_groups,-1,attn_last_ori.shape[-1])
645:         attn_last_gqa = attn_last_gqa.mean(dim=1)
646:         attn_last = attn_last_gqa
647: 
648:         q_last_num = attn_last.shape[1]
649:         attn_last_flat = attn_last.view(attn_last.shape[0], -1).to(torch.float) 
650:         vmin = torch.quantile(attn_last_flat, 1-self.top_fraction, dim=1, keepdim=True).unsqueeze(2)
651:         vmax = torch.quantile(attn_last_flat, self.top_fraction, dim=1, keepdim=True).unsqueeze(2)
652:         vmin = vmin.repeat(1, q_last_num, 1)
653:         vmax = vmax.repeat(1, q_last_num, 1)
654: 
655:         threshold = vmin + (vmax - vmin) * self.top_threshold
656:         threshold = torch.clamp(threshold, min=1e-9)
657:         data_gt_threshold = attn_last > threshold
658: 
659:         chunks = data_gt_threshold.view(data_gt_threshold.size(0),data_gt_threshold.size(1),-1,self.chunk_size)
660:         chunk_mask = chunks.max(dim=3).values # (head_num,last_token,chunk_num)
661: 
662:         chunk_top_num = chunk_mask.sum(dim=1).float() # (head_num,chunk_num)
663: 
664:         
665:         # calculate cv
666:         self.chunk_top_num.append(chunk_top_num)
667:         top_mean_num = torch.mean(chunk_top_num,dim=1)
668:         top_std_num = torch.std(chunk_top_num,dim=1)
669:         top_mean_num[top_mean_num == 0] = 1e-10
670:         top_cv = top_std_num / top_mean_num 
671:         self.top_cv.append(top_cv)
672: 
673:         # register rest_idxed landmarks to k_landmark
674:         self.register_k_landmark(k_landmark_max, k_landmark_min)
675: 
676:         if layer_idx == self.num_layers - 1:
677:             assert self.sparse_budget < incoming
678:             self.kv_offset += incoming
679:             assert len(self.top_cv) == self.num_layers
680:             self.cv_threshold_one = torch.quantile(torch.stack(self.top_cv),self.cv_threshold)
681:             
682:             head_cls = torch.zeros(self.num_layers, self.num_key_value_heads)
683:             for layer_id in range(self.num_layers):
684:                 for head_id in range(self.num_key_value_heads):
685:                     head_cls[layer_id][head_id] = self.top_cv[layer_id][head_id].item()
686:             head_cls_np = head_cls.numpy()
687: 
688:             random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
689: 
690:             # save head_cls_np to csv
691:             save_head_dir = f'./select_headmask/headmask_new{self.model_name}/vt_fraction{self.top_fraction}_top{self.top_threshold}_lastq{self.last_q}'
692:             os.makedirs(save_head_dir, exist_ok=True)
693:             head_cls_file_path = os.path.join(save_head_dir, f"{random_string}_head_cls.csv")
694:             # 使用 pandas 保存为 CSV
695:             head_cls_df = pd.DataFrame(head_cls_np)
696:             head_cls_df.to_csv(head_cls_file_path, index=False, header=False)
985:             middle_v_cache = full_new_v_cache.gather(dim=2, index=position_ids_expanded)
986:             k = torch.cat([full_new_k_cache[:, :, :self.init_tokens, :], middle_k_cache, full_new_k_cache[:, :, self.chunk_end-self.recent_tokens:, :]],dim=2).clone()
987:             v = torch.cat([full_new_v_cache[:, :, :self.init_tokens, :], middle_v_cache, full_new_v_cache[:, :, self.chunk_end-self.recent_tokens:, :]],dim=2).clone()
988:             self.k_cache_full[layer_idx][self.prefilled_batch:self.prefilled_batch + bsz, :, :full_cache_num, :] = k
989:             self.v_cache_full[layer_idx][self.prefilled_batch:self.prefilled_batch + bsz, :, :full_cache_num, :] = v
990:         
991:         if len(sparse_heads) > 0:
992:             sparse_chunk_top_num = chunk_top_num[:,sparse_heads,:]
993:             chunk_top_indices = sparse_chunk_top_num.topk(k=self.select_sets,dim=-1).indices # (b,h,k)
994:             position_ids = (chunk_top_indices.unsqueeze(-1) * self.chunk_size + torch.arange(self.chunk_size, device=chunk_top_num.device)) 
995:             position_ids = position_ids.view(position_ids.size(0), len(sparse_heads), -1) + self.init_tokens
996:             sparse_new_k_cache = new_k_cache[:,sparse_heads,:,:]
997:             sparse_new_v_cache = new_v_cache[:,sparse_heads,:,:]
998:             position_ids_expanded = position_ids.unsqueeze(-1).expand(-1, -1, -1, sparse_new_k_cache.size(-1))  
999:             middle_k_cache = sparse_new_k_cache.gather(dim=2, index=position_ids_expanded)
1000:             middle_v_cache = sparse_new_v_cache.gather(dim=2, index=position_ids_expanded)
1001:             self.k_cache_sparse[layer_idx][self.prefilled_batch:self.prefilled_batch + bsz, :, :sparse_cache_num, :] = torch.cat([sparse_new_k_cache[:, :, :self.init_tokens, :], middle_k_cache, sparse_new_k_cache[:, :, self.chunk_end-self.recent_tokens:, :]],dim=2).clone()
1002:             self.v_cache_sparse[layer_idx][self.prefilled_batch:self.prefilled_batch + bsz, :, :sparse_cache_num, :] = torch.cat([sparse_new_v_cache[:, :, :self.init_tokens, :], middle_v_cache, sparse_new_v_cache[:, :, self.chunk_end-self.recent_tokens:, :]],dim=2).clone()
1003: 
1004:         if layer_idx == self.num_layers - 1:
1005:             self.prefilled_batch += bsz
1006:             assert self.sparse_budget < incoming
1007:             if self.prefilled_batch == self.batch_size:
1008:                 self.full_kv_offset += full_cache_num
1009:                 self.sparse_kv_offset += sparse_cache_num
1010:                 self.prefill = incoming
1011: 
1012:     def collect_kv(self, layer_idx, query_states):
1013: 
1014:         self.incoming_q_len = query_states.shape[-2]  
1015: 
1016:         full_head_query_index = self.full_query_head_indices[layer_idx]
1017:         sparse_head_query_index = self.sparse_query_head_indices[layer_idx]
1018: 
1019:         full_kv_offset = self.full_kv_offset if layer_idx == self.num_layers - 1 else self.full_kv_offset + self.incoming_q_len
1020:         full_k = self.k_cache_full[layer_idx][:,:,:full_kv_offset]
1021:         full_v = self.v_cache_full[layer_idx][:,:,:full_kv_offset]
1022:         sparse_kv_offset = self.sparse_kv_offset if layer_idx == self.num_layers - 1 else self.sparse_kv_offset + self.incoming_q_len
1023:         sparse_k = self.k_cache_sparse[layer_idx][:,:,:sparse_kv_offset]
1024:         sparse_v = self.v_cache_sparse[layer_idx][:,:,:sparse_kv_offset]
1025: 
1026:         return full_head_query_index, sparse_head_query_index, full_k.to('cuda:0'), full_v.to('cuda:0'), sparse_k.to('cuda:0'), sparse_v.to('cuda:0')
1027: 
1028:     def update_kv_cache(self, 
1029:             new_k_cache :torch.Tensor,
1030:             new_v_cache :torch.Tensor,
1031:             layer_idx :int,
1032:             ):
1033: 
1034:         incoming = new_k_cache.shape[-2]
1035: 
1036:         sparse_heads = self.sparse_head_indices[layer_idx]
1037:         full_heads = self.full_head_indices[layer_idx]
1038: 
1039:         full_new_k_cache = new_k_cache[:,full_heads,:,:]
1040:         full_new_v_cache = new_v_cache[:,full_heads,:,:]
1041:         sparse_new_k_cache = new_k_cache[:,sparse_heads,:,:]
1042:         sparse_new_v_cache = new_v_cache[:,sparse_heads,:,:]
1043:         
1044:         self.k_cache_full[layer_idx][:, :, self.full_kv_offset:self.full_kv_offset + incoming].copy_(full_new_k_cache)
1045:         self.v_cache_full[layer_idx][:, :, self.full_kv_offset:self.full_kv_offset + incoming].copy_(full_new_v_cache)
1046:         self.k_cache_sparse[layer_idx][:, :, self.sparse_kv_offset:self.sparse_kv_offset + incoming].copy_(sparse_new_k_cache)
1047:         self.v_cache_sparse[layer_idx][:, :, self.sparse_kv_offset:self.sparse_kv_offset + incoming].copy_(sparse_new_v_cache)
1048: 
1049:         if layer_idx == self.num_layers - 1:
1050:             self.full_kv_offset += incoming
1051:             self.sparse_kv_offset += incoming
1052:             self.gen_offset += incoming