optipfair 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cli/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """
2
+ CLI package for OptiPFair.
3
+ """
4
+
5
+ from .commands import cli
6
+
7
+ __all__ = ["cli"]
cli/commands.py ADDED
@@ -0,0 +1,209 @@
1
+ """
2
+ Command-line interface for OptiPFair.
3
+
4
+ This module provides the CLI commands for pruning models and related operations.
5
+ """
6
+
7
+ import click
8
+ import logging
9
+ import os
10
+ from transformers import AutoModelForCausalLM, AutoTokenizer
11
+ import torch
12
+
13
+ from .. import prune_model
14
+ from ..pruning.utils import count_parameters
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ @click.group()
19
+ def cli():
20
+ """OptiPFair: A library for structured pruning of large language models."""
21
+ pass
22
+
23
+ @cli.command()
24
+ @click.option('--model-path', required=True, help='Path or identifier of the model to prune.')
25
+ @click.option('--pruning-type', default='MLP_GLU', type=click.Choice(['MLP_GLU']),
26
+ help='Type of pruning to apply.')
27
+ @click.option('--method', default='MAW', type=click.Choice(['MAW', 'VOW', 'PON']),
28
+ help='Method to calculate neuron importance.')
29
+ @click.option('--pruning-percentage', default=None, type=float,
30
+ help='Percentage of neurons to prune (0-100).')
31
+ @click.option('--expansion-rate', default=None, type=float,
32
+ help='Target expansion rate in percentage (mutually exclusive with pruning-percentage).')
33
+ @click.option('--output-path', required=True, help='Path to save the pruned model.')
34
+ @click.option('--device', default='auto', help='Device to use for computation (auto, cpu, cuda, cuda:0, etc.)')
35
+ @click.option('--dtype', default='auto', type=click.Choice(['auto', 'float32', 'float16', 'bfloat16']),
36
+ help='Data type to load the model with.')
37
+ @click.option('--verbose/--quiet', default=True, help='Whether to show verbose output.')
38
+ def prune(model_path, pruning_type, method, pruning_percentage, expansion_rate,
39
+ output_path, device, dtype, verbose):
40
+ """Prune a language model using the specified parameters."""
41
+ # Configure logging based on verbosity
42
+ log_level = logging.INFO if verbose else logging.WARNING
43
+ logging.basicConfig(level=log_level, format='%(message)s')
44
+
45
+ # Validate inputs
46
+ if pruning_percentage is not None and expansion_rate is not None:
47
+ raise click.UsageError("--pruning-percentage and --expansion-rate are mutually exclusive.")
48
+
49
+ if pruning_percentage is None and expansion_rate is None:
50
+ pruning_percentage = 10
51
+ logger.info(f"No pruning target specified, defaulting to {pruning_percentage}% pruning.")
52
+
53
+ # Determine device
54
+ if device == 'auto':
55
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
56
+
57
+ # Determine dtype
58
+ if dtype == 'auto':
59
+ if 'cuda' in device and torch.cuda.is_available():
60
+ if torch.cuda.get_device_capability()[0] >= 8: # Ampere or newer
61
+ dtype = torch.bfloat16
62
+ else:
63
+ dtype = torch.float16
64
+ else:
65
+ dtype = torch.float32
66
+ else:
67
+ dtype_map = {
68
+ 'float32': torch.float32,
69
+ 'float16': torch.float16,
70
+ 'bfloat16': torch.bfloat16,
71
+ }
72
+ dtype = dtype_map[dtype]
73
+
74
+ logger.info(f"Loading model from {model_path} to {device} with {dtype}")
75
+
76
+ # Load model and tokenizer
77
+ try:
78
+ model = AutoModelForCausalLM.from_pretrained(
79
+ model_path,
80
+ torch_dtype=dtype,
81
+ device_map=device
82
+ )
83
+ tokenizer = AutoTokenizer.from_pretrained(model_path)
84
+ except Exception as e:
85
+ logger.error(f"Error loading model: {str(e)}")
86
+ raise
87
+
88
+ # Log original model parameters
89
+ original_params = count_parameters(model)
90
+ logger.info(f"Original model parameters: {original_params:,}")
91
+
92
+ # Apply pruning
93
+ logger.info(f"Pruning model with {pruning_type} pruning, {method} neuron selection method")
94
+ if pruning_percentage is not None:
95
+ logger.info(f"Target: {pruning_percentage}% reduction in neurons")
96
+ else:
97
+ logger.info(f"Target: {expansion_rate}% expansion rate")
98
+
99
+ pruned_model, stats = prune_model(
100
+ model=model,
101
+ pruning_type=pruning_type,
102
+ neuron_selection_method=method,
103
+ pruning_percentage=pruning_percentage,
104
+ expansion_rate=expansion_rate,
105
+ show_progress=verbose,
106
+ return_stats=True,
107
+ )
108
+
109
+ # Log pruning statistics
110
+ logger.info("Pruning complete!")
111
+ logger.info(f"Original parameters: {stats['original_parameters']:,}")
112
+ logger.info(f"Pruned parameters: {stats['pruned_parameters']:,}")
113
+ logger.info(f"Reduction: {stats['reduction']:,} parameters ({stats['percentage_reduction']:.2f}%)")
114
+
115
+ if stats['expansion_rate'] is not None:
116
+ logger.info(f"Final expansion rate: {stats['expansion_rate']:.2f}%")
117
+
118
+ # Create output directory if it doesn't exist
119
+ os.makedirs(output_path, exist_ok=True)
120
+
121
+ # Save model and tokenizer
122
+ logger.info(f"Saving pruned model to {output_path}")
123
+ pruned_model.save_pretrained(output_path)
124
+ tokenizer.save_pretrained(output_path)
125
+
126
+ logger.info("Done!")
127
+
128
+ @cli.command()
129
+ @click.option('--model-path', required=True, help='Path or identifier of the model to analyze.')
130
+ @click.option('--device', default='auto', help='Device to use for computation (auto, cpu, cuda, cuda:0, etc.)')
131
+ def analyze(model_path, device):
132
+ """Analyze a model's architecture and parameter distribution."""
133
+ # Configure logging
134
+ logging.basicConfig(level=logging.INFO, format='%(message)s')
135
+
136
+ # Determine device
137
+ if device == 'auto':
138
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
139
+
140
+ logger.info(f"Loading model from {model_path} to {device}")
141
+
142
+ # Load model
143
+ try:
144
+ model = AutoModelForCausalLM.from_pretrained(
145
+ model_path,
146
+ device_map=device
147
+ )
148
+ except Exception as e:
149
+ logger.error(f"Error loading model: {str(e)}")
150
+ raise
151
+
152
+ # Log basic model information
153
+ total_params = count_parameters(model)
154
+ logger.info(f"Model: {model_path}")
155
+ logger.info(f"Total parameters: {total_params:,}")
156
+
157
+ # Try to identify model architecture
158
+ from ..pruning.utils import get_model_layers, validate_model_for_glu_pruning
159
+
160
+ layers = get_model_layers(model)
161
+ logger.info(f"Number of layers: {len(layers)}")
162
+
163
+ # Check if model is compatible with GLU pruning
164
+ is_glu_compatible = validate_model_for_glu_pruning(model)
165
+ logger.info(f"Compatible with GLU pruning: {is_glu_compatible}")
166
+
167
+ if is_glu_compatible and layers:
168
+ # Get information about the first layer
169
+ first_layer = layers[0]
170
+ mlp = first_layer.mlp
171
+
172
+ hidden_size = mlp.gate_proj.in_features
173
+ intermediate_size = mlp.gate_proj.out_features
174
+ expansion_ratio = intermediate_size / hidden_size
175
+
176
+ logger.info(f"Hidden size: {hidden_size}")
177
+ logger.info(f"Intermediate size: {intermediate_size}")
178
+ logger.info(f"Expansion ratio: {expansion_ratio:.2f}x ({expansion_ratio*100:.2f}%)")
179
+
180
+ # Parameter distribution
181
+ attn_params = sum(p.numel() for name, p in first_layer.named_parameters() if 'self_attn' in name)
182
+ mlp_params = sum(p.numel() for name, p in first_layer.named_parameters() if 'mlp' in name)
183
+ other_params = sum(p.numel() for name, p in first_layer.named_parameters()
184
+ if 'self_attn' not in name and 'mlp' not in name)
185
+
186
+ # Extrapolate to whole model
187
+ total_layer_params = attn_params + mlp_params + other_params
188
+ attn_percentage = (attn_params / total_layer_params) * 100
189
+ mlp_percentage = (mlp_params / total_layer_params) * 100
190
+ other_percentage = (other_params / total_layer_params) * 100
191
+
192
+ logger.info("\nParameter distribution per layer:")
193
+ logger.info(f"Attention: {attn_params:,} ({attn_percentage:.2f}%)")
194
+ logger.info(f"MLP: {mlp_params:,} ({mlp_percentage:.2f}%)")
195
+ logger.info(f"Other: {other_params:,} ({other_percentage:.2f}%)")
196
+
197
+ # Estimate potential parameter savings
198
+ for prune_percent in [10, 20, 30, 40, 50]:
199
+ new_intermediate_size = intermediate_size * (1 - prune_percent/100)
200
+ new_expansion_ratio = new_intermediate_size / hidden_size
201
+ param_reduction = (intermediate_size - new_intermediate_size) * (hidden_size + mlp.down_proj.out_features)
202
+ model_reduction_percent = (param_reduction * len(layers)) / total_params * 100
203
+
204
+ logger.info(f"\nWith {prune_percent}% MLP neuron pruning:")
205
+ logger.info(f" New expansion ratio: {new_expansion_ratio:.2f}x ({new_expansion_ratio*100:.2f}%)")
206
+ logger.info(f" Estimated parameter reduction: {model_reduction_percent:.2f}% of model")
207
+
208
+ if __name__ == '__main__':
209
+ cli()
evaluation/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """
2
+ Evaluation package for OptiPFair.
3
+
4
+ This package provides evaluation utilities for assessing pruned models.
5
+ """
@@ -0,0 +1,157 @@
1
+ """
2
+ Benchmarking utilities for evaluating pruned models.
3
+
4
+ This module provides tools for evaluating the performance of pruned models
5
+ on standard benchmarks like LAMBADA, BoolQ, etc.
6
+ """
7
+
8
+ import logging
9
+ from typing import Dict, List, Any, Union, Optional
10
+ import time
11
+ import torch
12
+ from transformers import PreTrainedModel, AutoTokenizer
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ def time_inference(
17
+ model: PreTrainedModel,
18
+ tokenizer: AutoTokenizer,
19
+ prompt: str,
20
+ max_new_tokens: int = 100,
21
+ num_runs: int = 5,
22
+ warmup_runs: int = 2,
23
+ ) -> Dict[str, Any]:
24
+ """
25
+ Measure inference time for a model.
26
+
27
+ Args:
28
+ model: Model to evaluate
29
+ tokenizer: Tokenizer to use
30
+ prompt: Input prompt for generation
31
+ max_new_tokens: Maximum number of tokens to generate
32
+ num_runs: Number of inference runs to average over
33
+ warmup_runs: Number of initial runs to discard (for warm-up)
34
+
35
+ Returns:
36
+ Dictionary containing timing results
37
+ """
38
+ # Prepare input
39
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
40
+
41
+ # Warmup runs
42
+ for _ in range(warmup_runs):
43
+ with torch.no_grad():
44
+ _ = model.generate(
45
+ inputs.input_ids,
46
+ max_new_tokens=max_new_tokens,
47
+ do_sample=False,
48
+ )
49
+
50
+ # Timed runs
51
+ times = []
52
+ for _ in range(num_runs):
53
+ start_time = time.time()
54
+ with torch.no_grad():
55
+ output = model.generate(
56
+ inputs.input_ids,
57
+ max_new_tokens=max_new_tokens,
58
+ do_sample=False,
59
+ )
60
+ end_time = time.time()
61
+ times.append(end_time - start_time)
62
+
63
+ generated_tokens = output.size(1) - inputs.input_ids.size(1)
64
+
65
+ return {
66
+ "avg_time": sum(times) / len(times),
67
+ "min_time": min(times),
68
+ "max_time": max(times),
69
+ "tokens_per_second": generated_tokens / (sum(times) / len(times)),
70
+ "num_runs": num_runs,
71
+ "generated_tokens": generated_tokens,
72
+ }
73
+
74
+ def compare_models_inference(
75
+ original_model: PreTrainedModel,
76
+ pruned_model: PreTrainedModel,
77
+ tokenizer: AutoTokenizer,
78
+ prompts: List[str],
79
+ max_new_tokens: int = 100,
80
+ ) -> Dict[str, Any]:
81
+ """
82
+ Compare inference performance between original and pruned models.
83
+
84
+ Args:
85
+ original_model: Original model before pruning
86
+ pruned_model: Model after pruning
87
+ tokenizer: Tokenizer to use
88
+ prompts: List of input prompts for generation
89
+ max_new_tokens: Maximum number of tokens to generate
90
+
91
+ Returns:
92
+ Dictionary containing comparison results
93
+ """
94
+ # Ensure models are in eval mode
95
+ original_model.eval()
96
+ pruned_model.eval()
97
+
98
+ original_results = []
99
+ pruned_results = []
100
+
101
+ for prompt in prompts:
102
+ logger.info(f"Testing prompt: {prompt[:50]}...")
103
+
104
+ original_timing = time_inference(
105
+ original_model, tokenizer, prompt, max_new_tokens
106
+ )
107
+ original_results.append(original_timing)
108
+
109
+ pruned_timing = time_inference(
110
+ pruned_model, tokenizer, prompt, max_new_tokens
111
+ )
112
+ pruned_results.append(pruned_timing)
113
+
114
+ # Aggregate results
115
+ avg_original_time = sum(r["avg_time"] for r in original_results) / len(original_results)
116
+ avg_pruned_time = sum(r["avg_time"] for r in pruned_results) / len(pruned_results)
117
+
118
+ avg_original_tps = sum(r["tokens_per_second"] for r in original_results) / len(original_results)
119
+ avg_pruned_tps = sum(r["tokens_per_second"] for r in pruned_results) / len(pruned_results)
120
+
121
+ speedup = avg_original_time / avg_pruned_time if avg_pruned_time > 0 else float('inf')
122
+ tps_improvement = (avg_pruned_tps / avg_original_tps - 1) * 100 if avg_original_tps > 0 else float('inf')
123
+
124
+ return {
125
+ "avg_original_time": avg_original_time,
126
+ "avg_pruned_time": avg_pruned_time,
127
+ "avg_original_tokens_per_second": avg_original_tps,
128
+ "avg_pruned_tokens_per_second": avg_pruned_tps,
129
+ "speedup": speedup,
130
+ "tps_improvement_percent": tps_improvement,
131
+ "num_prompts": len(prompts),
132
+ }
133
+
134
+ # Note: This is a placeholder for future implementation
135
+ def evaluate_on_lm_benchmarks(
136
+ model: PreTrainedModel,
137
+ benchmarks: List[str] = ["lambada", "boolq"],
138
+ num_few_shot: int = 0,
139
+ ) -> Dict[str, Any]:
140
+ """
141
+ Placeholder for evaluating a model on language modeling benchmarks.
142
+
143
+ Args:
144
+ model: Model to evaluate
145
+ benchmarks: List of benchmarks to evaluate on
146
+ num_few_shot: Number of few-shot examples to use
147
+
148
+ Returns:
149
+ Dictionary containing benchmark results
150
+ """
151
+ logger.warning("LM benchmark evaluation not implemented yet. Will be added in a future version.")
152
+
153
+ # This would use libraries like lm-eval-harness, EleutherAI's evaluation framework, etc.
154
+ return {
155
+ "message": "Not implemented yet",
156
+ "benchmarks": benchmarks,
157
+ }
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2025] [Pere Martra]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,174 @@
1
+ Metadata-Version: 2.1
2
+ Name: optipfair
3
+ Version: 0.1.0
4
+ Summary: A library for structured pruning & Bias visualization of large language models
5
+ Home-page: https://github.com/peremartra/optipfair
6
+ Author: Pere Martra
7
+ Author-email: peremartra@uadla.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: torch >=1.10.0
18
+ Requires-Dist: transformers >=4.25.0
19
+ Requires-Dist: tqdm >=4.62.0
20
+ Requires-Dist: click >=8.0.0
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest >=7.0.0 ; extra == 'dev'
23
+ Requires-Dist: black >=22.0.0 ; extra == 'dev'
24
+ Requires-Dist: flake8 >=4.0.0 ; extra == 'dev'
25
+ Requires-Dist: isort >=5.10.0 ; extra == 'dev'
26
+ Requires-Dist: mypy >=0.900 ; extra == 'dev'
27
+ Provides-Extra: eval
28
+ Requires-Dist: datasets >=2.0.0 ; extra == 'eval'
29
+ Requires-Dist: numpy >=1.20.0 ; extra == 'eval'
30
+ Requires-Dist: pandas >=1.3.0 ; extra == 'eval'
31
+ Requires-Dist: matplotlib >=3.5.0 ; extra == 'eval'
32
+ Requires-Dist: seaborn >=0.11.0 ; extra == 'eval'
33
+
34
+ # OptiPFair
35
+
36
+ A Python library for structured pruning of large language models, with a focus on GLU architectures.
37
+
38
+ ## Overview
39
+
40
+ OptiPFair enables efficient pruning of large language models while maintaining their performance. It implements various structured pruning methods, starting with MLP pruning for GLU architectures (as used in models like LLaMA, Mistral, etc.).
41
+
42
+ Key features:
43
+ - GLU architecture-aware pruning that preserves model structure
44
+ - Multiple neuron importance calculation methods
45
+ - Support for both pruning percentage and target expansion rate
46
+ - Simple Python API and CLI interface
47
+ - Progress tracking and detailed statistics
48
+
49
+ ## Installation
50
+
51
+ ```bash
52
+ # From PyPI (not yet available)
53
+ pip install optipfair
54
+
55
+ # From source
56
+ git clone https://github.com/yourusername/optipfair.git
57
+ cd optipfair
58
+ pip install -e .
59
+ ```
60
+
61
+ ## Quick Start
62
+
63
+ ### Python API
64
+
65
+ ```python
66
+ from transformers import AutoModelForCausalLM
67
+ from optipfair import prune_model
68
+
69
+ # Load a pre-trained model
70
+ model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-3.2-1B")
71
+
72
+ # Prune 20% of neurons from MLP layers using MAW method
73
+ pruned_model, stats = prune_model(
74
+ model=model,
75
+ pruning_type="MLP_GLU",
76
+ neuron_selection_method="MAW",
77
+ pruning_percentage=20,
78
+ show_progress=True,
79
+ return_stats=True
80
+ )
81
+
82
+ # Print pruning statistics
83
+ print(f"Original parameters: {stats['original_parameters']:,}")
84
+ print(f"Pruned parameters: {stats['pruned_parameters']:,}")
85
+ print(f"Reduction: {stats['reduction']:,} parameters ({stats['percentage_reduction']:.2f}%)")
86
+
87
+ # Save pruned model
88
+ pruned_model.save_pretrained("./pruned-llama-model")
89
+ ```
90
+
91
+ ### Command-Line Interface
92
+
93
+ ```bash
94
+ # Prune a model with default settings (10% pruning, MAW method)
95
+ optipfair prune --model-path meta-llama/Llama-3.2-1B --output-path ./pruned-model
96
+
97
+ # Prune with custom settings
98
+ optipfair prune \
99
+ --model-path meta-llama/Llama-3.2-1B \
100
+ --pruning-type MLP_GLU \
101
+ --method MAW \
102
+ --pruning-percentage 20 \
103
+ --output-path ./pruned-model
104
+
105
+ # Use expansion rate instead of pruning percentage
106
+ optipfair prune \
107
+ --model-path meta-llama/Llama-3.2-1B \
108
+ --expansion-rate 140 \
109
+ --output-path ./pruned-model
110
+
111
+ # Analyze a model's architecture
112
+ optipfair analyze --model-path meta-llama/Llama-3.2-1B
113
+ ```
114
+
115
+ ## Neuron Selection Methods
116
+
117
+ OptiPFair supports three methods for calculating neuron importance:
118
+
119
+ 1. **MAW (Maximum Absolute Weight)** - Default method that identifies influential neurons based on the magnitude of their connections. Typically provides the best pruning results.
120
+
121
+ 2. **VOW (Variance of Weights)** - Identifies neurons based on the variance of their weights. May be useful for specific architectures.
122
+
123
+ 3. **PON (Product of Norms)** - Uses the product of L1 norms to identify important neurons. This method may be applicable in certain contexts.
124
+
125
+ ## Documentation
126
+
127
+ Complete documentation is available at [https://yourusername.github.io/optipfair/](https://yourusername.github.io/optipfair/).
128
+
129
+ ## Supported Models
130
+
131
+ OptiPFair is designed to work with transformer-based language models that use GLU architecture in their MLP layers, including:
132
+
133
+ - LLaMA family (LLaMA, LLaMA-2, LLaMA-3)
134
+ - Mistral models
135
+ - And other models with similar GLU architecture
136
+
137
+ ## Expansion Rate vs Pruning Percentage
138
+
139
+ OptiPFair supports two ways to specify the pruning target:
140
+
141
+ 1. **Pruning Percentage** - Directly specify what percentage of neurons to remove (e.g., 20%)
142
+
143
+ 2. **Expansion Rate** - Specify the target expansion rate (ratio of intermediate size to hidden size) as a percentage (e.g., 140% instead of the default 400%)
144
+
145
+ The expansion rate approach is often more intuitive when comparing across different model scales.
146
+
147
+ ## Future Roadmap
148
+
149
+ - Support for attention layer pruning
150
+ - Whole block pruning
151
+ - Quantization-aware pruning
152
+ - Integrated evaluation benchmarks
153
+ - Iterative pruning capabilities
154
+
155
+ ## Citation
156
+
157
+ If you use OptiPFair in your research, please cite:
158
+
159
+ ```
160
+ @software{optipfair2025,
161
+ author = {Pere Martra},
162
+ title = {OptiPFair: A Library for Structured Pruning of Large Language Models},
163
+ year = {2025},
164
+ url = {https://github.com/yourusername/optipfair}
165
+ }
166
+ ```
167
+
168
+ ## License
169
+
170
+ Apache 2.0
171
+
172
+ ## Contributing
173
+
174
+ Contributions are welcome! Please check out our [contributing guidelines](CONTRIBUTING.md) for details.
@@ -0,0 +1,16 @@
1
+ cli/__init__.py,sha256=zXFlgks4qK6E94fExZsJToZIMkEgcBWcSpKKL0vhjjw,80
2
+ cli/commands.py,sha256=tVc0cRvqriWqjXAfnQwXuaslaip33k0POjy06AxUU90,8716
3
+ evaluation/__init__.py,sha256=4Bv7kFHji5lP6LnlcbYtwBrnw8MC7MUwRY85Y2-RgNg,114
4
+ evaluation/benchmarks.py,sha256=lb603AqR7udHA8ru9hKd3eDfV_Pp7Aa-KUXStloEvro,5054
5
+ pruning/__init__.py,sha256=t86KAxqZluSXz4Cz2LofmQpsf8o7thGUcejKOUL7q6o,425
6
+ pruning/mlp_glu.py,sha256=8r7idI_2Dzey16dZ4Q2No0CGj8YRNpRkKYR51koSM0A,10338
7
+ pruning/utils.py,sha256=RlyHmomzrwaRNGhSbUV5-7Lm4mMFCDJM521-zDvfdu4,5051
8
+ pruning/future_extensions/__init__.py,sha256=TJIpxmqHPXBKFaTskK-O9sScAkBWa4_SrteOgk1-oLc,130
9
+ pruning/future_extensions/attention.py,sha256=K-BAgoUpTGyQIoDVfilxbiNA4NBHuQ3MZCm0N_5xLzw,697
10
+ pruning/future_extensions/block.py,sha256=AvOvXYOqKQuCH5-Q4V2T6sM0nLbGVgx1r7q7PEwPLDI,678
11
+ optipfair-0.1.0.dist-info/LICENSE,sha256=jePzZyOOJNMJn9MaXviqb7sKrkuNFnrtMwnBYs22Ilc,11345
12
+ optipfair-0.1.0.dist-info/METADATA,sha256=9ikleULsAieZbljpwv5GtAAWnTbspN2VR5oybtouGSQ,5583
13
+ optipfair-0.1.0.dist-info/WHEEL,sha256=iAkIy5fosb7FzIOwONchHf19Qu7_1wCWyFNR5gu9nU0,91
14
+ optipfair-0.1.0.dist-info/entry_points.txt,sha256=g_jYd69Iz2iPaddlBoXx99W4ATZ8_fQQYRKP0BwYa2s,48
15
+ optipfair-0.1.0.dist-info/top_level.txt,sha256=m910PciT6fKdznCidcHuUZ1K4vxhQprVnpnSm-pBCzs,23
16
+ optipfair-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.3.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ optipfair = optipfair.cli:cli
@@ -0,0 +1,3 @@
1
+ cli
2
+ evaluation
3
+ pruning
pruning/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """
2
+ Pruning package for OptiPFair.
3
+
4
+ This package provides various pruning methods for transformer-based models.
5
+ """
6
+
7
+ from .mlp_glu import prune_model_mlp_glu
8
+ from .utils import validate_model_for_glu_pruning, get_model_layers, count_parameters, get_pruning_statistics
9
+
10
+ __all__ = [
11
+ "prune_model_mlp_glu",
12
+ "validate_model_for_glu_pruning",
13
+ "get_model_layers",
14
+ "count_parameters",
15
+ "get_pruning_statistics",
16
+ ]
@@ -0,0 +1,5 @@
1
+ """
2
+ Future extensions for OptiPFair pruning methods.
3
+
4
+ This package will contain additional pruning methods in future releases.
5
+ """
@@ -0,0 +1,20 @@
1
+ """
2
+ Attention module pruning (placeholder for future implementation).
3
+
4
+ This module will implement pruning techniques for attention layers in transformer models.
5
+ """
6
+
7
+ # This is a placeholder file for future implementation
8
+ def prune_attention_heads(model, head_importance_method="ATTENTION_WEIGHTS", prune_percentage=10):
9
+ """
10
+ Placeholder for future implementation of attention head pruning.
11
+
12
+ Args:
13
+ model: Model to prune
14
+ head_importance_method: Method to calculate head importance
15
+ prune_percentage: Percentage of heads to prune
16
+
17
+ Returns:
18
+ model: Pruned model
19
+ """
20
+ raise NotImplementedError("Attention pruning is not yet implemented.")
@@ -0,0 +1,20 @@
1
+ """
2
+ Block-level pruning (placeholder for future implementation).
3
+
4
+ This module will implement pruning techniques for entire transformer blocks.
5
+ """
6
+
7
+ # This is a placeholder file for future implementation
8
+ def prune_transformer_blocks(model, block_importance_method="PERPLEXITY", prune_percentage=10):
9
+ """
10
+ Placeholder for future implementation of transformer block pruning.
11
+
12
+ Args:
13
+ model: Model to prune
14
+ block_importance_method: Method to calculate block importance
15
+ prune_percentage: Percentage of blocks to prune
16
+
17
+ Returns:
18
+ model: Pruned model
19
+ """
20
+ raise NotImplementedError("Block pruning is not yet implemented.")
pruning/mlp_glu.py ADDED
@@ -0,0 +1,251 @@
1
+ """
2
+ MLPGLUPruning - Module for pruning MLP layers with GLU architecture in transformer models.
3
+
4
+ This module provides functionality to prune neurons in MLP layers that follow the
5
+ Gated Linear Unit (GLU) architecture, as used in models like LLaMA. The pruning
6
+ is structured to maintain the paired nature of gate_proj and up_proj layers.
7
+ """
8
+
9
+ import torch
10
+ from torch import nn
11
+ import logging
12
+ from typing import Tuple, Dict, List, Optional, Callable, Union, Any
13
+ from tqdm import tqdm
14
+ from transformers import PreTrainedModel
15
+
16
+ from .utils import validate_model_for_glu_pruning, get_model_layers
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ def compute_neuron_pair_importance_maw(gate_weight: torch.Tensor, up_weight: torch.Tensor) -> torch.Tensor:
21
+ """
22
+ Compute neuron pair importance scores using Maximum Absolute Weight method.
23
+
24
+ Args:
25
+ gate_weight: Weight matrix from the gate_proj layer
26
+ up_weight: Weight matrix from the up_proj layer
27
+
28
+ Returns:
29
+ importance_scores: Importance scores for each neuron pair
30
+ """
31
+ gate_max_abs = torch.max(gate_weight, dim=1).values + torch.abs(torch.min(gate_weight, dim=1).values)
32
+ up_max_abs = torch.max(up_weight, dim=1).values + torch.abs(torch.min(up_weight, dim=1).values)
33
+ importance_scores = gate_max_abs + up_max_abs
34
+ return importance_scores
35
+
36
+ def compute_neuron_pair_importance_vow(gate_weight: torch.Tensor, up_weight: torch.Tensor) -> torch.Tensor:
37
+ """
38
+ Compute neuron pair importance scores using Variance of Weights method.
39
+
40
+ Args:
41
+ gate_weight: Weight matrix from the gate_proj layer
42
+ up_weight: Weight matrix from the up_proj layer
43
+
44
+ Returns:
45
+ importance_scores: Importance scores for each neuron pair
46
+ """
47
+ gate_variance = torch.var(gate_weight, dim=1)
48
+ up_variance = torch.var(up_weight, dim=1)
49
+ importance_scores = gate_variance + up_variance
50
+ return importance_scores
51
+
52
+ def compute_neuron_pair_importance_pon(gate_weight: torch.Tensor, up_weight: torch.Tensor) -> torch.Tensor:
53
+ """
54
+ Compute neuron pair importance scores using Product of Norms method.
55
+
56
+ Args:
57
+ gate_weight: Weight matrix from the gate_proj layer
58
+ up_weight: Weight matrix from the up_proj layer
59
+
60
+ Returns:
61
+ importance_scores: Importance scores for each neuron pair
62
+ """
63
+ gate_norms = torch.norm(gate_weight, p=1, dim=1)
64
+ up_norms = torch.norm(up_weight, p=1, dim=1)
65
+ importance_scores = gate_norms * up_norms
66
+ return importance_scores
67
+
68
+ # Dictionary mapping method names to their respective functions
69
+ IMPORTANCE_FUNCTIONS = {
70
+ "MAW": compute_neuron_pair_importance_maw,
71
+ "VOW": compute_neuron_pair_importance_vow,
72
+ "PON": compute_neuron_pair_importance_pon,
73
+ }
74
+
75
+ def prune_neuron_pairs(
76
+ mlp: nn.Module,
77
+ prune_percentage: float,
78
+ importance_fn: Callable = compute_neuron_pair_importance_maw
79
+ ) -> Tuple[nn.Linear, nn.Linear, nn.Linear, int]:
80
+ """
81
+ Prune a specific percentage of neurons from the MLP layers (GLU architecture).
82
+
83
+ Args:
84
+ mlp: MLP module containing gate_proj, up_proj, and down_proj layers
85
+ prune_percentage: Percentage of neurons to prune (0-100)
86
+ importance_fn: Function to compute neuron pair importance
87
+
88
+ Returns:
89
+ new_gate_proj: Pruned gate_proj layer
90
+ new_up_proj: Pruned up_proj layer
91
+ new_down_proj: Pruned down_proj layer
92
+ k: New intermediate size after pruning
93
+ """
94
+ # Extract the weights from the MLP layers
95
+ gate_weight = mlp.gate_proj.weight.data.float()
96
+ up_weight = mlp.up_proj.weight.data.float()
97
+
98
+ # Compute importance scores for neuron pairs
99
+ importance_scores = importance_fn(gate_weight, up_weight)
100
+
101
+ # Determine the new intermediate size
102
+ original_intermediate_size = gate_weight.size(0)
103
+ num_neuron_pairs_to_prune = min(int(prune_percentage / 100 * original_intermediate_size), original_intermediate_size - 1)
104
+ k = original_intermediate_size - num_neuron_pairs_to_prune
105
+
106
+ # Validate the new size
107
+ if k <= 0:
108
+ raise ValueError(f"Invalid number of neuron pairs to keep: {k}. Reduce pruning percentage.")
109
+
110
+ # Select the neurons to keep based on importance scores
111
+ _, indices_to_keep = torch.topk(importance_scores, k, largest=True)
112
+ indices_to_keep = indices_to_keep.sort().values
113
+
114
+ # Create new layers with reduced dimensions
115
+ new_gate_proj = nn.Linear(mlp.gate_proj.in_features, k, bias=mlp.gate_proj.bias is not None)
116
+ new_up_proj = nn.Linear(mlp.up_proj.in_features, k, bias=mlp.up_proj.bias is not None)
117
+ new_down_proj = nn.Linear(k, mlp.down_proj.out_features, bias=mlp.down_proj.bias is not None)
118
+
119
+ # Copy selected weights to the new layers
120
+ new_gate_proj.weight.data = gate_weight[indices_to_keep, :]
121
+ if mlp.gate_proj.bias is not None:
122
+ new_gate_proj.bias.data = mlp.gate_proj.bias.data[indices_to_keep]
123
+
124
+ new_up_proj.weight.data = up_weight[indices_to_keep, :]
125
+ if mlp.up_proj.bias is not None:
126
+ new_up_proj.bias.data = mlp.up_proj.bias.data[indices_to_keep]
127
+
128
+ new_down_proj.weight.data = mlp.down_proj.weight.data[:, indices_to_keep]
129
+ if mlp.down_proj.bias is not None:
130
+ new_down_proj.bias.data = mlp.down_proj.bias.data.clone()
131
+
132
+ return new_gate_proj, new_up_proj, new_down_proj, k
133
+
134
+ def calculate_pruning_percentage_from_expansion_rate(
135
+ current_intermediate_size: int,
136
+ current_hidden_size: int,
137
+ target_expansion_rate: float
138
+ ) -> float:
139
+ """
140
+ Calculate the pruning percentage needed to achieve a target expansion rate.
141
+
142
+ Args:
143
+ current_intermediate_size: Current size of the intermediate layer
144
+ current_hidden_size: Current size of the hidden layer
145
+ target_expansion_rate: Target expansion rate in percentage (e.g., 140 for 140%)
146
+
147
+ Returns:
148
+ pruning_percentage: Percentage of neurons to prune
149
+ """
150
+ current_expansion_rate = (current_intermediate_size / current_hidden_size) * 100
151
+ target_intermediate_size = (target_expansion_rate / 100) * current_hidden_size
152
+
153
+ if target_intermediate_size >= current_intermediate_size:
154
+ raise ValueError(
155
+ f"Target expansion rate ({target_expansion_rate}%) would increase the model size. "
156
+ f"Current expansion rate is {current_expansion_rate:.2f}%."
157
+ )
158
+
159
+ pruning_percentage = (1 - (target_intermediate_size / current_intermediate_size)) * 100
160
+ return pruning_percentage
161
+
162
+ def prune_model_mlp_glu(
163
+ model: PreTrainedModel,
164
+ neuron_selection_method: str = "MAW",
165
+ pruning_percentage: Optional[float] = 10,
166
+ expansion_rate: Optional[float] = None,
167
+ show_progress: bool = True,
168
+ ) -> PreTrainedModel:
169
+ """
170
+ Prune the MLP layers in a model with GLU architecture.
171
+
172
+ Args:
173
+ model: Pre-trained model to prune
174
+ neuron_selection_method: Method to use for calculating neuron importance ("MAW", "VOW", or "PON")
175
+ pruning_percentage: Percentage of neurons to prune (0-100)
176
+ expansion_rate: Target expansion rate in percentage (mutually exclusive with pruning_percentage)
177
+ show_progress: Whether to show progress during pruning
178
+
179
+ Returns:
180
+ model: Pruned model
181
+ """
182
+ # Validate the model for GLU pruning
183
+ if not validate_model_for_glu_pruning(model):
184
+ raise ValueError("Model is not compatible with GLU pruning. It must have gate_proj, up_proj, and down_proj layers.")
185
+
186
+ # Select the appropriate importance function
187
+ if neuron_selection_method not in IMPORTANCE_FUNCTIONS:
188
+ raise ValueError(f"Invalid neuron selection method: {neuron_selection_method}. "
189
+ f"Choose from {list(IMPORTANCE_FUNCTIONS.keys())}.")
190
+
191
+ importance_fn = IMPORTANCE_FUNCTIONS[neuron_selection_method]
192
+
193
+ # Handle mutually exclusive parameters
194
+ if pruning_percentage is not None and expansion_rate is not None:
195
+ raise ValueError("pruning_percentage and expansion_rate are mutually exclusive. Provide only one.")
196
+
197
+ if expansion_rate is not None:
198
+ # Get the first MLP layer to calculate current expansion rate
199
+ layers = get_model_layers(model)
200
+ if not layers:
201
+ raise ValueError("Could not find MLP layers in the model.")
202
+
203
+ first_mlp = layers[0].mlp
204
+ current_intermediate_size = first_mlp.gate_proj.out_features
205
+ current_hidden_size = first_mlp.gate_proj.in_features
206
+
207
+ pruning_percentage = calculate_pruning_percentage_from_expansion_rate(
208
+ current_intermediate_size, current_hidden_size, expansion_rate
209
+ )
210
+
211
+ logger.info(f"Calculated pruning percentage: {pruning_percentage:.2f}% to achieve "
212
+ f"expansion rate of {expansion_rate}%")
213
+
214
+ # Ensure pruning_percentage is within valid range
215
+ if not 0 <= pruning_percentage <= 100:
216
+ raise ValueError(f"pruning_percentage must be between 0 and 100, got {pruning_percentage}")
217
+
218
+ # Get all layers to prune
219
+ layers = get_model_layers(model)
220
+ if not layers:
221
+ raise ValueError("Could not find MLP layers in the model.")
222
+
223
+ new_intermediate_size = None
224
+
225
+ # Wrap with tqdm if show_progress is True
226
+ layer_iterator = tqdm(enumerate(layers), total=len(layers), desc="Pruning layers") if show_progress else enumerate(layers)
227
+
228
+ # Iterate through layers and apply pruning
229
+ for idx, layer in layer_iterator:
230
+ mlp = layer.mlp
231
+
232
+ # Prune neuron pairs in the MLP layer
233
+ new_gate_proj, new_up_proj, new_down_proj, new_size = prune_neuron_pairs(
234
+ mlp, pruning_percentage, importance_fn
235
+ )
236
+
237
+ # Replace original layers with pruned layers
238
+ mlp.gate_proj = new_gate_proj
239
+ mlp.up_proj = new_up_proj
240
+ mlp.down_proj = new_down_proj
241
+
242
+ # Store the new intermediate size (should be the same for all layers)
243
+ if new_intermediate_size is None:
244
+ new_intermediate_size = new_size
245
+
246
+ # Update model configuration
247
+ if hasattr(model, "config") and hasattr(model.config, "intermediate_size"):
248
+ model.config.intermediate_size = new_intermediate_size
249
+ logger.info(f"Updated model config: intermediate_size = {new_intermediate_size}")
250
+
251
+ return model
pruning/utils.py ADDED
@@ -0,0 +1,148 @@
1
+ """
2
+ Utility functions for the OptiPFair library.
3
+
4
+ This module provides helper functions for model compatibility checking,
5
+ layer extraction, and other common tasks needed across different pruning methods.
6
+ """
7
+
8
+ import torch
9
+ from typing import List, Optional, Union, Any, Dict
10
+ import logging
11
+ from transformers import PreTrainedModel
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ def validate_model_for_glu_pruning(model: PreTrainedModel) -> bool:
16
+ """
17
+ Validate that a model is compatible with GLU pruning.
18
+
19
+ Args:
20
+ model: Model to validate
21
+
22
+ Returns:
23
+ bool: True if the model is compatible, False otherwise
24
+ """
25
+ # Check if the model has the expected structure
26
+ try:
27
+ layers = get_model_layers(model)
28
+ if not layers:
29
+ logger.warning("Could not find decoder layers in the model")
30
+ return False
31
+
32
+ # Check the first layer for GLU components
33
+ first_layer = layers[0]
34
+ if not hasattr(first_layer, 'mlp'):
35
+ logger.warning("Model layers do not have 'mlp' attribute")
36
+ return False
37
+
38
+ mlp = first_layer.mlp
39
+ required_attributes = ['gate_proj', 'up_proj', 'down_proj']
40
+ for attr in required_attributes:
41
+ if not hasattr(mlp, attr):
42
+ logger.warning(f"MLP does not have required attribute: {attr}")
43
+ return False
44
+
45
+ # Verify these are linear layers
46
+ layer = getattr(mlp, attr)
47
+ if not isinstance(layer, torch.nn.Linear):
48
+ logger.warning(f"{attr} is not a Linear layer")
49
+ return False
50
+
51
+ # Verify gate_proj and up_proj have the same dimensions
52
+ if mlp.gate_proj.in_features != mlp.up_proj.in_features:
53
+ logger.warning("gate_proj and up_proj have different input dimensions")
54
+ return False
55
+
56
+ if mlp.gate_proj.out_features != mlp.up_proj.out_features:
57
+ logger.warning("gate_proj and up_proj have different output dimensions")
58
+ return False
59
+
60
+ if mlp.down_proj.in_features != mlp.gate_proj.out_features:
61
+ logger.warning("down_proj input dimensions don't match gate_proj output dimensions")
62
+ return False
63
+
64
+ return True
65
+
66
+ except Exception as e:
67
+ logger.warning(f"Error validating model for GLU pruning: {str(e)}")
68
+ return False
69
+
70
+ def get_model_layers(model: PreTrainedModel) -> List[Any]:
71
+ """
72
+ Extract transformer layers from a pre-trained model.
73
+ Currently supports LLaMA, Mistral, and similar model architectures.
74
+
75
+ Args:
76
+ model: Pre-trained model
77
+
78
+ Returns:
79
+ List of decoder layers that contain MLP blocks
80
+ """
81
+ # Try different attribute paths based on common model architectures
82
+ if hasattr(model, 'model') and hasattr(model.model, 'layers'):
83
+ # LLaMA, Mistral, and similar architectures
84
+ return list(model.model.layers)
85
+ elif hasattr(model, 'transformer') and hasattr(model.transformer, 'h'):
86
+ # GPT-2 and similar architectures
87
+ return list(model.transformer.h)
88
+ elif hasattr(model, 'encoder') and hasattr(model.encoder, 'layer'):
89
+ # BERT and similar architectures
90
+ return list(model.encoder.layer)
91
+ elif hasattr(model, 'layers'):
92
+ # Direct layers attribute
93
+ return list(model.layers)
94
+
95
+ logger.warning("Could not find layers in the model")
96
+ return []
97
+
98
+ def count_parameters(model: torch.nn.Module) -> int:
99
+ """
100
+ Count the number of trainable parameters in a model.
101
+
102
+ Args:
103
+ model: PyTorch model
104
+
105
+ Returns:
106
+ Number of trainable parameters
107
+ """
108
+ return sum(p.numel() for p in model.parameters() if p.requires_grad)
109
+
110
+ def get_pruning_statistics(
111
+ original_model: torch.nn.Module,
112
+ pruned_model: torch.nn.Module,
113
+ ) -> Dict[str, Any]:
114
+ """
115
+ Calculate statistics about the pruning operation.
116
+
117
+ Args:
118
+ original_model: Original model before pruning
119
+ pruned_model: Model after pruning
120
+
121
+ Returns:
122
+ Dictionary containing pruning statistics
123
+ """
124
+ original_params = count_parameters(original_model)
125
+ pruned_params = count_parameters(pruned_model)
126
+
127
+ reduction = original_params - pruned_params
128
+ percentage_reduction = (reduction / original_params) * 100
129
+
130
+ # Get expansion rate if possible
131
+ expansion_rate = None
132
+ try:
133
+ layers = get_model_layers(pruned_model)
134
+ if layers:
135
+ first_mlp = layers[0].mlp
136
+ intermediate_size = first_mlp.gate_proj.out_features
137
+ hidden_size = first_mlp.gate_proj.in_features
138
+ expansion_rate = (intermediate_size / hidden_size) * 100
139
+ except Exception:
140
+ pass
141
+
142
+ return {
143
+ "original_parameters": original_params,
144
+ "pruned_parameters": pruned_params,
145
+ "reduction": reduction,
146
+ "percentage_reduction": percentage_reduction,
147
+ "expansion_rate": expansion_rate
148
+ }