
FILE end-to-end/prox_op.py
25: 
26: def process_weights(weight_matrix): 
27: 
28:     #  abs and signed
29:     abs_weights = torch.abs(weight_matrix)
30:     sign_mask = torch.sign(weight_matrix)  
31:     
32:     # Reorder descendingly
33:     sorted_weights, original_indices = torch.sort(abs_weights, descending=True, dim=1)
34:     
35:     return sorted_weights, sign_mask, original_indices
36: 
37: def apply_sign_mask(weights, sign_mask):
38:     return weights * sign_mask
39: 
40: def reorder_to_original(sorted_weights, original_indices):
41:     # Reorder back 
42:     k = sorted_weights.shape[0]
43:     row_indices = torch.arange(k).unsqueeze(1).expand_as(original_indices)
44:     reordered_weights = torch.zeros_like(sorted_weights)     # scatter    
45:     reordered_weights[row_indices, original_indices] = sorted_weights
46:     
47:     return reordered_weights
48: 
49: def soft_threshold_nonneg(x, tau):
50:     return torch.maximum(x - tau, torch.tensor(0.0, device=x.device))
51: 
52: def solve_prox_sorted_alternating(z, lamb, iter_num=100):
53:     w = torch.zeros_like(z)
54:     wprev = torch.zeros_like(z)
55:     for _ in range(iter_num):
56:         wprev.copy_(w)
57:         
58:         inter_term = lamb * (w[:, 0] * w[:, 1] + w[:, 1] * w[:, 2] + w[:, 2] * w[:, 0])
59:         w[:, 3] = soft_threshold_nonneg(z[:, 3], inter_term)
60:         
61:         inter_term = lamb * (w[:, 0] * w[:, 1] + w[:, 1] * w[:, 3] + w[:, 3] * w[:, 0])
62:         w[:, 2] = soft_threshold_nonneg(z[:, 2], inter_term)
63:         
64:         inter_term = lamb * (w[:, 0] * w[:, 2] + w[:, 2] * w[:, 3] + w[:, 3] * w[:, 0])
65:         w[:, 1] = soft_threshold_nonneg(z[:, 1], inter_term)
66:         
67:         inter_term = lamb * (w[:, 1] * w[:, 2] + w[:, 2] * w[:, 3] + w[:, 3] * w[:, 1])
68:         w[:, 0] = soft_threshold_nonneg(z[:, 0], inter_term)
69:         
70:         # Check for convergence
71:         if torch.sum(torch.abs(w - wprev)) < 1e-8:
72:             break
73: 
74:     return w
75: 
76: def solve_prox_sorted_alternating_top3(z, lamb, iter_num=100):
77:     w = torch.zeros_like(z)
78:     wprev = torch.zeros_like(z)
79: 
80:     for _ in range(iter_num):
81:         wprev.copy_(w)
82:         
83:         inter_term = lamb * (w[:, 0] * w[:, 1])
84:         w[:, 2] = soft_threshold_nonneg(z[:, 2], inter_term)
85:         
86:         inter_term = lamb * (w[:, 0] * w[:, 2])
87:         w[:, 1] = soft_threshold_nonneg(z[:, 1], inter_term)
88:         
89:         inter_term = lamb * (w[:, 1] * w[:, 2])
90:         w[:, 0] = soft_threshold_nonneg(z[:, 0], inter_term)
91:         
92:         # Check for convergence
93:         if torch.sum(torch.abs(w - wprev)) < 1e-8:
94:             break
95: 
96:     return w
97: 
98: 
99: def reg(w):
100:     w1 = w[:, 0]
101:     w2 = w[:, 1]
102:     w3 = w[:, 2]
103:     w4 = w[:, 3]
104:     return (torch.abs(w1 * w2 * w3) + torch.abs(w2 * w3 * w4) + torch.abs(w3 * w4 * w1) + torch.abs(w4 * w1 * w2))
105: 
106: def obj(w, z, lamb):
107:     return 0.5 * torch.norm(w - z, p=2, dim=1)**2 + lamb * reg(w)
108: 
109: def prox_op(weight_matrix, lambda_ = 0.1): # in this implementation, lambda could either be a value or tensor
110:     weight_matrix, m, n = reshape_weights(weight_matrix) # check
111:     sorted_weights, sign_mask, original_indices = process_weights(weight_matrix)
112:     
113:     del weight_matrix
114:     
115:     w2sparse = sorted_weights.clone()
116:     w2sparse[:, 2] = 0
117:     w2sparse[:, 3] = 0
118:     
119:     w3sparse = solve_prox_sorted_alternating_top3(sorted_weights, lambda_)
120:     w4sparse = solve_prox_sorted_alternating(sorted_weights, lambda_)
121: 
122:     obj_2sparse = obj(w2sparse, sorted_weights, lambda_)
123:     obj_3sparse = obj(w3sparse, sorted_weights, lambda_)
124:     obj_4sparse = obj(w4sparse, sorted_weights, lambda_)
125: 
126: 
127:     min_obj_values = torch.min(torch.stack([obj_2sparse, obj_3sparse, obj_4sparse]), dim=0)
128:     best_weights = torch.where(min_obj_values.indices.unsqueeze(1) == 0, w2sparse, 
129:                                 torch.where(min_obj_values.indices.unsqueeze(1) == 1, w3sparse, w4sparse))
130:     reordered_weights = reorder_to_original(best_weights, original_indices)
131: 
132:     signed_weights = apply_sign_mask(reordered_weights, sign_mask)
133: 
134:     sorted_weights = reshape_weights_back(signed_weights, m, n)
135:     del w2sparse, w3sparse, w4sparse
136:     return sorted_weights
137: 
138: 
139: def compute_mask_loss(model, loss, lambda2_ = 0.01):
140:     loss_mask = torch.tensor(0, dtype = loss.dtype, device = loss.device)
141:     for n, m in model.named_modules():
151:     weight = weight.view(-1, m) 
152:     w_mask = torch.zeros_like(weight)
153:     w_mask.scatter_(1, torch.topk(torch.abs(weight), n, dim = 1, largest = True)[1], True)
154:     weight = w_mask * weight
155:     weight = weight.view(dim[0], dim[1])
156:     return weight
157: 
158: def replace_weight(model, lambda_ = 0.1):
159:     for n, m in model.named_parameters():
160:         if "bias" not in n and ("k_proj" in n or "q_proj" in n or "v_proj" in n or "o_proj" in n or "up_proj" in n or "down_proj" in n or "gate_proj" in n or "out_proj" in n or "fc1" in n or "fc2" in n):
161:             m.data = prox_op(m.data, lambda_) 

FILE end-to-end/prox_linear.py
25:         return weight
26: 
27:     def custom_sign(self, x):
28:         return torch.where(x == 0, torch.tensor(1, dtype=x.dtype, device=x.device), torch.sign(x))
29: 
30:     def compute_proximal_loss(self):
31:         ratio = self.weight / (self.original_weight + config.epsilon * self.custom_sign(self.original_weight))# )
32:         diff = self.weight - self.original_weight
33:         product = ratio * diff        
34:         final = torch.norm(product, p=2) ** 2
48: def replace_prox_linear(model):
49:     with torch.no_grad():
50:         for name, m in model.named_children():
51:             if isinstance(m, nn.Linear) and ("bias" not in name and ("k_proj" in name or "v_proj" in name or "q_proj" in name or "o_proj" in name
52:                                              or "up_proj" in name or "down_proj" in name or "gate_proj" in name
53:                                              or "out_proj" in name or "fc1" in name or "fc2" in name)):
54:                 newlinear = ProxLinear(m.in_features, m.out_features, m.bias is not None, device = m.weight.device, dtype=m.weight.dtype)
55:                 newlinear.weight.data.copy_(m.weight.data)
56:                 newlinear.original_weight.copy_(m.weight.data)
57:                 if m.bias is not None:
58:                     newlinear.bias.data.copy_(m.bias.data)
59:                 setattr(model, name, newlinear)
60:             elif isinstance(m, torch.nn.LayerNorm):
61:                 pass
62:             else:
63:                 replace_prox_linear(m)

FILE end-to-end/main.py
46: 
47: args = parser.parse_args()
48: model_name = args.model
49: dataset_name = args.dataset
50: lr = args.learning_rate
51: dataset = load_dataset("allenai/c4", data_files="en/c4-train.00000-of-01024.json.gz")
52: ctx_len = args.ctx_len
53: samples = args.samples
54: batch_size = args.batch_size
55: epsilon = args.epsilon
56: 
57: config.lambda_ = args.lambda_value
58: config.epsilon = epsilon
59: config.lambda2_ = args.lambda2_value
60: config.project_lambda2 = args.project_lambda2
61: 
62: train_testvalid = dataset["train"].train_test_split(test_size=0.95, seed=42) # train 3563 on 0.99 # when data size is large, there might be memory outage, mostly 95
63: valid_test = train_testvalid["test"].train_test_split(test_size=0.999, seed=42) # valid 352
64: dataset = DatasetDict({
65:     'train': train_testvalid['train'].select(range(samples)), # 5x data, but 16x, in case of huggingface bug
66:     'validation': valid_test['train'].select(range(32)), # we prune at every checkpoint
67:     'test': valid_test['test']})
68: 
95: 
96: dataset_id = dataset_name
97: BASE_MODEL = model_name
98: 
99: if config.project_lambda2 == 1:
100:     repository_id = f"{BASE_MODEL.split('/')[1]}-{dataset_id}_sft_final_reg{regularizer}_{samples}_lr{lr}_len{ctx_len}_batch{batch_size}_lambdaone{config.lambda_}_lambdatwo{config.lambda2_}"
101: else:
102:     repository_id = f"{BASE_MODEL.split('/')[1]}-{dataset_id}_sft_final_{samples}_lr{lr}_len{ctx_len}_batch{batch_size}_lambda{config.lambda_}"
103: 
104: sft_config = SFTConfig(
105:     dataset_text_field="text",
106:     output_dir=repository_id,
107:     per_device_train_batch_size=batch_size,
108:     per_device_eval_batch_size=batch_size,
109:     max_seq_length=ctx_len,
110:     learning_rate=lr,
111:     num_train_epochs=1,
112:     optim="adamw_torch",
113:     warmup_ratio = 0.1, 

FILE end-to-end/patch_transformers_trainer.py
638:                             grad_norm = grad_norm.item()
639:                     else:
640:                         grad_norm = _grad_norm
641: 
642:                 self.optimizer.step()
643: 
644:                 # 2025: Amazon addition. 
645:                 ## Prox_OP
646:                 replace_weight(model, config.lambda_)
647:                 # End of Amazon addition.
648: 
649:                 self.control = self.callback_handler.on_optimizer_step(args, self.state, self.control)
650: 
787:                 "The model did not return a loss from the inputs, only the following keys: "
788:                 f"{','.join(outputs.keys())}. For reference, the inputs it received are {','.join(inputs.keys())}."
789:             )
790:         # We don't use .loss here since the model may return tuples instead of ModelOutput.
791:         loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
792:     # 2025: Amazon addition. 
793:     ## Prox_OP
794:     if config.project_lambda2 == 1:
795:         loss = loss + compute_mask_loss(model, loss, config.lambda2_)
796:     # End of Amazon addition.
797:     return (loss, outputs) if return_outputs else loss
798: 
799: 
800: ######## functioning

FILE script/learn_mask_llama2_13b_full.sh
1: model_dir=meta-llama
2: model_subdir=Llama-2-13b
3: lambda_=0.5
4: lambda2_=0.25
5: project_lambda2=1
6: epsilon=0.5
7: batch_size=1
8: ctx_len=4096
9: samples=400 # this is related to the final checkpoint dir name
10: lr=1e-04
11: checkpoint=$samples
12: 
13: DIR="${model_subdir}-en_sft_final_reg${epsilon}_${samples}_lr${lr}_len${ctx_len}_batch${batch_size}_lambdaone${lambda_}_lambdatwo${lambda2_}"
14: echo -e "Starting learning mask with ProxSparse" 
15: # Mask Learning
16: CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 python end-to-end/main.py --model "${model_dir}/${model_subdir}" --lambda_value $lambda_ --lambda2_value $lambda2_ --project_lambda2 $project_lambda2 --ctx_len $ctx_len --batch_size $batch_size --samples $samples  --epsilon $epsilon --learning_rate $lr
17: 
18: # checking mask
19: echo -e "Finished learning, now extracting binary mask. Mask stored in proximal_* directory" 
20: python end-to-end/mask_op.py --model "$DIR/checkpoint-$checkpoint" >> prune_sparsity.txt
21: 
22: # Apply mask
23: echo -e "Applying mask to the original model, evaluate on C4 PPL" 
24: python eval/eval_mask_ppl.py --mask "$DIR/checkpoint-$checkpoint" --model "${model_dir}/${model_subdir}" --method else --ctx_len 4096 >> prune_full_iteration.txt
25: 

FILE eval/eval_mask_ppl.py
282: 
283: 
284: mask_set = []
285: def loop_lambda(model):
286:     for n, m in model.named_parameters():
287:         if "bias" not in n and ("k_proj" in n or "q_proj" in n or "v_proj" in n or "o_proj" in n or "up_proj" in n or "down_proj" in n or "gate_proj" in n or "out_proj" in n or "fc1" in n or "fc2" in n):
288:             # import ipdb; ipdb.set_trace()
289:             if method == "projected":
290:                 mask = torch.load(f"./projected_mask/{n}.pt")
291:                 mask_set.append(mask.bool())
292:             if method == "proximal":
293:                 mask = torch.load(f"./proximal_mask/{n}.pt")
294:                 mask_set.append(mask.bool())
295:             if method == "else":
296:                 mask = torch.load(f"./proximal_{mask_name}/{n}.pt")
297:                 mask_set.append(mask.bool())
298: loop_lambda(model)
299: 
300: from torch.nn import Linear
301: import torch.nn as nn
302: import torch.nn.functional as F
303: class ProxLinear(Linear):
304:     def __init__(self, in_features, out_features, bias=True, device=None, dtype=None, mask=None):
305:         super(ProxLinear, self).__init__(in_features, out_features, bias, device=device, dtype=dtype)
306:         self.mask = mask # inverse
307: 
308:     def forward(self, input):
309:         qw = self.weight * self.mask
310:         return F.linear(input, qw, self.bias)
311:         
312: 
313: 
314:     def modify_weight(self, weight, mask):
315:         qw = weight * mask
316:         return qw
317: 
318:     def sparsify_magnitude(self, weight, n, m): 
319:         dim = weight.shape
320:         weight = weight.view(-1, m) 
321:         w_mask = torch.zeros_like(weight)
322:         w_mask.scatter_(1, torch.topk(torch.abs(weight), n, dim = 1, largest = True)[1], True)
323:         weight = w_mask * weight
324:         weight = weight.view(dim[0], dim[1])
325:         return weight
326:     
327:     
328: def replace_linear(model):
329:     with torch.no_grad():
330:         for name, m in model.named_children():
331:             if isinstance(m, nn.Linear) and ("bias" not in name and ("k_proj" in name or "v_proj" in name or "q_proj" in name or "o_proj" in name
332:                                              or "up_proj" in name or "down_proj" in name or "gate_proj" in name or "out_proj" in name or "fc1" in name or "fc2" in name)):
333:                 newlinear = ProxLinear(m.in_features, m.out_features, m.bias is not None, device = m.weight.device, dtype=m.weight.dtype, mask = (mask_set[0]).to(m.weight.device).to(m.weight.dtype))
334:                 del mask_set[0]
335:                 newlinear.weight.data.copy_(m.weight.data * newlinear.mask) 
336:                 if m.bias is not None:
337:                     newlinear.bias.data.copy_(m.bias.data)
338:                 setattr(model, name, newlinear)
339:             elif isinstance(m, torch.nn.LayerNorm):
340:                 pass
341:             else:
342:                 replace_linear(m)
343: 

FILE end-to-end/mask_op.py
22: 
23: 
24: def explicit_sparsify_magnitude_row(weight, n, m): # prune and leave n out of m in 2d array
25:     dim = weight.shape
26:     weight = weight.view(-1, m) # for a 2d array, reshale into 4 blocks
27:     w_mask = torch.zeros_like(weight)
28:     w_mask.scatter_(1, torch.topk(torch.abs(weight), n, dim = 1, largest = True)[1], True)
29:     w_mask = w_mask.view(dim[0], dim[1])
30:     return w_mask
72:         one_sparse += num_zeros_1
73:         two_sparse += num_zeros_2
74:         three_sparse += num_zeros_3
75: 
76:         mask = explicit_sparsify_magnitude_row(m, 2, 4)
77:         if not os.path.isdir(f"./proximal_{model_name.split('/')[0]}"):
78:             os.mkdir(f"./proximal_{model_name.split('/')[0]}")
79:         if not os.path.isdir(f"./proximal_{model_name}"):
80:             os.mkdir(f"./proximal_{model_name}")
81:         torch.save(mask, f"./proximal_{model_name}/{n}.pt")
82: 