Skip to content

Commit 65d11d9

Browse files
authored
Merge pull request #5 from intsystems/v_min
clean up analyze_intrinsic.ipynb, add support for BERT-like model & update README file
2 parents 6675e35 + 3333fc4 commit 65d11d9

7 files changed

Lines changed: 3075 additions & 412 deletions

File tree

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ __pycache__/
111111
.gitignore
112112
# Exclude folders with name logs:
113113
logs/
114-
114+
115115
# Exclude all .dat files:
116116
*.dat
117117
# Exclude all files which begin on .
@@ -125,3 +125,4 @@ data
125125
configs
126126
activation_saved
127127
cache
128+
all_stats

README.md

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
# Testing the Manifold Hypothesis in the Embedding Subspaces of Large Language Models
2+
3+
A comprehensive research project investigating the manifold hypothesis in the embedding subspaces of large language models, with implications for understanding model behavior and improving interpretability.
4+
5+
## About This Project
6+
7+
This research explores whether embedding subspaces of large language models exhibit manifold structure. Understanding the geometric properties of these embeddings can provide insights into model behavior, generalization patterns, and potential improvements for model architecture and training procedures.
8+
9+
| | |
10+
|---|---|
11+
| **Research Topic** | Testing the Manifold Hypothesis in the Embedding Subspaces of Large Language Models |
12+
| **Research Type** | Creation of Intelligent Systems (CoIS) |
13+
| **Authors** | Ivan Papai, Vladislav Minashkin, Fedor Sobolevsky, Vladislav Meshkov |
14+
| **Supervisor** | Andrey Grabovoy |
15+
16+
## Features
17+
18+
- **Manifold Hypothesis Testing**: Statistical analysis of embedding subspace geometry
19+
- **Multi-layer Analysis**: Investigation across different transformer layers
20+
- **Dimensionality Reduction**: Advanced techniques for high-dimensional visualization
21+
- **Synthetic Validation**: Testing framework with controlled manifold structures
22+
- **Comprehensive Visualization**: Interactive tools for embedding space exploration
23+
- **Statistical Framework**: Robust hypothesis testing with multiple validation methods
24+
25+
## Quick Start
26+
27+
### Prerequisites
28+
29+
- Python 3.9 or higher
30+
- [uv](https://github.com/astral-sh/uv) - Modern Python package manager
31+
- Git for version control
32+
33+
### Installation
34+
35+
1. **Clone the repository**
36+
```bash
37+
git clone https://github.com/intsystems/CreationOfIntelligentSystems_LLM_25.git
38+
cd CreationOfIntelligentSystems_LLM_25
39+
```
40+
41+
2. **Install uv** (if not already installed)
42+
```bash
43+
# On macOS/Linux
44+
curl -LsSf https://astral.sh/uv/install.sh | sh
45+
46+
# On Windows
47+
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
48+
```
49+
50+
3. **Set up the project**
51+
```bash
52+
# Create virtual environment and install dependencies
53+
uv venv
54+
source .venv/bin/activate # On Windows: .venv\Scripts\activate
55+
56+
# Install all project dependencies
57+
uv sync
58+
59+
# Alternative: Use uv run to execute commands directly
60+
uv run python your_script.py
61+
```
62+
63+
4. **Verify installation**
64+
```bash
65+
uv run python -c "import torch; print(f'PyTorch version: {torch.__version__}')"
66+
uv run python -c "import transformers; print(f'Transformers version: {transformers.__version__}')"
67+
```
68+
69+
## Project Structure
70+
71+
```
72+
CreationOfIntelligentSystems_LLM_25/
73+
├── README.md # Project documentation
74+
├── pyproject.toml # Project configuration and dependencies
75+
├── uv.lock # Locked dependency versions
76+
├── linkreview.md # Literature review and related work
77+
├── src/ # Main source code directory
78+
│ ├── activation_processor.py # Process neural network activations
79+
│ ├── calc_stats.py # Statistical calculations
80+
│ ├── create_topic_configs.py # Configuration management
81+
│ ├── dataset.py # Dataset handling
82+
│ ├── extract_act_main.py # Main activation extraction script
83+
│ ├── hooks.py # Model hooks for activation capture
84+
│ ├── model.py # Model definitions
85+
│ ├── parse_mrpc.py # MRPC dataset parsing
86+
│ ├── parse_topics.py # Topic analysis utilities
87+
│ ├── save_stats_from_topics.py # Save statistical results
88+
│ └── utils.py # Utility functions
89+
├── tests/ # Test suite
90+
├── notebooks/ # Jupyter notebooks for experiments
91+
│ ├── exploratory_analysis.ipynb
92+
│ ├── manifold_testing.ipynb
93+
│ └── visualization_demo.ipynb
94+
├── data/ # Datasets and data files
95+
├── paper/ # LaTeX source for research paper
96+
├── slides/ # Presentation materials
97+
├── configs/ # Configuration files
98+
├── all_stats/ # Statistical analysis results
99+
├── cache/ # Cached computational results
100+
├── doc/ # Documentation
101+
└── activation_saved/ # Saved neural network activations
102+
```
103+
104+
## Usage Examples
105+
106+
### Extract Hidden States
107+
```bash
108+
109+
uv run python src/extract_act_main.py --config-name="bert-base_mrpc.yaml"
110+
111+
```
112+
113+
## Calculate Statistics
114+
115+
```bash
116+
117+
uv run python src/calc_stats.py --config-name="calc_stats"
118+
119+
```
120+
121+
### Working with Jupyter Notebooks
122+
```bash
123+
# Start Jupyter Lab with project environment
124+
uv run jupyter lab
125+
126+
# Navigate to notebooks/ and run analyze_instrinsic.ipynb
127+
# This notebook contains intrinsic dimensionality analysis of LLM embeddings
128+
```
129+
130+
## Research Methodology
131+
132+
This project employs a comprehensive approach to testing the manifold hypothesis:
133+
134+
### 1. Embedding Extraction
135+
- Collect embeddings from multiple transformer layers
136+
- Support for various LLM architectures (GPT, BERT, T5, etc.)
137+
- Proper handling of different embedding dimensions
138+
139+
### 2. Dimensionality Analysis
140+
- Principal Component Analysis (PCA)
141+
- t-SNE and UMAP for non-linear dimensionality reduction
142+
- Intrinsic dimensionality estimation
143+
144+
### 3. Manifold Testing
145+
- **Intrinsic Tests**: Measures based on local geometry
146+
- **Extrinsic Tests**: Global embedding space analysis
147+
- **Statistical Validation**: Hypothesis testing with significance levels
148+
- **Cross-validation**: Bootstrap methods for robust estimation
149+
150+
### 4. Visualization
151+
- Interactive 3D embedding visualizations
152+
- Manifold structure representation
153+
- Statistical distribution plots
154+
- Comparative analysis across layers
155+
156+
### 5. Synthetic Validation
157+
- Generated manifolds with known properties
158+
- Controlled experiments with varying complexity
159+
- Baseline comparisons for method validation
160+
161+
## Performance Characteristics
162+
163+
- **Embedding Processing**: Efficient handling of large-scale embeddings
164+
- **Memory Usage**: Optimized for high-dimensional data analysis
165+
- **Computational Complexity**: Scalable to various embedding sizes
166+
- **Support for Multiple Models**: GPT, BERT, T5, and other transformer variants
167+
168+
### Research Extensions
169+
- **Temporal Analysis**: Manifold evolution during training
170+
- **Cross-linguistic Studies**: Manifold properties across languages
171+
- **Task-specific Analysis**: Manifold structure for different downstream tasks
172+
- **Theoretical Framework**: Mathematical foundations for observed phenomena
173+
174+
## Citation
175+
176+
If you use this research in your work, please cite:
177+
178+
```bibtex
179+
@software{manifold_llm_embeddings_2025,
180+
title={Testing the Manifold Hypothesis in the Embedding Subspaces of Large Language Models},
181+
authors={Papai, Ivan and Minashkin, Vladislav and Sobolevsky, Fedor and Meshkov, Vladislav},
182+
year={2024},
183+
url={https://github.com/your-repo/CreationOfIntelligentSystems_LLM_25}
184+
}
185+
```

README.rst

Lines changed: 0 additions & 39 deletions
This file was deleted.

notebooks/analyze_intrinsic.ipynb

Lines changed: 84 additions & 265 deletions
Large diffs are not rendered by default.

pyproject.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,17 @@ dependencies = [
99
"datasets>=4.4.0",
1010
"dotenv>=0.9.9",
1111
"hydra-core>=1.3.2",
12+
"ipykernel>=6.31.0",
1213
"numpy>=2.0.2",
1314
"protobuf>=6.33.0",
1415
"scikit-learn>=1.6.1",
1516
"sentencepiece>=0.2.1",
1617
"torch>=2.8.0",
1718
"transformers>=4.57.1",
19+
"tqdm",
20+
"intrinsics_dimension",
21+
"matplotlib>=3.9.4",
22+
"ipywidgets",
23+
"jupyterlab-widgets>=3.0.16",
24+
"jupyterlab>=4.4.10",
1825
]

src/model.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Model loading utilities."""
22
import torch
3-
from transformers import AutoTokenizer, AutoModelForCausalLM
3+
from transformers import AutoTokenizer, AutoModelForCausalLM, BertLMHeadModel, OPTForCausalLM
44
from omegaconf import DictConfig
55
import logging
66

@@ -66,6 +66,10 @@ def get_model_layers(model, use_bloom: bool):
6666
"""
6767
if use_bloom:
6868
modules = [model.transformer.word_embeddings_layernorm] + list(model.transformer.h)
69+
elif isinstance(model, BertLMHeadModel):
70+
modules = [model.bert.embeddings.word_embeddings] + list(model.bert.encoder.layer)
71+
elif isinstance(model, OPTForCausalLM):
72+
modules = [model.model.decoder.embed_tokens] + list(model.model.decoder.layers)
6973
else:
7074
modules = [model.model.embed_tokens] + list(model.model.layers)
7175

0 commit comments

Comments
 (0)