Skip to content

Commit 594841f

Browse files
committed
Update sitemap and enhance usage documentation with depth pruning details
- Updated last modified dates in sitemap.xml for all URLs to 2025-09-24. - Modified sitemap.xml.gz to reflect changes in sitemap.xml. - Expanded usage/index.html to include comprehensive sections on depth pruning, covering: - Overview of depth pruning and its benefits. - Detailed Python API examples for basic depth pruning, pruning by percentage, and pruning with specific layer indices. - Command-line interface examples for depth pruning. - Comparative analysis of MLP GLU vs Depth Pruning, including when to use each method. - Added evaluation methods for assessing pruned models.
1 parent 8e5fa9e commit 594841f

10 files changed

Lines changed: 1173 additions & 211 deletions

File tree

docs/index.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,12 @@ Understanding bias in language models is crucial for:
2323

2424
- **GLU Architecture-Aware Pruning**: Maintains the paired nature of gate_proj and up_proj layers
2525
- **Depth Pruning**: Remove entire transformer layers for aggressive efficiency gains
26+
- **Layer Importance Analysis**: Analyze transformer layers using cosine similarity to inform pruning decisions
27+
- **Bias Visualization Tools**: Comprehensive analysis of how models process demographic attributes
28+
- **Quantitative Bias Metrics**: Numeric measurements for consistent evaluation
2629
- **Multiple Neuron Selection Methods**: MAW, VOW, and PON for different pruning strategies
2730
- **Flexible Pruning Targets**: Support for both pruning percentage and target expansion rate
2831
- **Layer Selection Methods**: Choose specific layers or use automatic selection strategies
29-
- **Bias Visualization Tools**: Comprehensive analysis of how models process demographic attributes
30-
- **Quantitative Bias Metrics**: Numeric measurements for consistent evaluation
3132
- **Simple API and CLI**: Easy to use interfaces for Python and command line
3233
- **Progress Tracking**: Visual progress bars and detailed statistics
3334

docs/usage.md

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Usage Guide
2+
This guide provides detailed instructions on how to use the core functionalities of OptiPFair, from pruning models to analyzing bias.
23

34
## Python API
45

@@ -267,4 +268,102 @@ comparison = compare_models_inference(
267268

268269
print(f"Speedup: {comparison['speedup']:.2f}x")
269270
print(f"Tokens per second improvement: {comparison['tps_improvement_percent']:.2f}%")
271+
```
272+
273+
## Layer Importance Analysis
274+
275+
OptiPFair includes functionality to analyze the importance of transformer layers using cosine similarity. This helps identify which layers contribute most to the model's transformations, informing depth pruning decisions.
276+
277+
### Basic Usage
278+
279+
```python
280+
from transformers import AutoModelForCausalLM, AutoTokenizer
281+
from torch.utils.data import DataLoader
282+
from optipfair import analyze_layer_importance
283+
284+
# Load model and tokenizer
285+
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B")
286+
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
287+
288+
# Prepare your dataset (user responsibility)
289+
# Example with a simple dataset
290+
from datasets import load_dataset
291+
dataset = load_dataset('wikitext', 'wikitext-2-raw-v1', split='train[:100]')
292+
293+
def tokenize_function(examples):
294+
return tokenizer(
295+
examples['text'],
296+
truncation=True,
297+
padding='max_length',
298+
max_length=512,
299+
return_tensors='pt'
300+
)
301+
302+
tokenized_dataset = dataset.map(tokenize_function, batched=True)
303+
dataloader = DataLoader(tokenized_dataset, batch_size=8)
304+
305+
# Analyze layer importance
306+
importance_scores = analyze_layer_importance(model, dataloader)
307+
308+
# Results: {0: 0.890395, 1: 0.307580, 2: 0.771541, ...}
309+
print(importance_scores)
310+
```
311+
312+
### Advanced Usage
313+
314+
```python
315+
# With manual architecture specification
316+
importance_scores = analyze_layer_importance(
317+
model=model,
318+
dataloader=dataloader,
319+
layers_path='transformer.h', # For GPT-2 style models
320+
show_progress=True
321+
)
322+
323+
# Analyze specific layers for depth pruning
324+
# Higher scores indicate layers that transform data more significantly
325+
# Lower scores indicate "passive" layers that could be candidates for removal
326+
sorted_layers = sorted(importance_scores.items(), key=lambda x: x[1], reverse=True)
327+
print("Most important layers:", sorted_layers[:3])
328+
print("Least important layers:", sorted_layers[-3:])
329+
```
330+
331+
### Multi-Architecture Support
332+
333+
The function automatically detects transformer layers for different architectures:
334+
335+
- **LLaMA/Qwen/Mistral**: `model.layers`
336+
- **GPT-2/DistilGPT2**: `transformer.h`
337+
- **T5**: `encoder.block` or `decoder.block`
338+
- **BERT**: `encoder.layer`
339+
340+
If automatic detection fails, specify the path manually:
341+
342+
```python
343+
# Manual specification for custom architectures
344+
importance_scores = analyze_layer_importance(
345+
model=model,
346+
dataloader=dataloader,
347+
layers_path='model.custom_transformer_layers'
348+
)
349+
```
350+
351+
### Integration with Depth Pruning
352+
353+
Use importance scores to inform depth pruning decisions:
354+
355+
```python
356+
# Analyze layer importance
357+
importance_scores = analyze_layer_importance(model, dataloader)
358+
359+
# Identify least important layers
360+
sorted_layers = sorted(importance_scores.items(), key=lambda x: x[1])
361+
layers_to_remove = [layer_idx for layer_idx, score in sorted_layers[:4]]
362+
363+
# Apply depth pruning to remove least important layers
364+
pruned_model = prune_model(
365+
model=model,
366+
pruning_type="DEPTH",
367+
layer_indices=layers_to_remove
368+
)
270369
```

0 commit comments

Comments
 (0)