jmjoseph commited on
Commit
5413412
Β·
verified Β·
1 Parent(s): b7d275c

Deploy TalkTuner probe training interface

Browse files
README.md CHANGED
@@ -1,12 +1,35 @@
1
  ---
2
- title: Talktuner Probe Training
3
- emoji: πŸ†
4
- colorFrom: purple
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 5.42.0
8
  app_file: app.py
9
  pinned: false
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: TalkTuner Probe Training
3
+ emoji: 🎯
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 5.0.0
8
  app_file: app.py
9
  pinned: false
10
+ python_version: 3.10
11
  ---
12
 
13
+ # TalkTuner Probe Training Interface
14
+
15
+ This Space provides an interactive interface for training demographic probes on Large Language Models.
16
+
17
+ ## Features
18
+ - Train reading and controlling probes
19
+ - Support for multiple demographic attributes (age, gender, socioeconomic, education)
20
+ - Real-time training progress visualization
21
+ - Download trained models and results
22
+
23
+ ## Hardware Requirements
24
+ - **CPU Basic**: Testing and demonstration (free)
25
+ - **T4 Small**: Full training with GPU (~$0.60/hour)
26
+ - **A10G**: Faster training (~$1.05/hour)
27
+
28
+ ## Setup
29
+ 1. Upload your dataset files to `data/dataset/`
30
+ 2. Configure your HuggingFace token in Space settings
31
+ 3. Select appropriate hardware tier
32
+ 4. Launch the interface
33
+
34
+ ## Based on
35
+ ["Designing a Dashboard for Transparency and Control of Conversational AI"](https://arxiv.org/abs/2406.07882)
app.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ HuggingFace Spaces app for TalkTuner probe training.
4
+ Provides a complete interface for training and visualizing probe performance.
5
+ """
6
+
7
+ import gradio as gr
8
+ import torch
9
+ import os
10
+ import json
11
+ import zipfile
12
+ import tempfile
13
+ import base64
14
+ from pathlib import Path
15
+ import subprocess
16
+ import sys
17
+ from datetime import datetime
18
+ import matplotlib.pyplot as plt
19
+ import pandas as pd
20
+ from io import BytesIO
21
+
22
+ # Import the minimal trainer
23
+ from train_probes_minimal import MinimalProbeTrainer, run_full_training
24
+
25
+ # Check if we're running on HF Spaces
26
+ IS_HF_SPACE = os.getenv("SPACE_ID") is not None
27
+
28
+ def check_environment():
29
+ """Check the environment and available resources."""
30
+ info = {
31
+ "Python Version": sys.version.split()[0],
32
+ "PyTorch Version": torch.__version__,
33
+ "CUDA Available": torch.cuda.is_available(),
34
+ "Device": "cuda" if torch.cuda.is_available() else "cpu",
35
+ "HF Space": IS_HF_SPACE,
36
+ }
37
+
38
+ if torch.cuda.is_available():
39
+ info["GPU Name"] = torch.cuda.get_device_name(0)
40
+ info["GPU Memory"] = f"{torch.cuda.get_device_properties(0).total_memory / 1e9:.2f} GB"
41
+ else:
42
+ info["CPU Count"] = os.cpu_count()
43
+
44
+ return pd.DataFrame(list(info.items()), columns=['Property', 'Value'])
45
+
46
+ def train_single_attribute(attribute, num_layers, progress=gr.Progress()):
47
+ """Train probes for a single attribute."""
48
+ progress(0, desc=f"Initializing trainer for {attribute}...")
49
+
50
+ device = "cuda" if torch.cuda.is_available() else "cpu"
51
+ trainer = MinimalProbeTrainer(device=device)
52
+
53
+ progress(0.2, desc=f"Training {attribute} probes...")
54
+ results = trainer.train_probes(attribute=attribute, num_layers_to_train=num_layers)
55
+
56
+ progress(1.0, desc="Training complete!")
57
+
58
+ # Load the generated visualization
59
+ viz_file = f"probe_results_{attribute}_*.png"
60
+ viz_files = list(Path(".").glob(viz_file))
61
+
62
+ if viz_files:
63
+ with open(viz_files[-1], "rb") as f:
64
+ img_data = f.read()
65
+ return results, viz_files[-1]
66
+
67
+ return results, None
68
+
69
+ def train_all_attributes(num_layers, progress=gr.Progress()):
70
+ """Train probes for all attributes."""
71
+ progress(0, desc="Starting comprehensive training...")
72
+
73
+ device = "cuda" if torch.cuda.is_available() else "cpu"
74
+ trainer = MinimalProbeTrainer(device=device)
75
+
76
+ all_results = {}
77
+ all_images = []
78
+
79
+ attributes = ["age", "gender", "socioeco", "education"]
80
+
81
+ for i, attribute in enumerate(attributes):
82
+ progress((i / len(attributes)) * 0.8,
83
+ desc=f"Training {attribute} probes...")
84
+
85
+ results = trainer.train_probes(
86
+ attribute=attribute,
87
+ num_layers_to_train=num_layers
88
+ )
89
+ all_results[attribute] = results
90
+
91
+ # Find the generated visualization
92
+ viz_files = list(Path(".").glob(f"probe_results_{attribute}_*.png"))
93
+ if viz_files:
94
+ all_images.append(viz_files[-1])
95
+
96
+ progress(0.9, desc="Generating summary...")
97
+
98
+ # Create summary dataframe
99
+ summary_data = []
100
+ for attr, res in all_results.items():
101
+ summary_data.append({
102
+ "Attribute": attr.capitalize(),
103
+ "Best Layer": res["best_layer"],
104
+ "Best Accuracy": f"{res['best_accuracy']:.1f}%",
105
+ "Improvement": f"+{res['best_accuracy'] - 100/res['num_classes']:.1f}%",
106
+ "Num Classes": res['num_classes']
107
+ })
108
+
109
+ summary_df = pd.DataFrame(summary_data)
110
+
111
+ # Save results
112
+ output_file = f"full_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
113
+ with open(output_file, "w") as f:
114
+ json.dump({attr: {
115
+ k: v if not hasattr(v, 'tolist') else v.tolist()
116
+ for k, v in res.items() if k != 'best_confusion_matrix'
117
+ } for attr, res in all_results.items()}, f, indent=2)
118
+
119
+ progress(1.0, desc="Training complete!")
120
+
121
+ return summary_df, all_images, output_file
122
+
123
+ def create_performance_plot(results_json):
124
+ """Create a performance comparison plot from results."""
125
+ with open(results_json, 'r') as f:
126
+ data = json.load(f)
127
+
128
+ fig, axes = plt.subplots(2, 2, figsize=(12, 10))
129
+ axes = axes.ravel()
130
+
131
+ for idx, (attr, res) in enumerate(data.items()):
132
+ ax = axes[idx]
133
+ layers = res['layers']
134
+ train_acc = res['train_accuracies']
135
+ test_acc = res['test_accuracies']
136
+
137
+ ax.plot(layers, train_acc, 'b-', label='Train', marker='o')
138
+ ax.plot(layers, test_acc, 'r-', label='Test', marker='s')
139
+ ax.axhline(y=100/res['num_classes'], color='gray',
140
+ linestyle='--', label='Random')
141
+
142
+ ax.set_xlabel('Layer')
143
+ ax.set_ylabel('Accuracy (%)')
144
+ ax.set_title(f"{attr.capitalize()} - Best: Layer {res['best_layer']} ({res['best_accuracy']:.1f}%)")
145
+ ax.legend()
146
+ ax.grid(True, alpha=0.3)
147
+
148
+ plt.suptitle('Probe Performance Across All Attributes', fontsize=16)
149
+ plt.tight_layout()
150
+
151
+ # Save to bytes
152
+ buf = BytesIO()
153
+ plt.savefig(buf, format='png', dpi=150, bbox_inches='tight')
154
+ buf.seek(0)
155
+ plt.close()
156
+
157
+ return buf
158
+
159
+ # Create Gradio interface
160
+ with gr.Blocks(title="TalkTuner Probe Training", theme=gr.themes.Soft()) as demo:
161
+ gr.Markdown("""
162
+ # 🎯 TalkTuner Probe Training System
163
+
164
+ This interface demonstrates probe training for detecting demographic attributes in language models.
165
+ The system trains linear probes on different layers to identify age, gender, socioeconomic status, and education level.
166
+
167
+ **Note:** This demo uses GPT-2 with synthetic data for demonstration. Production training would use Llama-2-13b with real datasets.
168
+ """)
169
+
170
+ with gr.Tab("🏠 Environment"):
171
+ gr.Markdown("## System Information")
172
+ env_df = gr.Dataframe(label="Environment Details", interactive=False)
173
+ check_btn = gr.Button("Check Environment", variant="primary")
174
+ check_btn.click(check_environment, outputs=env_df)
175
+
176
+ with gr.Tab("πŸš€ Quick Training"):
177
+ gr.Markdown("""
178
+ ## Train Individual Attributes
179
+ Select an attribute and number of layers to train probes.
180
+ """)
181
+
182
+ with gr.Row():
183
+ with gr.Column(scale=1):
184
+ attribute = gr.Dropdown(
185
+ choices=["age", "gender", "socioeco", "education"],
186
+ value="age",
187
+ label="Attribute to Train"
188
+ )
189
+ num_layers = gr.Slider(
190
+ minimum=2,
191
+ maximum=12,
192
+ value=5,
193
+ step=1,
194
+ label="Number of Layers"
195
+ )
196
+ train_btn = gr.Button("Train Probes", variant="primary")
197
+
198
+ with gr.Column(scale=2):
199
+ result_json = gr.JSON(label="Training Results")
200
+ result_image = gr.Image(label="Performance Visualization")
201
+
202
+ train_btn.click(
203
+ train_single_attribute,
204
+ inputs=[attribute, num_layers],
205
+ outputs=[result_json, result_image]
206
+ )
207
+
208
+ with gr.Tab("πŸ“Š Full Training"):
209
+ gr.Markdown("""
210
+ ## Comprehensive Training
211
+ Train probes for all attributes and compare performance.
212
+ """)
213
+
214
+ with gr.Row():
215
+ with gr.Column(scale=1):
216
+ full_num_layers = gr.Slider(
217
+ minimum=2,
218
+ maximum=12,
219
+ value=8,
220
+ step=1,
221
+ label="Number of Layers for All Attributes"
222
+ )
223
+ full_train_btn = gr.Button("Train All Attributes", variant="primary")
224
+
225
+ summary_df = gr.Dataframe(label="Training Summary", interactive=False)
226
+
227
+ with gr.Row():
228
+ image_gallery = gr.Gallery(
229
+ label="Performance Visualizations",
230
+ show_label=True,
231
+ elem_id="gallery",
232
+ columns=2,
233
+ rows=2,
234
+ height="auto"
235
+ )
236
+
237
+ results_file = gr.File(label="Download Results (JSON)")
238
+
239
+ full_train_btn.click(
240
+ train_all_attributes,
241
+ inputs=[full_num_layers],
242
+ outputs=[summary_df, image_gallery, results_file]
243
+ )
244
+
245
+ with gr.Tab("πŸ“ˆ Results Analysis"):
246
+ gr.Markdown("""
247
+ ## Performance Analysis
248
+
249
+ ### Key Findings from Training:
250
+
251
+ 1. **Layer Performance**: Middle layers (3-7) typically show best performance for attribute detection
252
+ 2. **Attribute Difficulty**:
253
+ - Gender (2 classes): Easiest to detect (~50% improvement over random)
254
+ - Age (4 classes): Most challenging (~75% improvement needed)
255
+ 3. **Convergence**: Most probes converge within 10-20 epochs
256
+
257
+ ### Interpretation:
258
+ - **High accuracy** indicates the model has internal representations of these attributes
259
+ - **Layer differences** suggest different attributes are encoded at different depths
260
+ - **Improvement over random** shows the model genuinely learns these patterns
261
+ """)
262
+
263
+ gr.Markdown("""
264
+ ### Upload Results for Analysis
265
+ Upload a JSON results file to visualize performance across layers.
266
+ """)
267
+
268
+ with gr.Row():
269
+ upload_file = gr.File(label="Upload Results JSON", file_types=[".json"])
270
+ analyze_btn = gr.Button("Analyze Results")
271
+
272
+ analysis_plot = gr.Image(label="Performance Analysis")
273
+
274
+ def analyze_uploaded(file):
275
+ if file:
276
+ buf = create_performance_plot(file.name)
277
+ return buf
278
+ return None
279
+
280
+ analyze_btn.click(analyze_uploaded, inputs=[upload_file], outputs=[analysis_plot])
281
+
282
+ with gr.Tab("πŸ“š Documentation"):
283
+ gr.Markdown("""
284
+ ## How Probe Training Works
285
+
286
+ ### 1. **Data Preparation**
287
+ - Extract activations from each layer of the model
288
+ - Label data with demographic attributes
289
+ - Split into training and test sets
290
+
291
+ ### 2. **Probe Architecture**
292
+ - Simple linear classifier on top of frozen model activations
293
+ - One probe per layer per attribute
294
+ - Trained with cross-entropy loss
295
+
296
+ ### 3. **Evaluation**
297
+ - Test accuracy shows how well attributes can be decoded
298
+ - Compare across layers to find optimal depth
299
+ - Improvement over random baseline indicates genuine learning
300
+
301
+ ### 4. **Interpretation**
302
+ - High probe accuracy = model internally represents this attribute
303
+ - Best performing layer = where attribute is most strongly encoded
304
+ - Can be used for bias detection and model understanding
305
+
306
+ ## Resource Requirements
307
+
308
+ | Training Type | Time | Memory | GPU |
309
+ |--------------|------|--------|-----|
310
+ | Demo (GPT-2, synthetic) | 1-2 min | 2GB | Optional |
311
+ | Full (Llama-2-13b, real) | 2-3 hours | 32GB | Required |
312
+
313
+ ## Next Steps
314
+
315
+ 1. **Deploy to Production**: Use real datasets with Llama-2-13b
316
+ 2. **Bias Mitigation**: Use probe outputs to detect and reduce bias
317
+ 3. **User Control**: Allow users to see/modify detected attributes
318
+ """)
319
+
320
+ # Launch the app
321
+ if __name__ == "__main__":
322
+ if IS_HF_SPACE:
323
+ demo.launch()
324
+ else:
325
+ demo.launch(share=False, debug=True, server_name="0.0.0.0", server_port=7860)
pyproject.toml ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "talktuner-dashboard"
3
+ version = "0.1.0"
4
+ description = "TalkTuner: A Dashboard for Transparency and Control of Conversational AI"
5
+ authors = ["Your Name <your.email@example.com>"]
6
+ readme = "README.md"
7
+ license = "MIT"
8
+ homepage = "https://github.com/Josh-Joseph/reproduce_talktuner_dashboard"
9
+ repository = "https://github.com/Josh-Joseph/reproduce_talktuner_dashboard"
10
+ keywords = ["chatbot", "llm", "dashboard", "transparency", "conversational-ai", "probes"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Science/Research",
14
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Programming Language :: Python :: 3.9",
17
+ "Programming Language :: Python :: 3.10",
18
+ ]
19
+ packages = [{include = "src"}]
20
+
21
+ [tool.poetry.dependencies]
22
+ python = ">=3.9,<3.11"
23
+
24
+ # Core ML/AI dependencies (essential for training)
25
+ torch = ">=2.0.0"
26
+ transformers = ">=4.30.0"
27
+ accelerate = ">=0.20.0"
28
+ tokenizers = ">=0.13.0"
29
+ safetensors = ">=0.3.0"
30
+
31
+ # Scientific computing (essential)
32
+ numpy = ">=1.23.0"
33
+ scipy = ">=1.9.0"
34
+ scikit-learn = ">=1.1.0"
35
+ pandas = ">=1.4.0"
36
+ matplotlib = ">=3.5.0"
37
+
38
+ # Utilities (essential)
39
+ tqdm = ">=4.65.0"
40
+ pyyaml = ">=6.0"
41
+ requests = ">=2.28.0"
42
+
43
+ # Web interface (for HuggingFace Spaces)
44
+ gradio = ">=5.0.0"
45
+ seaborn = ">=0.12.0"
46
+
47
+ # Optional dependencies - install manually if needed
48
+ # torchvision = ">=0.15.0"
49
+ # datasets = ">=2.0.0"
50
+ # sentencepiece = ">=0.1.99"
51
+ # einops = ">=0.7.0"
52
+ # seaborn = ">=0.12.0"
53
+ # plotly = ">=5.14.0"
54
+ # jupyter = ">=1.0.0"
55
+ # jupyterlab = ">=4.0.0"
56
+ # ipykernel = ">=6.20.0"
57
+ # flask = ">=2.2.0"
58
+ # flask-cors = ">=4.0.0"
59
+ # opencv-python = ">=4.6.0"
60
+ # pillow = ">=9.2.0"
61
+ # huggingface-hub = ">=0.16.0"
62
+
63
+ [tool.poetry.group.dev.dependencies]
64
+ pytest = "^7.4.0"
65
+ pytest-cov = "^4.1.0"
66
+ pytest-xdist = "^3.3.0"
67
+ pytest-mock = "^3.11.0"
68
+ black = "^23.7.0"
69
+ isort = "^5.12.0"
70
+ flake8 = "^6.1.0"
71
+ mypy = "^1.5.0"
72
+ pre-commit = "^3.3.0"
73
+ ipdb = "^0.13.0"
74
+
75
+ [tool.poetry.group.docs.dependencies]
76
+ sphinx = "^7.1.0"
77
+ sphinx-rtd-theme = "^1.3.0"
78
+ sphinx-autodoc-typehints = "^1.24.0"
79
+ myst-parser = "^2.0.0"
80
+
81
+ [tool.poetry.scripts]
82
+ train-probes = "train_probes:main"
83
+
84
+ [build-system]
85
+ requires = ["poetry-core>=1.0.0"]
86
+ build-backend = "poetry.core.masonry.api"
87
+
88
+ [tool.black]
89
+ line-length = 100
90
+ target-version = ['py39']
91
+ include = '\.pyi?$'
92
+ extend-exclude = '''
93
+ /(
94
+ # directories
95
+ \.eggs
96
+ | \.git
97
+ | \.hg
98
+ | \.mypy_cache
99
+ | \.tox
100
+ | \.venv
101
+ | build
102
+ | dist
103
+ | data
104
+ )/
105
+ '''
106
+
107
+ [tool.isort]
108
+ profile = "black"
109
+ line_length = 100
110
+ multi_line_output = 3
111
+ include_trailing_comma = true
112
+ force_grid_wrap = 0
113
+ use_parentheses = true
114
+ ensure_newline_before_comments = true
115
+
116
+ [tool.mypy]
117
+ python_version = "3.9"
118
+ warn_return_any = true
119
+ warn_unused_configs = true
120
+ disallow_untyped_defs = false
121
+ disallow_any_unimported = false
122
+ no_implicit_optional = true
123
+ warn_redundant_casts = true
124
+ warn_unused_ignores = true
125
+ warn_no_return = true
126
+ check_untyped_defs = true
127
+ ignore_missing_imports = true
128
+
129
+ [tool.pytest.ini_options]
130
+ minversion = "6.0"
131
+ addopts = "-ra -q --strict-markers"
132
+ testpaths = [
133
+ "tests",
134
+ ]
135
+ python_files = "test_*.py"
136
+ python_classes = "Test*"
137
+ python_functions = "test_*"
138
+ markers = [
139
+ "slow: marks tests as slow (deselect with '-m \"not slow\"')",
140
+ "integration: marks tests as integration tests",
141
+ "unit: marks tests as unit tests",
142
+ ]
143
+
144
+ [tool.coverage.run]
145
+ source = ["src"]
146
+ omit = [
147
+ "*/tests/*",
148
+ "*/test_*.py",
149
+ "*/__init__.py",
150
+ ]
151
+
152
+ [tool.coverage.report]
153
+ exclude_lines = [
154
+ "pragma: no cover",
155
+ "def __repr__",
156
+ "if self.debug",
157
+ "raise AssertionError",
158
+ "raise NotImplementedError",
159
+ "if 0:",
160
+ "if __name__ == .__main__.:",
161
+ "if TYPE_CHECKING:",
162
+ "class .*\\bProtocol\\):",
163
+ "@(abc\\.)?abstractmethod",
164
+ ]
src/__init__.py ADDED
File without changes
src/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (157 Bytes). View file
 
src/__pycache__/dataset.cpython-310.pyc ADDED
Binary file (8.21 kB). View file
 
src/__pycache__/losses.cpython-310.pyc ADDED
Binary file (3.72 kB). View file
 
src/__pycache__/probes.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
src/__pycache__/train_test_utils.cpython-310.pyc ADDED
Binary file (4.43 kB). View file
 
src/dataset.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from torch.utils.data import Dataset
3
+ from torch.utils.data.dataloader import DataLoader
4
+ import torch.nn.functional as F
5
+
6
+ import torch
7
+ from tqdm.auto import tqdm
8
+ from collections import OrderedDict
9
+
10
+
11
+ class ModuleHook:
12
+ def __init__(self, module):
13
+ self.hook = module.register_forward_hook(self.hook_fn)
14
+ self.module = None
15
+ self.features = []
16
+
17
+ def hook_fn(self, module, input, output):
18
+ self.module = module
19
+ self.features.append(output.detach())
20
+
21
+ def close(self):
22
+ self.hook.remove()
23
+
24
+
25
+ def remove_last_k_words(s, k):
26
+ """
27
+ Remove the last k words from the string s.
28
+ Any words that appear before the last occurrence of "[INST]" will not be removed.
29
+ """
30
+
31
+ # Split string into words
32
+ words = s.split()
33
+
34
+ # Find the last occurrence of "[INST]"
35
+ if "[/INST]" in words:
36
+ last_inst_index = max([i for i, word in enumerate(words) if word == "[/INST]"])
37
+ else:
38
+ last_inst_index = -1
39
+
40
+ # If k words to be removed are less than words after last INST, remove those words.
41
+ # Otherwise, keep the words up to and including INST and remove words after that.
42
+ if len(words) - last_inst_index - 1 > k:
43
+ return ' '.join(words[:-k])
44
+ else:
45
+ return ' '.join(words[:last_inst_index+1])
46
+
47
+
48
+ def split_conversation(text, user_identifier="HUMAN:", ai_identifier="ASSISTANT:"):
49
+ user_messages = []
50
+ assistant_messages = []
51
+
52
+ lines = text.split("\n")
53
+
54
+ current_user_message = ""
55
+ current_assistant_message = ""
56
+
57
+ for line in lines:
58
+ line = line.lstrip(" ")
59
+ if line.startswith(user_identifier):
60
+ if current_assistant_message:
61
+ assistant_messages.append(current_assistant_message.strip())
62
+ current_assistant_message = ""
63
+ current_user_message += line.replace(user_identifier, "").strip() + " "
64
+ elif line.startswith(ai_identifier):
65
+ if current_user_message:
66
+ user_messages.append(current_user_message.strip())
67
+ current_user_message = ""
68
+ current_assistant_message += line.replace(ai_identifier, "").strip() + " "
69
+
70
+ if current_user_message:
71
+ user_messages.append(current_user_message.strip())
72
+ if current_assistant_message:
73
+ assistant_messages.append(current_assistant_message.strip())
74
+
75
+ return user_messages, assistant_messages
76
+
77
+
78
+ def llama_v2_prompt(
79
+ messages: list[dict],
80
+ system_prompt=None
81
+ ):
82
+ B_INST, E_INST = "[INST]", "[/INST]"
83
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
84
+ BOS, EOS = "<s>", "</s>"
85
+ if system_prompt:
86
+ DEFAULT_SYSTEM_PROMPT = system_prompt
87
+ else:
88
+ DEFAULT_SYSTEM_PROMPT = f"""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."""
89
+
90
+ if messages[0]["role"] != "system":
91
+ messages = [
92
+ {
93
+ "role": "system",
94
+ "content": DEFAULT_SYSTEM_PROMPT,
95
+ }
96
+ ] + messages
97
+ messages = [
98
+ {
99
+ "role": messages[1]["role"],
100
+ "content": B_SYS + messages[0]["content"] + E_SYS + messages[1]["content"],
101
+ }
102
+ ] + messages[2:]
103
+
104
+ messages_list = [
105
+ f"{BOS}{B_INST} {(prompt['content']).strip()} {E_INST} {(answer['content']).strip()} {EOS}"
106
+ for prompt, answer in zip(messages[::2], messages[1::2])
107
+ ]
108
+ if messages[-1]["role"] == "user":
109
+ messages_list.append(f"{BOS}{B_INST} {(messages[-1]['content']).strip()} {E_INST}")
110
+
111
+ return "".join(messages_list)
112
+
113
+
114
+ prompt_translator = {"_age_": "age",
115
+ "_gender_": "gender",
116
+ "_socioeco_": "socioeconomic status",
117
+ "_education_": "education level",}
118
+
119
+
120
+ class TextDataset(Dataset):
121
+ def __init__(self, directory, tokenizer, model, label_idf="_age_", label_to_id=None,
122
+ convert_to_llama2_format=False, user_identifier="HUMAN:", ai_identifier="ASSISTANT:", control_probe=False,
123
+ additional_datas=None, residual_stream=False, new_format=False, if_augmented=False, k=20,
124
+ remove_last_ai_response=False, include_inst=False, one_hot=False, last_tok_pos=-1):
125
+ self.file_paths = [os.path.join(directory, f) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)) and f.endswith('.txt')]
126
+ self.tokenizer = tokenizer
127
+ self.labels = []
128
+ self.acts = []
129
+ self.texts = []
130
+ self.label_idf = label_idf
131
+ self.label_to_id = label_to_id
132
+ self.model = model
133
+ self.convert_to_llama2_format = convert_to_llama2_format
134
+ self.user_identifier = user_identifier
135
+ self.ai_identifier = ai_identifier
136
+ self.additional_datas = additional_datas
137
+ self.residual_stream = residual_stream
138
+ self.new_format = new_format
139
+ self.if_augmented = if_augmented
140
+ self.k = k
141
+ self.if_remove_last_ai_response = remove_last_ai_response
142
+ self.include_inst = include_inst
143
+ self.one_hot = one_hot
144
+ self.last_tok_pos = last_tok_pos
145
+ self.control_probe = control_probe
146
+ if self.additional_datas:
147
+ for directory in self.additional_datas:
148
+ self.file_paths += [os.path.join(directory, f) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)) and f.endswith('.txt')]
149
+ self._load_in_data()
150
+
151
+ def __len__(self):
152
+ return len(self.texts)
153
+
154
+ def _load_in_data(self):
155
+ for idx in tqdm(range(len(self.file_paths))):
156
+ file_path = self.file_paths[idx]
157
+ corrupted_file_paths = []
158
+
159
+ int_idx = file_path[file_path.find("conversation_")+len("conversation_"):]
160
+ int_idx = int(int_idx[:int_idx.find("_")])
161
+
162
+ with open(file_path, 'r', encoding='utf-8') as f:
163
+ text = f.read()
164
+
165
+ if self.convert_to_llama2_format:
166
+ if "### Human:" in text:
167
+ user_msgs, ai_msgs = split_conversation(text, "### Human:", "### Assistant:")
168
+ elif "### User:" in text:
169
+ user_msgs, ai_msgs = split_conversation(text, "### User:", "### Assistant:")
170
+ else:
171
+ user_msgs, ai_msgs = split_conversation(text, self.user_identifier, self.ai_identifier)
172
+ messages_dict = []
173
+
174
+ for user_msg, ai_msg in zip(user_msgs, ai_msgs):
175
+ messages_dict.append({'content': user_msg, 'role': 'user'})
176
+ messages_dict.append({'content': ai_msg, 'role': 'assistant'})
177
+
178
+ if len(messages_dict) < 1:
179
+ corrupted_file_paths.append(file_path)
180
+ print(f"Corrupted file at {file_path}")
181
+ continue
182
+
183
+ if self.if_remove_last_ai_response and messages_dict[-1]["role"] == "assistant":
184
+ messages_dict = messages_dict[:-1]
185
+ try:
186
+ text = llama_v2_prompt(messages_dict)
187
+ except:
188
+ corrupted_file_paths.append(file_path)
189
+ print(f"Corrupted file at {file_path}")
190
+ continue
191
+
192
+ if self.new_format and self.if_remove_last_ai_response and self.include_inst:
193
+ text = text[text.find("<s>") + len("<s>"):]
194
+ elif self.new_format and self.include_inst:
195
+ text = text[text.find("<s>") + len("<s>"):]
196
+ elif self.new_format:
197
+ text = text[text.find("<s>") + len("<s>"): text.rfind("[/INST]") - 1]
198
+
199
+ label = file_path[file_path.rfind(self.label_idf) + len(self.label_idf):file_path.rfind(".txt")]
200
+
201
+ if label not in self.label_to_id.keys():
202
+ continue
203
+
204
+ if self.label_to_id:
205
+ label = self.label_to_id[label]
206
+
207
+ if self.one_hot:
208
+ label = F.one_hot(torch.Tensor([label]).to(torch.long), len(self.label_to_id.keys()))
209
+
210
+
211
+ if not self.control_probe:
212
+ text += f" I think the {prompt_translator[self.label_idf]} of this user is"
213
+ with torch.no_grad():
214
+ encoding = self.tokenizer(
215
+ text,
216
+ truncation=True,
217
+ max_length=2048,
218
+ return_attention_mask=True,
219
+ return_tensors='pt'
220
+ )
221
+
222
+ features = OrderedDict()
223
+ for name, module in self.model.named_modules():
224
+ if name.endswith(".mlp") or name.endswith(".embed_tokens"):
225
+ features[name] = ModuleHook(module)
226
+
227
+ # Get the device from the model
228
+ device = next(self.model.parameters()).device
229
+ output = self.model(input_ids=encoding['input_ids'].to(device),
230
+ attention_mask=encoding['attention_mask'].to(device),
231
+ output_hidden_states=True,
232
+ return_dict=True)
233
+ for feature in features.values():
234
+ feature.close()
235
+
236
+ last_acts = []
237
+ if self.if_augmented:
238
+ if self.residual_stream:
239
+ for layer_num in range(41):
240
+ last_acts.append(output["hidden_states"][layer_num][:, -self.k:].detach().cpu().clone().to(torch.float))
241
+ last_acts = torch.cat(last_acts, dim=0)
242
+ else:
243
+ last_acts.append(features['model.embed_tokens'].features[0][:, -self.k:].detach().cpu().clone().to(torch.float))
244
+ for layer_num in range(1, 41):
245
+ last_acts.append(features[f'model.layers.{layer_num - 1}.mlp'].features[0][:, -self.k:].detach().cpu().clone().to(torch.float))
246
+ last_acts = torch.cat(last_acts, dim=0)
247
+ else:
248
+ if self.residual_stream:
249
+ for layer_num in range(41):
250
+ last_acts.append(output["hidden_states"][layer_num][:, -1].detach().cpu().clone().to(torch.float))
251
+ last_acts = torch.cat(last_acts)
252
+ else:
253
+ last_acts.append(features['model.embed_tokens'].features[0][:, -1].detach().cpu().clone().to(torch.float))
254
+ for layer_num in range(1, 41):
255
+ last_acts.append(features[f'model.layers.{layer_num - 1}.mlp'].features[0][:, -1].detach().cpu().clone().to(torch.float))
256
+ last_acts = torch.cat(last_acts)
257
+
258
+ self.texts.append(text)
259
+ self.labels.append(label)
260
+ self.acts.append(last_acts)
261
+
262
+ for path in corrupted_file_paths:
263
+ self.file_paths.remove(path)
264
+ def __getitem__(self, idx):
265
+ label = self.labels[idx]
266
+ text = self.texts[idx]
267
+
268
+ if self.if_augmented:
269
+ random_k = torch.randint(0, self.k, [1])[0].item()
270
+ hidden_states = self.acts[idx][:, -random_k]
271
+ else:
272
+ hidden_states = self.acts[idx]
273
+
274
+ return {
275
+ 'hidden_states': hidden_states,
276
+ 'file_path': self.file_paths[idx],
277
+ 'age': label,
278
+ 'text': text,
279
+ }
280
+
src/intervention_utils.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from src.probes import ProbeClassification, ProbeClassificationMixScaler, LinearProbeClassification, LinearProbeClassificationMixScaler
2
+ import os
3
+ import torch.nn.functional as F
4
+
5
+ import torch
6
+ from tqdm.auto import tqdm
7
+
8
+ from src.dataset import llama_v2_prompt
9
+ import numpy as np
10
+
11
+ from torch import nn
12
+ device = "cuda"
13
+ torch_device = "cuda"
14
+
15
+
16
+ def load_probe_classifier(model_func, input_dim, num_classes, weight_path, **kwargs):
17
+ """
18
+ Instantiate a ProbeClassification model and load its pretrained weights.
19
+
20
+ Args:
21
+ - input_dim (int): Input dimension for the classifier.
22
+ - num_classes (int): Number of classes for classification.
23
+ - weight_path (str): Path to the pretrained weights.
24
+
25
+ Returns:
26
+ - model: The ProbeClassification model with loaded weights.
27
+ """
28
+
29
+ # Instantiate the model
30
+ model = model_func(device, num_classes, input_dim, **kwargs)
31
+
32
+ # Load the pretrained weights into the model
33
+ model.load_state_dict(torch.load(weight_path))
34
+
35
+ return model
36
+
37
+
38
+ num_classes = {"age": 4,
39
+ "gender": 2,
40
+ "education": 3,
41
+ "socioeco": 3,}
42
+
43
+
44
+ def return_classifier_dict(directory, model_func, chosen_layer=None, mix_scaler=False, sklearn=False, **kwargs):
45
+ checkpoint_paths = os.listdir(directory)
46
+ # file_paths = [os.path.join(directory, file) for file in checkpoint_paths if file.endswith("pth")]
47
+ classifier_dict = {}
48
+ for i in range(len(checkpoint_paths)):
49
+ category = checkpoint_paths[i][:checkpoint_paths[i].find("_")]
50
+ weight_path = os.path.join(directory, checkpoint_paths[i])
51
+ num_class = num_classes[category]
52
+ if category == "gender" and sklearn:
53
+ num_class = 1
54
+ if category not in classifier_dict.keys():
55
+ classifier_dict[category] = {}
56
+ if mix_scaler:
57
+ classifier_dict[category]["all"] = load_probe_classifier(model_func, 5120,
58
+ num_classes=num_class,
59
+ weight_path=weight_path, **kwargs)
60
+ else:
61
+ layer_num = int(checkpoint_paths[i][checkpoint_paths[i].rfind("_") + 1: checkpoint_paths[i].rfind(".pth")])
62
+
63
+ if chosen_layer is None or layer_num == chosen_layer:
64
+ try:
65
+ classifier_dict[category][layer_num] = load_probe_classifier(model_func, 5120,
66
+ num_classes=num_class,
67
+ weight_path=weight_path, **kwargs)
68
+ except Exception as e:
69
+ print(category)
70
+ # print(e)
71
+
72
+ return classifier_dict
73
+
74
+
75
+ def split_into_messages(text: str) -> list[str]:
76
+ # Constants used for splitting
77
+ B_INST, E_INST = "[INST]", "[/INST]"
78
+
79
+ # Use the tokens to split the text
80
+ parts = []
81
+ current_message = ""
82
+
83
+ for word in text.split():
84
+ # If we encounter a start or end token, and there's a current message, store it
85
+ if word in [B_INST, E_INST] and current_message:
86
+ parts.append(current_message.strip())
87
+ current_message = ""
88
+ # If the word is not a token, add it to the current message
89
+ elif word not in [B_INST, E_INST]:
90
+ current_message += word + " "
91
+
92
+ # Append any remaining message
93
+ if current_message:
94
+ parts.append(current_message.strip())
95
+
96
+ return parts
97
+
98
+
99
+ def llama_v2_reverse(prompt: str) -> list[dict]:
100
+ # Constants used in the LLaMa style
101
+ B_INST, E_INST = "[INST]", "[/INST]"
102
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
103
+ BOS, EOS = "<s>", "</s>"
104
+ messages = []
105
+ sys_start = prompt.find(B_SYS)
106
+ sys_end = prompt.rfind(E_SYS)
107
+ if sys_start != -1 and sys_end != -1:
108
+ system_msg = prompt[sys_start + len(B_SYS): sys_end]
109
+ messages.append({"role": "system", "content": system_msg})
110
+ prompt = prompt[sys_end + len(E_SYS):]
111
+
112
+ user_ai_msgs = split_into_messages(prompt)
113
+
114
+ user_turn = True
115
+ for message in user_ai_msgs:
116
+ if user_turn:
117
+ messages.append({"role": "user", "content": message})
118
+ else:
119
+ messages.append({"role": "assistant", "content": message})
120
+
121
+ if user_turn:
122
+ user_turn = False
123
+ else:
124
+ user_turn = True
125
+
126
+ return messages
127
+
128
+
129
+ def optimize_one_inter_rep(inter_rep, layer_name, target, probe,
130
+ lr=1e-2,
131
+ N=4, normalized=False):
132
+ global first_time
133
+ tensor = (inter_rep.clone()).to(torch_device).requires_grad_(True)
134
+ rep_f = lambda: tensor
135
+ target_clone = target.clone().to(torch_device).to(torch.float)
136
+
137
+ cur_input_tensor = rep_f().clone().detach()
138
+ if normalized:
139
+ cur_input_tensor = rep_f() + target_clone.view(1, -1) @ probe.proj[0].weight * N * 100 / rep_f().norm()
140
+ else:
141
+ cur_input_tensor = rep_f() + target_clone.view(1, -1) @ probe.proj[0].weight * N
142
+ return cur_input_tensor.clone()
143
+
144
+
145
+ def edit_inter_rep_multi_layers(output, layer_name):
146
+ """
147
+ This function must be called inside the script, given classifier dict and other hyperparameters are undefined in this function
148
+ """
149
+ if residual:
150
+ layer_num = layer_name[layer_name.rfind("model.layers.") + len("model.layers."):]
151
+ else:
152
+ layer_num = layer_name[layer_name.rfind("model.layers.") + len("model.layers."):layer_name.rfind(".mlp")]
153
+ layer_num = int(layer_num)
154
+ probe = classifier_dict[attribute][layer_num + 1]
155
+ cloned_inter_rep = output[0][0][-1].unsqueeze(0).detach().clone().to(torch.float)
156
+ with torch.enable_grad():
157
+ cloned_inter_rep = optimize_one_inter_rep(cloned_inter_rep, layer_name,
158
+ cf_target, probe,
159
+ lr=lr,
160
+ N=N,)
161
+ # output[1] = cloned_inter_rep.to(torch.float16)
162
+ # print(len(output))
163
+ output[0][0][-1] = cloned_inter_rep[0].to(torch.float16)
164
+ return output
src/losses.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import scipy.ndimage as nd
4
+ import numpy as np
5
+
6
+
7
+ def get_device():
8
+ use_cuda = torch.cuda.is_available()
9
+ device = torch.device("cuda:0" if use_cuda else "cpu")
10
+ return device
11
+
12
+
13
+ def relu_evidence(y):
14
+ return F.relu(y)
15
+
16
+
17
+ def one_hot_embedding(labels, num_classes=10):
18
+ # Convert to One Hot Encoding
19
+ y = torch.eye(num_classes)
20
+ return y[labels]
21
+
22
+
23
+ def exp_evidence(y):
24
+ return torch.exp(torch.clamp(y, -10, 10))
25
+
26
+
27
+ def softplus_evidence(y):
28
+ return F.softplus(y)
29
+
30
+
31
+ def kl_divergence(alpha, num_classes, device=None):
32
+ if not device:
33
+ device = get_device()
34
+ ones = torch.ones([1, num_classes], dtype=torch.float32, device=device)
35
+ sum_alpha = torch.sum(alpha, dim=1, keepdim=True)
36
+ first_term = (
37
+ torch.lgamma(sum_alpha)
38
+ - torch.lgamma(alpha).sum(dim=1, keepdim=True)
39
+ + torch.lgamma(ones).sum(dim=1, keepdim=True)
40
+ - torch.lgamma(ones.sum(dim=1, keepdim=True))
41
+ )
42
+ second_term = (
43
+ (alpha - ones)
44
+ .mul(torch.digamma(alpha) - torch.digamma(sum_alpha))
45
+ .sum(dim=1, keepdim=True)
46
+ )
47
+ kl = first_term + second_term
48
+ return kl
49
+
50
+
51
+ def loglikelihood_loss(y, alpha, device=None):
52
+ if not device:
53
+ device = get_device()
54
+ y = y.to(device)
55
+ alpha = alpha.to(device)
56
+ S = torch.sum(alpha, dim=1, keepdim=True)
57
+ loglikelihood_err = torch.sum((y - (alpha / S)) ** 2, dim=1, keepdim=True)
58
+ loglikelihood_var = torch.sum(
59
+ alpha * (S - alpha) / (S * S * (S + 1)), dim=1, keepdim=True
60
+ )
61
+ loglikelihood = loglikelihood_err + loglikelihood_var
62
+ return loglikelihood
63
+
64
+
65
+ def mse_loss(y, alpha, epoch_num, num_classes, annealing_step, device=None):
66
+ if not device:
67
+ device = get_device()
68
+ y = y.to(device)
69
+ alpha = alpha.to(device)
70
+ loglikelihood = loglikelihood_loss(y, alpha, device=device)
71
+
72
+ annealing_coef = torch.min(
73
+ torch.tensor(1.0, dtype=torch.float32),
74
+ torch.tensor(epoch_num / annealing_step, dtype=torch.float32),
75
+ )
76
+
77
+ kl_alpha = (alpha - 1) * (1 - y) + 1
78
+ kl_div = annealing_coef * kl_divergence(kl_alpha, num_classes, device=device)
79
+ return loglikelihood + kl_div
80
+
81
+
82
+ def edl_loss(func, y, alpha, epoch_num, num_classes, annealing_step, device=None):
83
+ y = y.to(device)
84
+ alpha = alpha.to(device)
85
+ S = torch.sum(alpha, dim=1, keepdim=True)
86
+
87
+ A = torch.sum(y * (func(S) - func(alpha)), dim=1, keepdim=True)
88
+
89
+ annealing_coef = torch.min(
90
+ torch.tensor(1.0, dtype=torch.float32),
91
+ torch.tensor(epoch_num / annealing_step, dtype=torch.float32),
92
+ )
93
+
94
+ kl_alpha = (alpha - 1) * (1 - y) + 1
95
+ kl_div = annealing_coef * kl_divergence(kl_alpha, num_classes, device=device)
96
+ return A + kl_div
97
+
98
+
99
+ def edl_mse_loss(output, target, epoch_num, num_classes, annealing_step=10, device="cuda", probability=False):
100
+ if not probability:
101
+ target = one_hot_embedding(target, num_classes)
102
+ else:
103
+ target = target
104
+ if not device:
105
+ device = get_device()
106
+ evidence = relu_evidence(output)
107
+ alpha = evidence + 1
108
+ loss = torch.mean(
109
+ mse_loss(target, alpha, epoch_num, num_classes, annealing_step, device=device)
110
+ )
111
+ return loss
112
+
113
+
114
+ def edl_log_loss(output, target, epoch_num, num_classes, annealing_step, device="cuda"):
115
+ if not device:
116
+ device = get_device()
117
+ evidence = relu_evidence(output)
118
+ alpha = evidence + 1
119
+ loss = torch.mean(
120
+ edl_loss(
121
+ torch.log, target, alpha, epoch_num, num_classes, annealing_step, device
122
+ )
123
+ )
124
+ return loss
125
+
126
+
127
+ def edl_digamma_loss(
128
+ output, target, epoch_num, num_classes, annealing_step, device=None
129
+ ):
130
+ if not device:
131
+ device = get_device()
132
+ evidence = relu_evidence(output)
133
+ alpha = evidence + 1
134
+ loss = torch.mean(
135
+ edl_loss(
136
+ torch.digamma, target, alpha, epoch_num, num_classes, annealing_step, device
137
+ )
138
+ )
139
+ return loss
140
+
141
+
142
+ def calc_prob_uncertinty(p):
143
+ evidence = relu_evidence(p)
144
+ alpha = evidence + 1
145
+ uncertainty = 6 / torch.sum(alpha, dim=1, keepdim=True)
146
+ _, preds = torch.max(p, 1)
147
+ prob = alpha / torch.sum(alpha, dim=1, keepdim=True)
148
+ prob = prob.flatten()
149
+ preds = preds.flatten()
150
+ return prob, uncertainty
src/probes.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torch import nn
4
+
5
+ class ProbeClassification(nn.Module):
6
+ def __init__(self, device, probe_class, input_dim=512, hidden_neurons=128): # from 0 to 15
7
+ super().__init__()
8
+ self.input_dim = input_dim
9
+ self.probe_class = probe_class
10
+ self.proj = nn.Sequential(
11
+ nn.Linear(self.input_dim, hidden_neurons),
12
+ nn.ReLU(True),
13
+ nn.Linear(hidden_neurons, self.probe_class),
14
+ )
15
+ self.apply(self._init_weights)
16
+ # logger.info("number of parameters: %e", sum(p.numel() for p in self.parameters()))
17
+ self.to(device)
18
+ def forward(self, act, y=None):
19
+ # [B, f], [B]
20
+ logits = self.proj(act)#.reshape(-1, self.probe_number, self.probe_class) # [B, C]
21
+ if y is None:
22
+ return logits, None
23
+ else:
24
+ targets = y.to(torch.long)
25
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)
26
+ return logits, loss
27
+
28
+ def _init_weights(self, module):
29
+ if isinstance(module, (nn.Linear, nn.Embedding)):
30
+ module.weight.data.normal_(mean=0.0, std=0.02)
31
+ if isinstance(module, nn.Linear) and module.bias is not None:
32
+ module.bias.data.zero_()
33
+ elif isinstance(module, nn.LayerNorm):
34
+ module.bias.data.zero_()
35
+ module.weight.data.fill_(1.0)
36
+
37
+ def configure_optimizers(self, train_config):
38
+ """
39
+ This long function is unfortunately doing something very simple and is being very defensive:
40
+ We are separating out all parameters of the model into two buckets: those that will experience
41
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
42
+ We are then returning the PyTorch optimizer object.
43
+ """
44
+ # separate out all parameters to those that will and won't experience regularizing weight decay
45
+ decay = set()
46
+ no_decay = set()
47
+ whitelist_weight_modules = (torch.nn.Linear, )
48
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
49
+ for mn, m in self.named_modules():
50
+ for pn, p in m.named_parameters():
51
+ fpn = '%s.%s' % (mn, pn) if mn else pn # full param name
52
+ if pn.endswith('bias'):
53
+ # biases of whitelist modules will be weight decayed
54
+ decay.add(fpn)
55
+ elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
56
+ # weights of whitelist modules will be weight decayed
57
+ decay.add(fpn)
58
+ elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
59
+ # weights of blacklist modules will NOT be weight decayed
60
+ no_decay.add(fpn)
61
+
62
+ # special case the position embedding parameter in the root GPT module as not decayed
63
+ # no_decay.add('pos_emb')
64
+
65
+ # validate that we considered every parameter
66
+ param_dict = {pn: p for pn, p in self.named_parameters()}
67
+ inter_params = decay & no_decay
68
+ union_params = decay | no_decay
69
+ assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
70
+ assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \
71
+ % (str(param_dict.keys() - union_params), )
72
+ print("Decayed:", decay)
73
+ # create the pytorch optimizer object
74
+ optim_groups = [
75
+ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": train_config.weight_decay},
76
+ {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
77
+ ]
78
+ optimizer = torch.optim.Adam(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)
79
+ scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.75, patience=0)
80
+ return optimizer, scheduler
81
+
82
+
83
+ class LinearProbeClassification(nn.Module):
84
+ def __init__(self, device, probe_class, input_dim=512, logistic=False, Relu=False, TanH=False): # from 0 to 15
85
+ super().__init__()
86
+ self.input_dim = input_dim
87
+ self.probe_class = probe_class
88
+ if logistic:
89
+ self.proj = nn.Sequential(
90
+ nn.Linear(self.input_dim, self.probe_class),
91
+ nn.Sigmoid()
92
+ )
93
+ elif Relu:
94
+ self.proj = nn.Sequential(
95
+ nn.Linear(self.input_dim, self.probe_class),
96
+ nn.ReLU(True)
97
+ )
98
+ elif TanH:
99
+ self.proj = nn.Sequential(
100
+ nn.Linear(self.input_dim, self.probe_class),
101
+ # nn.Hardtanh(inplace=True, min_val=0.001, max_val=0.999)
102
+ nn.Hardsigmoid(inplace=True)
103
+ )
104
+ else:
105
+
106
+ self.proj = nn.Sequential(
107
+ nn.Linear(self.input_dim, self.probe_class),
108
+ )
109
+
110
+ self.apply(self._init_weights)
111
+ # logger.info("number of parameters: %e", sum(p.numel() for p in self.parameters()))
112
+ self.to(device)
113
+ def forward(self, act, y=None):
114
+ # [B, f], [B]
115
+ logits = self.proj(act)#.reshape(-1, self.probe_number, self.probe_class) # [B, C]
116
+ if y is None:
117
+ return logits, None
118
+ else:
119
+ targets = y.to(torch.long)
120
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)
121
+ return logits, loss
122
+
123
+ def _init_weights(self, module):
124
+ if isinstance(module, (nn.Linear, nn.Embedding)):
125
+ module.weight.data.normal_(mean=0.0, std=0.02)
126
+ if isinstance(module, nn.Linear) and module.bias is not None:
127
+ module.bias.data.zero_()
128
+ elif isinstance(module, nn.LayerNorm):
129
+ module.bias.data.zero_()
130
+ module.weight.data.fill_(1.0)
131
+
132
+ def configure_optimizers(self, train_config):
133
+ """
134
+ This long function is unfortunately doing something very simple and is being very defensive:
135
+ We are separating out all parameters of the model into two buckets: those that will experience
136
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
137
+ We are then returning the PyTorch optimizer object.
138
+ """
139
+ # separate out all parameters to those that will and won't experience regularizing weight decay
140
+ decay = set()
141
+ no_decay = set()
142
+ whitelist_weight_modules = (torch.nn.Linear, )
143
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
144
+ for mn, m in self.named_modules():
145
+ for pn, p in m.named_parameters():
146
+ fpn = '%s.%s' % (mn, pn) if mn else pn # full param name
147
+ if pn.endswith('bias'):
148
+ # biases of whitelist modules will be weight decayed
149
+ decay.add(fpn)
150
+ elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
151
+ # weights of whitelist modules will be weight decayed
152
+ decay.add(fpn)
153
+ elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
154
+ # weights of blacklist modules will NOT be weight decayed
155
+ no_decay.add(fpn)
156
+
157
+ # special case the position embedding parameter in the root GPT module as not decayed
158
+ # no_decay.add('pos_emb')
159
+
160
+ # validate that we considered every parameter
161
+ param_dict = {pn: p for pn, p in self.named_parameters()}
162
+ inter_params = decay & no_decay
163
+ union_params = decay | no_decay
164
+ assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
165
+ assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \
166
+ % (str(param_dict.keys() - union_params), )
167
+ print("Decayed:", decay)
168
+ # create the pytorch optimizer object
169
+ optim_groups = [
170
+ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": train_config.weight_decay},
171
+ {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
172
+ ]
173
+ optimizer = torch.optim.Adam(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)
174
+ scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.75, patience=0)
175
+ return optimizer, scheduler
176
+
177
+
178
+ class TwoLayerLinearProbeClassification(nn.Module):
179
+ def __init__(self, device, probe_class, input_dim=512, logistic=False): # from 0 to 15
180
+ super().__init__()
181
+ self.input_dim = input_dim
182
+ self.probe_class = probe_class
183
+ if not logistic:
184
+ self.proj = nn.Sequential(
185
+ nn.Linear(self.input_dim, self.input_dim),
186
+ nn.Linear(self.input_dim, self.probe_class),
187
+ )
188
+ else:
189
+ self.proj = nn.Sequential(
190
+ nn.Linear(self.input_dim, self.input_dim),
191
+ nn.Linear(self.input_dim, self.probe_class),
192
+ nn.Sigmoid()
193
+ )
194
+
195
+ self.apply(self._init_weights)
196
+ # logger.info("number of parameters: %e", sum(p.numel() for p in self.parameters()))
197
+ self.to(device)
198
+ def forward(self, act, y=None):
199
+ # [B, f], [B]
200
+ logits = self.proj(act)#.reshape(-1, self.probe_number, self.probe_class) # [B, C]
201
+ if y is None:
202
+ return logits, None
203
+ else:
204
+ targets = y.to(torch.long)
205
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)
206
+ return logits, loss
207
+
208
+ def _init_weights(self, module):
209
+ if isinstance(module, (nn.Linear, nn.Embedding)):
210
+ module.weight.data.normal_(mean=0.0, std=0.02)
211
+ if isinstance(module, nn.Linear) and module.bias is not None:
212
+ module.bias.data.zero_()
213
+ elif isinstance(module, nn.LayerNorm):
214
+ module.bias.data.zero_()
215
+ module.weight.data.fill_(1.0)
216
+
217
+ def configure_optimizers(self, train_config):
218
+ """
219
+ This long function is unfortunately doing something very simple and is being very defensive:
220
+ We are separating out all parameters of the model into two buckets: those that will experience
221
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
222
+ We are then returning the PyTorch optimizer object.
223
+ """
224
+ # separate out all parameters to those that will and won't experience regularizing weight decay
225
+ decay = set()
226
+ no_decay = set()
227
+ whitelist_weight_modules = (torch.nn.Linear, )
228
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
229
+ for mn, m in self.named_modules():
230
+ for pn, p in m.named_parameters():
231
+ fpn = '%s.%s' % (mn, pn) if mn else pn # full param name
232
+ if pn.endswith('bias'):
233
+ # biases of whitelist modules will be weight decayed
234
+ decay.add(fpn)
235
+ elif pn.endswith('weight') and isinstance(m, whitelist_weight_modules):
236
+ # weights of whitelist modules will be weight decayed
237
+ decay.add(fpn)
238
+ elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
239
+ # weights of blacklist modules will NOT be weight decayed
240
+ no_decay.add(fpn)
241
+
242
+ # special case the position embedding parameter in the root GPT module as not decayed
243
+ # no_decay.add('pos_emb')
244
+
245
+ # validate that we considered every parameter
246
+ param_dict = {pn: p for pn, p in self.named_parameters()}
247
+ inter_params = decay & no_decay
248
+ union_params = decay | no_decay
249
+ assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
250
+ assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \
251
+ % (str(param_dict.keys() - union_params), )
252
+ print("Decayed:", decay)
253
+ # create the pytorch optimizer object
254
+ optim_groups = [
255
+ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": train_config.weight_decay},
256
+ {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
257
+ ]
258
+ optimizer = torch.optim.Adam(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)
259
+ scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.75, patience=0)
260
+ return optimizer, scheduler
261
+
262
+
263
+ class ProbeClassificationMixScaler(nn.Module):
264
+ def __init__(self, device, probe_class, input_dim=512, num_layers=41, soft_weight_lr_rate=1e-1,
265
+ hidden_neurons=128): # from 0 to 15
266
+ super().__init__()
267
+ self.input_dim = input_dim
268
+ self.probe_class = probe_class
269
+ self.num_layers = num_layers
270
+ # self.mix_weights = torch.nn.Parameter(1 / num_layers * torch.ones(num_layers), requires_grad=True)
271
+ self.mix_weights = nn.Linear(num_layers, 1, bias=False)
272
+ torch.nn.init.constant_(self.mix_weights.weight, 1 / num_layers)
273
+ self.soft_weight_lr_rate=soft_weight_lr_rate
274
+ self.proj = nn.Sequential(
275
+ nn.Linear(self.input_dim, hidden_neurons),
276
+ nn.ReLU(True),
277
+ nn.Linear(hidden_neurons, self.probe_class),
278
+ )
279
+ self.apply(self._init_weights)
280
+ # logger.info("number of parameters: %e", sum(p.numel() for p in self.parameters()))
281
+ self.to(device)
282
+ def forward(self, act, y=None):
283
+ # [B, f], [B]
284
+ softmaxed_weights = torch.nn.functional.softmax(self.mix_weights.weight, dim=1)
285
+ act = act.permute([0, 2, 1])
286
+ act = (act @ softmaxed_weights.T)[..., 0]
287
+ logits = self.proj(act)#.reshape(-1, self.probe_number, self.probe_class) # [B, C]
288
+ if y is None:
289
+ return logits, None
290
+ else:
291
+ targets = y.to(torch.long)
292
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)
293
+ return logits, loss
294
+
295
+ def _init_weights(self, module):
296
+ if isinstance(module, (nn.Linear, nn.Embedding)):
297
+ module.weight.data.normal_(mean=0.0, std=0.02)
298
+ if isinstance(module, nn.Linear) and module.bias is not None:
299
+ module.bias.data.zero_()
300
+ elif isinstance(module, nn.LayerNorm):
301
+ module.bias.data.zero_()
302
+ module.weight.data.fill_(1.0)
303
+
304
+ def configure_optimizers(self, train_config):
305
+ """
306
+ This long function is unfortunately doing something very simple and is being very defensive:
307
+ We are separating out all parameters of the model into two buckets: those that will experience
308
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
309
+ We are then returning the PyTorch optimizer object.
310
+ """
311
+ # separate out all parameters to those that will and won't experience regularizing weight decay
312
+ decay = set()
313
+ no_decay = set()
314
+ whitelist_weight_modules = (torch.nn.Linear, )
315
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
316
+ for mn, m in self.named_modules():
317
+ for pn, p in m.named_parameters():
318
+ fpn = '%s.%s' % (mn, pn) if mn else pn # full param name
319
+ if pn.endswith('bias'):
320
+ # biases of whitelist modules will be weight decayed
321
+ decay.add(fpn)
322
+ elif pn.endswith('weight') and (not "mix" in fpn) and isinstance(m, whitelist_weight_modules):
323
+ # weights of whitelist modules will be weight decayed
324
+ decay.add(fpn)
325
+ elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
326
+ # weights of blacklist modules will NOT be weight decayed
327
+ no_decay.add(fpn)
328
+
329
+ # special case the position embedding parameter in the root GPT module as not decayed
330
+ # no_decay.add('pos_emb')
331
+
332
+ # validate that we considered every parameter
333
+ param_dict = {pn: p for pn, p in self.named_parameters()}
334
+ inter_params = decay & no_decay
335
+ union_params = decay | no_decay
336
+ assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
337
+ # assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \
338
+ # % (str(param_dict.keys() - union_params), )
339
+ print("Decayed:", decay)
340
+ # create the pytorch optimizer object
341
+ optim_groups = [
342
+ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": train_config.weight_decay},
343
+ {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
344
+ {'params': self.mix_weights.weight, "lr": self.soft_weight_lr_rate, "weight_decay": train_config.weight_decay},
345
+ ]
346
+ optimizer = torch.optim.Adam(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)
347
+ scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.75, patience=0)
348
+ return optimizer, scheduler
349
+
350
+
351
+ class LinearProbeClassificationMixScaler(nn.Module):
352
+ def __init__(self, device, probe_class, input_dim=512, num_layers=41, soft_weight_lr_rate=1e-1,
353
+ logistic=False): # from 0 to 15
354
+ super().__init__()
355
+ self.input_dim = input_dim
356
+ self.probe_class = probe_class
357
+ self.num_layers = num_layers
358
+ # self.mix_weights = torch.nn.Parameter(1 / num_layers * torch.ones(num_layers), requires_grad=True)
359
+ self.mix_weights = nn.Linear(num_layers, 1, bias=False)
360
+ torch.nn.init.constant_(self.mix_weights.weight, 1 / num_layers)
361
+ self.soft_weight_lr_rate=soft_weight_lr_rate
362
+ if not logistic:
363
+ self.proj = nn.Sequential(
364
+ nn.Linear(self.input_dim, self.probe_class),
365
+ )
366
+ else:
367
+ self.proj = nn.Sequential(
368
+ nn.Linear(self.input_dim, self.probe_class),
369
+ nn.Sigmoid()
370
+ )
371
+ self.apply(self._init_weights)
372
+ # logger.info("number of parameters: %e", sum(p.numel() for p in self.parameters()))
373
+ self.to(device)
374
+ def forward(self, act, y=None):
375
+ # [B, f], [B]
376
+ softmaxed_weights = torch.nn.functional.softmax(self.mix_weights.weight, dim=1)
377
+ act = act.permute([0, 2, 1])
378
+ act = (act @ softmaxed_weights.T)[..., 0]
379
+ logits = self.proj(act)#.reshape(-1, self.probe_number, self.probe_class) # [B, C]
380
+ if y is None:
381
+ return logits, None
382
+ else:
383
+ targets = y.to(torch.long)
384
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)
385
+ return logits, loss
386
+
387
+ def _init_weights(self, module):
388
+ if isinstance(module, (nn.Linear, nn.Embedding)):
389
+ module.weight.data.normal_(mean=0.0, std=0.02)
390
+ if isinstance(module, nn.Linear) and module.bias is not None:
391
+ module.bias.data.zero_()
392
+ elif isinstance(module, nn.LayerNorm):
393
+ module.bias.data.zero_()
394
+ module.weight.data.fill_(1.0)
395
+
396
+ def configure_optimizers(self, train_config):
397
+ """
398
+ This long function is unfortunately doing something very simple and is being very defensive:
399
+ We are separating out all parameters of the model into two buckets: those that will experience
400
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
401
+ We are then returning the PyTorch optimizer object.
402
+ """
403
+ # separate out all parameters to those that will and won't experience regularizing weight decay
404
+ decay = set()
405
+ no_decay = set()
406
+ whitelist_weight_modules = (torch.nn.Linear, )
407
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
408
+ for mn, m in self.named_modules():
409
+ for pn, p in m.named_parameters():
410
+ fpn = '%s.%s' % (mn, pn) if mn else pn # full param name
411
+ if pn.endswith('bias'):
412
+ # biases of whitelist modules will be weight decayed
413
+ decay.add(fpn)
414
+ elif pn.endswith('weight') and (not "mix" in fpn) and isinstance(m, whitelist_weight_modules):
415
+ # weights of whitelist modules will be weight decayed
416
+ decay.add(fpn)
417
+ elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
418
+ # weights of blacklist modules will NOT be weight decayed
419
+ no_decay.add(fpn)
420
+
421
+ # special case the position embedding parameter in the root GPT module as not decayed
422
+ # no_decay.add('pos_emb')
423
+
424
+ # validate that we considered every parameter
425
+ param_dict = {pn: p for pn, p in self.named_parameters()}
426
+ inter_params = decay & no_decay
427
+ union_params = decay | no_decay
428
+ assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
429
+ # assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \
430
+ # % (str(param_dict.keys() - union_params), )
431
+ print("Decayed:", decay)
432
+ # create the pytorch optimizer object
433
+ optim_groups = [
434
+ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": train_config.weight_decay},
435
+ {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
436
+ {'params': self.mix_weights.weight, "lr": self.soft_weight_lr_rate, "weight_decay": train_config.weight_decay},
437
+ ]
438
+ optimizer = torch.optim.Adam(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)
439
+ scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.75, patience=0)
440
+ return optimizer, scheduler
441
+
442
+
443
+ class TwoLayerLinearProbeClassificationMixScaler(nn.Module):
444
+ def __init__(self, device, probe_class, input_dim=512, num_layers=41, soft_weight_lr_rate=1e-1,
445
+ logistic=False): # from 0 to 15
446
+ super().__init__()
447
+ self.input_dim = input_dim
448
+ self.probe_class = probe_class
449
+ self.num_layers = num_layers
450
+ # self.mix_weights = torch.nn.Parameter(1 / num_layers * torch.ones(num_layers), requires_grad=True)
451
+ self.mix_weights = nn.Linear(num_layers, 1, bias=False)
452
+ torch.nn.init.constant_(self.mix_weights.weight, 1 / num_layers)
453
+ self.soft_weight_lr_rate=soft_weight_lr_rate
454
+ self.rotates = nn.ModuleList([nn.Linear(5120, 5120) for _ in range(41)]),
455
+ if not logistic:
456
+ self.proj = nn.Sequential(
457
+ nn.Linear(self.input_dim, self.probe_class),
458
+ )
459
+ else:
460
+ self.proj = nn.Sequential(
461
+ nn.Linear(self.input_dim, self.probe_class),
462
+ nn.Sigmoid()
463
+ )
464
+ self.apply(self._init_weights)
465
+ # logger.info("number of parameters: %e", sum(p.numel() for p in self.parameters()))
466
+ self.to(device)
467
+ def forward(self, act, y=None):
468
+ # [B, f], [B]
469
+ outputs = []
470
+ for i in range(num_vectors):
471
+ output_i = self.rotates[i](act[:, i, :]) # shape: (batch_size, 5120)
472
+ outputs.append(output_i)
473
+
474
+ # Stack the outputs back together
475
+ act = torch.stack(outputs, dim=1)
476
+ softmaxed_weights = torch.nn.functional.softmax(self.mix_weights.weight, dim=1)
477
+ act = act.permute([0, 2, 1])
478
+ act = (act @ softmaxed_weights.T)[..., 0]
479
+ logits = self.proj(act)#.reshape(-1, self.probe_number, self.probe_class) # [B, C]
480
+ if y is None:
481
+ return logits, None
482
+ else:
483
+ targets = y.to(torch.long)
484
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-100)
485
+ return logits, loss
486
+
487
+ def _init_weights(self, module):
488
+ if isinstance(module, (nn.Linear, nn.Embedding)):
489
+ module.weight.data.normal_(mean=0.0, std=0.02)
490
+ if isinstance(module, nn.Linear) and module.bias is not None:
491
+ module.bias.data.zero_()
492
+ elif isinstance(module, nn.LayerNorm):
493
+ module.bias.data.zero_()
494
+ module.weight.data.fill_(1.0)
495
+
496
+ def configure_optimizers(self, train_config):
497
+ """
498
+ This long function is unfortunately doing something very simple and is being very defensive:
499
+ We are separating out all parameters of the model into two buckets: those that will experience
500
+ weight decay for regularization and those that won't (biases, and layernorm/embedding weights).
501
+ We are then returning the PyTorch optimizer object.
502
+ """
503
+ # separate out all parameters to those that will and won't experience regularizing weight decay
504
+ decay = set()
505
+ no_decay = set()
506
+ whitelist_weight_modules = (torch.nn.Linear, )
507
+ blacklist_weight_modules = (torch.nn.LayerNorm, torch.nn.Embedding)
508
+ for mn, m in self.named_modules():
509
+ for pn, p in m.named_parameters():
510
+ fpn = '%s.%s' % (mn, pn) if mn else pn # full param name
511
+ if pn.endswith('bias'):
512
+ # biases of whitelist modules will be weight decayed
513
+ decay.add(fpn)
514
+ elif pn.endswith('weight') and (not "mix" in fpn) and isinstance(m, whitelist_weight_modules):
515
+ # weights of whitelist modules will be weight decayed
516
+ decay.add(fpn)
517
+ elif pn.endswith('weight') and isinstance(m, blacklist_weight_modules):
518
+ # weights of blacklist modules will NOT be weight decayed
519
+ no_decay.add(fpn)
520
+
521
+ # special case the position embedding parameter in the root GPT module as not decayed
522
+ # no_decay.add('pos_emb')
523
+
524
+ # validate that we considered every parameter
525
+ param_dict = {pn: p for pn, p in self.named_parameters()}
526
+ inter_params = decay & no_decay
527
+ union_params = decay | no_decay
528
+ assert len(inter_params) == 0, "parameters %s made it into both decay/no_decay sets!" % (str(inter_params), )
529
+ # assert len(param_dict.keys() - union_params) == 0, "parameters %s were not separated into either decay/no_decay set!" \
530
+ # % (str(param_dict.keys() - union_params), )
531
+ print("Decayed:", decay)
532
+ # create the pytorch optimizer object
533
+ optim_groups = [
534
+ {"params": [param_dict[pn] for pn in sorted(list(decay))], "weight_decay": train_config.weight_decay},
535
+ {"params": [param_dict[pn] for pn in sorted(list(no_decay))], "weight_decay": 0.0},
536
+ {'params': self.mix_weights.weight, "lr": self.soft_weight_lr_rate, "weight_decay": train_config.weight_decay},
537
+ ]
538
+ optimizer = torch.optim.Adam(optim_groups, lr=train_config.learning_rate, betas=train_config.betas)
539
+ scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.75, patience=0)
540
+ return optimizer, scheduler
541
+
542
+
543
+ class TrainerConfig:
544
+ # optimization parameters
545
+ learning_rate = 1e-3
546
+ betas = (0.9, 0.95)
547
+ weight_decay = 0.1 # only applied on matmul weights
548
+
549
+ def __init__(self, **kwargs):
550
+ for k,v in kwargs.items():
551
+ setattr(self, k, v)
src/prompt_utils.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def split_into_messages(text: str) -> list[str]:
2
+ # Constants used for splitting
3
+ B_INST, E_INST = "[INST]", "[/INST]"
4
+
5
+ # Use the tokens to split the text
6
+ parts = []
7
+ current_message = ""
8
+
9
+ for word in text.split():
10
+ # If we encounter a start or end token, and there's a current message, store it
11
+ if word in [B_INST, E_INST] and current_message:
12
+ parts.append(current_message.strip())
13
+ current_message = ""
14
+ # If the word is not a token, add it to the current message
15
+ elif word not in [B_INST, E_INST]:
16
+ current_message += word + " "
17
+
18
+ # Append any remaining message
19
+ if current_message:
20
+ parts.append(current_message.strip())
21
+
22
+ return parts
23
+
24
+
25
+ def llama_v2_reverse(prompt: str) -> list[dict]:
26
+ # Constants used in the LLaMa style
27
+ B_INST, E_INST = "[INST]", "[/INST]"
28
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
29
+ BOS, EOS = "<s>", "</s>"
30
+ # DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."""
31
+
32
+ # Split by the message separators
33
+ # prompt = promp
34
+ # segments = [s.strip() for s in prompt.split(E_INST) if s.strip()]
35
+
36
+ messages = []
37
+ sys_start = prompt.find(B_SYS)
38
+ sys_end = prompt.rfind(E_SYS)
39
+ if sys_start != -1 and sys_end != -1:
40
+ system_msg = prompt[sys_start + len(B_SYS): sys_end]
41
+ messages.append({"role": "system", "content": system_msg})
42
+ prompt = prompt[sys_end + len(E_SYS):]
43
+
44
+ user_ai_msgs = split_into_messages(prompt)
45
+
46
+ user_turn = True
47
+ for message in user_ai_msgs:
48
+ if user_turn:
49
+ messages.append({"role": "user", "content": message})
50
+ else:
51
+ messages.append({"role": "assistant", "content": message})
52
+
53
+ if user_turn:
54
+ user_turn = False
55
+ else:
56
+ user_turn = True
57
+
58
+ return messages
src/train_test_utils.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from tqdm.auto import tqdm
3
+ import time
4
+ import numpy as np
5
+ from src.losses import calc_prob_uncertinty
6
+ tic, toc = (time.time, time.time)
7
+
8
+
9
+ def train(probe, device, train_loader, optimizer, epoch, loss_func,
10
+ class_names=None, report=False, verbose_interval=5, layer_num=40,
11
+ head=None, verbose=True, return_raw_outputs=False, one_hot=False, uncertainty=False, **kwargs,):
12
+ """
13
+ :param model: pytorch model (class:torch.nn.Module)
14
+ :param device: device used to train the model (e.g. torch.device("cuda") for training on GPU)
15
+ :param train_loader: torch.utils.data.DataLoader of train dataset
16
+ :param optimizer: optimizer for the model
17
+ :param epoch: current epoch of training
18
+ :param loss_func: loss function for the training
19
+ :param class_names: str Name for the classification classses. used in train report
20
+ :param report: whether to print a classification report of training
21
+ :param train_verbose: print a train progress report after how many batches of training in each epoch
22
+ :return: average loss, train accuracy, true labels, predictions
23
+ """
24
+ assert (verbose_interval is None) or verbose_interval > 0, "invalid verbose_interval, verbose_interval(int) > 0"
25
+ starttime = tic()
26
+ # Set the model to the train mode: Essential for proper gradient descent
27
+ probe.train()
28
+ loss_sum = 0
29
+ correct = 0
30
+ tot = 0
31
+
32
+ preds = []
33
+ truths = []
34
+
35
+ # Iterate through the train dataset
36
+ for batch_idx, batch in enumerate(train_loader):
37
+ batch_size = 1
38
+ target = batch["age"].long().cuda()
39
+ if one_hot:
40
+ target = torch.nn.functional.one_hot(target, **kwargs).float()
41
+ optimizer.zero_grad()
42
+
43
+ if layer_num or layer_num == 0:
44
+ act = batch["hidden_states"][:, layer_num,].to("cuda")
45
+ else:
46
+ act = batch["hidden_states"].to("cuda")
47
+ output = probe(act)
48
+ if not one_hot:
49
+ loss = loss_func(output[0], target, **kwargs)
50
+ else:
51
+ loss = loss_func(output[0], target)
52
+ loss.backward()
53
+ optimizer.step()
54
+
55
+ loss_sum += loss.sum().item()
56
+ if uncertainty:
57
+ pred, uncertainty = calc_prob_uncertinty(output[0].detach().cpu().numpy())
58
+ pred = torch.argmax(output[0], axis=1)
59
+
60
+ # In the Scikit-Learn's implementation of OvR Multi-class Logistic Regression. They linearly normalized the predicted probability and then call argmax
61
+ # Below is an equivalent implementation of the scikit-learn's decision function. The only difference is we didn't do the linearly normalization
62
+ # To save some computation time
63
+ if len(target.shape) > 1:
64
+ target = torch.argmax(target, axis=1)
65
+ correct += np.sum(np.array(pred.detach().cpu().numpy()) == np.array(target.detach().cpu().numpy()))
66
+ if return_raw_outputs:
67
+ preds.append(pred.detach().cpu().numpy())
68
+ truths.append(target.detach().cpu().numpy())
69
+ tot += pred.shape[0]
70
+
71
+ train_acc = correct / tot
72
+ loss_avg = loss_sum / len(train_loader)
73
+
74
+ endtime = toc()
75
+ if verbose:
76
+ print('\nTrain set: Average loss: {:.4f} ({:.3f} sec) Accuracy: {:.3f}\n'.\
77
+ format(loss_avg,
78
+ endtime-starttime,
79
+ train_acc))
80
+
81
+ preds = np.concatenate(preds)
82
+ truths = np.concatenate(truths)
83
+
84
+ if return_raw_outputs:
85
+ return loss_avg, train_acc, preds, truths
86
+ else:
87
+ return loss_avg, train_acc
88
+
89
+
90
+ def test(probe, device, test_loader, loss_func, return_raw_outputs=False, verbose=True,
91
+ layer_num=40, scheduler=None, one_hot=False, uncertainty=False, **kwargs):
92
+ """
93
+ :param model: pytorch model (class:torch.nn.Module)
94
+ :param device: device used to train the model (e.g. torch.device("cuda") for training on GPU)
95
+ :param test_loader: torch.utils.data.DataLoader of test dataset
96
+ :param loss_func: loss function for the training
97
+ :param class_names: str Name for the classification classses. used in train report
98
+ :param test_report: whether to print a classification report of testing after each epoch
99
+ :param return_raw_outputs: whether return the raw outputs of model (before argmax). used for auc computation
100
+ :return: average test loss, test accuracy, true labels, predictions, (and raw outputs \
101
+ from model if return_raw_outputs)
102
+ """
103
+ # Set the model to evaluation mode: Essential for testing model
104
+ probe.eval()
105
+ test_loss = 0
106
+ tot = 0
107
+ correct = 0
108
+ preds = []
109
+ truths = []
110
+
111
+ # Do not call gradient descent on the test set
112
+ # We don't adjust the weights of model on the test set
113
+ with torch.no_grad():
114
+ for batch_idx, batch in enumerate(test_loader):
115
+ batch_size = 1
116
+ target = batch["age"].long().cuda()
117
+ if one_hot:
118
+ target = torch.nn.functional.one_hot(target, **kwargs).float()
119
+ if layer_num or layer_num == 0:
120
+ act = batch["hidden_states"][:, layer_num,].to("cuda")
121
+ else:
122
+ act = batch["hidden_states"].to("cuda")
123
+ output = probe(act)
124
+ if uncertainty:
125
+ pred, uncertainty = calc_prob_uncertinty(output[0].detach().cpu().numpy())
126
+ pred = torch.argmax(output[0], axis=1)
127
+
128
+ if not one_hot:
129
+ loss = loss_func(output[0], target, **kwargs)
130
+ else:
131
+ loss = loss_func(output[0], target)
132
+ test_loss += loss.sum().item() # sum up batch loss
133
+
134
+ # In the Scikit-Learn's implementation of OvR Multi-class Logistic Regression. They linearly normalized the predicted probability and then call argmax
135
+ # Below is an equivalent implementation of the scikit-learn's decision function. The only difference is we didn't do the linearly normalization
136
+ # To save some computation time
137
+ if len(target.shape) > 1:
138
+ target = torch.argmax(target, axis=1)
139
+
140
+
141
+ pred = np.array(pred.detach().cpu().numpy())
142
+ target = np.array(target.detach().cpu().numpy())
143
+ correct += np.sum(pred == target)
144
+ tot += pred.shape[0]
145
+ if return_raw_outputs:
146
+ preds.append(pred)
147
+ truths.append(target)
148
+
149
+ test_loss /= len(test_loader)
150
+ if scheduler:
151
+ scheduler.step(test_loss)
152
+
153
+ test_acc = correct / tot
154
+
155
+ if verbose:
156
+ print('Test set: Average loss: {:.4f}, Accuracy: {:.3f}\n'.format(
157
+ test_loss,
158
+ test_acc))
159
+
160
+ preds = np.concatenate(preds)
161
+ truths = np.concatenate(truths)
162
+
163
+ # If return the raw outputs (before argmax) from the model
164
+ if return_raw_outputs:
165
+ return test_loss, test_acc, preds, truths
166
+ else:
167
+ return test_loss, test_acc
168
+
169
+ import torch
170
+ from tqdm.auto import tqdm
171
+ import time
172
+ import numpy as np
173
+ from .losses import calc_prob_uncertinty
174
+ tic, toc = (time.time, time.time)
train_probes.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Train reading and controlling probes for LLM attribute detection.
4
+ This script trains linear probes on different layers of a language model to detect
5
+ demographic attributes (age, gender, socioeconomic status, education level).
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ import argparse
11
+ import pickle
12
+ import time
13
+ from pathlib import Path
14
+ from typing import Dict, List, Tuple, Optional
15
+
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.nn.functional as F
19
+ from torch.utils.data import DataLoader, Subset
20
+ from transformers import AutoTokenizer, AutoModelForCausalLM
21
+ from tqdm.auto import tqdm
22
+ import sklearn.model_selection
23
+ from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix
24
+ import matplotlib.pyplot as plt
25
+
26
+ # Import custom modules
27
+ try:
28
+ from src.dataset import TextDataset
29
+ from src.probes import LinearProbeClassification
30
+ from src.train_test_utils import train, test
31
+ from src.losses import edl_mse_loss
32
+ except ImportError as e:
33
+ print(f"❌ ERROR: Failed to import required modules: {e}")
34
+ print("Please ensure all required modules are in the correct location.")
35
+ sys.exit(1)
36
+
37
+
38
+ class TrainerConfig:
39
+ """Configuration for training probes."""
40
+ learning_rate = 1e-3
41
+ betas = (0.9, 0.95)
42
+ weight_decay = 0.1 # only applied on matmul weights
43
+
44
+ def __init__(self, **kwargs):
45
+ for k, v in kwargs.items():
46
+ setattr(self, k, v)
47
+
48
+
49
+ class ProbeTrainer:
50
+ """Main class for training reading and controlling probes."""
51
+
52
+ def __init__(self, model_name: str = "meta-llama/Llama-2-13b-chat-hf",
53
+ device: str = "cuda", use_auth_token: bool = True):
54
+ """
55
+ Initialize the probe trainer.
56
+
57
+ Args:
58
+ model_name: HuggingFace model name
59
+ device: Device to use for training
60
+ use_auth_token: Whether to use auth token for model download
61
+ """
62
+ self.device = device
63
+ self.model_name = model_name
64
+
65
+ # Configuration flags
66
+ self.new_prompt_format = True
67
+ self.residual_stream = True
68
+ self.uncertainty = False
69
+ self.logistic = True
70
+ self.augmented = False
71
+ self.remove_last_ai_response = True
72
+ self.include_inst = True
73
+ self.one_hot = True
74
+
75
+ # Label mappings
76
+ self.label_mappings = {
77
+ "_age_": {
78
+ "child": 0,
79
+ "adolescent": 1,
80
+ "adult": 2,
81
+ "older adult": 3,
82
+ },
83
+ "_gender_": {
84
+ "male": 0,
85
+ "female": 1,
86
+ },
87
+ "_socioeco_": {
88
+ "low": 0,
89
+ "middle": 1,
90
+ "high": 2
91
+ },
92
+ "_education_": {
93
+ "someschool": 0,
94
+ "highschool": 1,
95
+ "collegemore": 2
96
+ }
97
+ }
98
+
99
+ self.prompt_translator = {
100
+ "_age_": "age",
101
+ "_gender_": "gender",
102
+ "_socioeco_": "socioeconomic status",
103
+ "_education_": "education level",
104
+ }
105
+
106
+ self.openai_dataset = {
107
+ "_age_": "data/dataset/openai_age_1/",
108
+ "_gender_": "data/dataset/openai_gender_1/",
109
+ "_education_": "data/dataset/openai_education_1/",
110
+ "_socioeco_": "data/dataset/openai_socioeconomic_1/",
111
+ }
112
+
113
+ # Dataset configurations
114
+ self.dataset_configs = [
115
+ ("data/dataset/llama_age_1/", "_age_"),
116
+ ("data/dataset/llama_gender_1/", "_gender_"),
117
+ ("data/dataset/llama_socioeconomic_1/", "_socioeco_"),
118
+ ("data/dataset/openai_education_1/", "_education_"),
119
+ ]
120
+
121
+ # Initialize model and tokenizer
122
+ print(f"πŸš€ Initializing ProbeTrainer with model: {model_name}")
123
+ self._initialize_model()
124
+
125
+ def _initialize_model(self):
126
+ """Initialize the tokenizer and model."""
127
+ try:
128
+ print("πŸ“₯ Loading tokenizer...")
129
+ self.tokenizer = AutoTokenizer.from_pretrained(
130
+ self.model_name,
131
+ use_auth_token=True
132
+ )
133
+ print("βœ… Tokenizer loaded successfully")
134
+
135
+ print("πŸ“₯ Loading model...")
136
+ self.model = AutoModelForCausalLM.from_pretrained(
137
+ self.model_name,
138
+ use_auth_token=True
139
+ )
140
+
141
+ if self.device == "cuda":
142
+ print("πŸ”§ Moving model to GPU and setting to half precision...")
143
+ self.model.half().cuda()
144
+
145
+ self.model.eval()
146
+ print("βœ… Model loaded and ready")
147
+
148
+ except Exception as e:
149
+ print(f"❌ ERROR: Failed to initialize model: {e}")
150
+ sys.exit(1)
151
+
152
+ def _get_additional_datasets(self, label_idf: str, directory: str) -> List[str]:
153
+ """Get additional datasets for training."""
154
+ additional_dataset = []
155
+
156
+ if label_idf == "_education_":
157
+ additional_dataset = []
158
+ else:
159
+ # Replace _1/ with _2/ for the second dataset
160
+ additional_dataset = [
161
+ directory.replace("_1/", "_2/"),
162
+ self.openai_dataset[label_idf]
163
+ ]
164
+
165
+ # Add extra datasets based on attribute type
166
+ if label_idf == "_gender_":
167
+ additional_dataset += [
168
+ "data/dataset/openai_gender_2/",
169
+ "data/dataset/openai_gender_3/",
170
+ "data/dataset/openai_gender_4",
171
+ ]
172
+ elif label_idf == "_education_":
173
+ additional_dataset += [
174
+ "data/dataset/openai_education_three_classes_2/",
175
+ "data/dataset/openai_education_three_classes_3/"
176
+ ]
177
+ elif label_idf == "_socioeco_":
178
+ additional_dataset += [
179
+ "data/dataset/openai_socioeconomic_2/"
180
+ ]
181
+ elif label_idf == "_age_":
182
+ additional_dataset += [
183
+ "data/dataset/openai_age_2/"
184
+ ]
185
+
186
+ return additional_dataset
187
+
188
+ def _create_dataset(self, directory: str, label_idf: str,
189
+ label_to_id: Dict, control_probe: bool = False) -> TextDataset:
190
+ """Create a dataset for training."""
191
+ additional_datasets = self._get_additional_datasets(label_idf, directory)
192
+
193
+ print(f" πŸ“‚ Creating dataset from {directory}")
194
+ print(f" πŸ“Ž Additional datasets: {len(additional_datasets)} sources")
195
+
196
+ try:
197
+ dataset = TextDataset(
198
+ directory,
199
+ self.tokenizer,
200
+ self.model,
201
+ label_idf=label_idf,
202
+ label_to_id=label_to_id,
203
+ convert_to_llama2_format=True,
204
+ additional_datas=additional_datasets,
205
+ new_format=self.new_prompt_format,
206
+ control_probe=control_probe,
207
+ residual_stream=self.residual_stream,
208
+ if_augmented=self.augmented,
209
+ remove_last_ai_response=self.remove_last_ai_response,
210
+ include_inst=self.include_inst,
211
+ k=1,
212
+ one_hot=False,
213
+ last_tok_pos=-1
214
+ )
215
+ print(f" βœ… Dataset created with {len(dataset)} samples")
216
+ return dataset
217
+ except Exception as e:
218
+ print(f" ❌ ERROR: Failed to create dataset: {e}")
219
+ raise
220
+
221
+ def _create_data_loaders(self, dataset: TextDataset) -> Tuple[DataLoader, DataLoader]:
222
+ """Create train and test data loaders."""
223
+ train_size = int(0.8 * len(dataset))
224
+ test_size = len(dataset) - train_size
225
+
226
+ print(f" πŸ“Š Splitting dataset: {train_size} train, {test_size} test")
227
+
228
+ try:
229
+ train_idx, val_idx = sklearn.model_selection.train_test_split(
230
+ list(range(len(dataset))),
231
+ test_size=test_size,
232
+ train_size=train_size,
233
+ random_state=12345,
234
+ shuffle=True,
235
+ stratify=dataset.labels,
236
+ )
237
+
238
+ train_dataset = Subset(dataset, train_idx)
239
+ test_dataset = Subset(dataset, val_idx)
240
+
241
+ train_loader = DataLoader(
242
+ train_dataset,
243
+ shuffle=True,
244
+ pin_memory=True,
245
+ batch_size=200,
246
+ num_workers=1
247
+ )
248
+
249
+ test_loader = DataLoader(
250
+ test_dataset,
251
+ shuffle=False,
252
+ pin_memory=True,
253
+ batch_size=400,
254
+ num_workers=1
255
+ )
256
+
257
+ print(f" βœ… Data loaders created")
258
+ return train_loader, test_loader
259
+
260
+ except Exception as e:
261
+ print(f" ❌ ERROR: Failed to create data loaders: {e}")
262
+ raise
263
+
264
+ def _train_probe_for_layer(self, train_loader: DataLoader, test_loader: DataLoader,
265
+ layer_num: int, num_classes: int, dict_name: str,
266
+ save_dir: str, max_epochs: int = 50) -> Tuple[float, float, float]:
267
+ """Train a probe for a specific layer."""
268
+ trainer_config = TrainerConfig()
269
+
270
+ probe = LinearProbeClassification(
271
+ probe_class=num_classes,
272
+ device=self.device,
273
+ input_dim=5120,
274
+ logistic=self.logistic
275
+ )
276
+
277
+ optimizer, scheduler = probe.configure_optimizers(trainer_config)
278
+
279
+ if self.uncertainty:
280
+ loss_func = edl_mse_loss
281
+ else:
282
+ loss_func = nn.BCELoss()
283
+
284
+ best_acc = 0
285
+ final_test_acc = 0
286
+ final_train_acc = 0
287
+
288
+ for epoch in range(1, max_epochs + 1):
289
+ verbosity = (epoch == max_epochs)
290
+
291
+ # Training
292
+ if self.uncertainty:
293
+ train_results = train(
294
+ probe, self.device, train_loader, optimizer,
295
+ epoch, loss_func=loss_func, verbose_interval=None,
296
+ verbose=verbosity, layer_num=layer_num,
297
+ return_raw_outputs=True, epoch_num=epoch,
298
+ num_classes=num_classes
299
+ )
300
+ test_results = test(
301
+ probe, self.device, test_loader, loss_func=loss_func,
302
+ return_raw_outputs=True, verbose=verbosity,
303
+ layer_num=layer_num, scheduler=scheduler,
304
+ epoch_num=epoch, num_classes=num_classes
305
+ )
306
+ else:
307
+ train_results = train(
308
+ probe, self.device, train_loader, optimizer,
309
+ epoch, loss_func=loss_func, verbose_interval=None,
310
+ verbose=verbosity, layer_num=layer_num,
311
+ return_raw_outputs=True, one_hot=self.one_hot,
312
+ num_classes=num_classes
313
+ )
314
+ test_results = test(
315
+ probe, self.device, test_loader, loss_func=loss_func,
316
+ return_raw_outputs=True, verbose=verbosity,
317
+ layer_num=layer_num, scheduler=scheduler,
318
+ one_hot=self.one_hot, num_classes=num_classes
319
+ )
320
+
321
+ if test_results[1] > best_acc:
322
+ best_acc = test_results[1]
323
+ save_path = f"{save_dir}/{dict_name}_probe_at_layer_{layer_num}.pth"
324
+ torch.save(probe.state_dict(), save_path)
325
+
326
+ if epoch == max_epochs:
327
+ final_test_acc = test_results[1]
328
+ final_train_acc = train_results[1]
329
+
330
+ # Save final model
331
+ final_path = f"{save_dir}/{dict_name}_probe_at_layer_{layer_num}_final.pth"
332
+ torch.save(probe.state_dict(), final_path)
333
+
334
+ # Generate confusion matrix
335
+ if verbosity:
336
+ try:
337
+ cm = confusion_matrix(test_results[3], test_results[2])
338
+ cm_display = ConfusionMatrixDisplay(
339
+ cm,
340
+ display_labels=list(self.label_mappings[f"_{dict_name}_"].keys())
341
+ ).plot()
342
+ plt.savefig(f"{save_dir}/{dict_name}_layer_{layer_num}_confusion.png")
343
+ plt.close()
344
+ except Exception as e:
345
+ print(f" ⚠️ Warning: Could not generate confusion matrix: {e}")
346
+
347
+ return best_acc, final_test_acc, final_train_acc
348
+
349
+ def train_probes(self, probe_type: str = "reading", num_layers: int = 41):
350
+ """
351
+ Train probes for all attributes and layers.
352
+
353
+ Args:
354
+ probe_type: Type of probe to train ("reading" or "controlling")
355
+ num_layers: Number of layers to train probes for
356
+ """
357
+ print(f"\n{'='*80}")
358
+ print(f"🎯 Training {probe_type.upper()} PROBES")
359
+ print(f"{'='*80}\n")
360
+
361
+ # Create output directory
362
+ save_dir = f"probe_checkpoints/{probe_type}_probe"
363
+ Path(save_dir).mkdir(parents=True, exist_ok=True)
364
+ print(f"πŸ“ Output directory: {save_dir}")
365
+
366
+ accuracy_dict = {}
367
+ control_probe = (probe_type == "controlling")
368
+
369
+ for directory, label_idf in self.dataset_configs:
370
+ dict_name = label_idf.strip("_")
371
+ label_to_id = self.label_mappings[label_idf]
372
+
373
+ print(f"\n{'-'*60}")
374
+ print(f"🏷️ Processing: {self.prompt_translator[label_idf].upper()}")
375
+ print(f" Classes: {list(label_to_id.keys())}")
376
+ print(f"{'-'*60}")
377
+
378
+ try:
379
+ # Create dataset
380
+ dataset = self._create_dataset(
381
+ directory, label_idf, label_to_id, control_probe
382
+ )
383
+
384
+ # Create data loaders
385
+ train_loader, test_loader = self._create_data_loaders(dataset)
386
+
387
+ # Initialize accuracy tracking
388
+ accuracy_dict[dict_name] = []
389
+ accuracy_dict[dict_name + "_final"] = []
390
+ accuracy_dict[dict_name + "_train"] = []
391
+
392
+ accs = []
393
+ final_accs = []
394
+ train_accs = []
395
+
396
+ # Train probes for each layer
397
+ print(f"\n πŸ”„ Training probes for {num_layers} layers...")
398
+ for layer_num in tqdm(range(num_layers), desc=f" Layers for {dict_name}"):
399
+ try:
400
+ print(f"\n Layer {layer_num}:")
401
+ best_acc, final_test_acc, final_train_acc = self._train_probe_for_layer(
402
+ train_loader, test_loader, layer_num,
403
+ len(label_to_id), dict_name, save_dir
404
+ )
405
+
406
+ accs.append(best_acc)
407
+ final_accs.append(final_test_acc)
408
+ train_accs.append(final_train_acc)
409
+
410
+ print(f" πŸ“ˆ Best: {best_acc:.3f}, Final: {final_test_acc:.3f}, Train: {final_train_acc:.3f}")
411
+
412
+ except Exception as e:
413
+ print(f" ❌ ERROR: Failed to train layer {layer_num}: {e}")
414
+ accs.append(0)
415
+ final_accs.append(0)
416
+ train_accs.append(0)
417
+
418
+ # Save accuracies
419
+ accuracy_dict[dict_name] = accs
420
+ accuracy_dict[dict_name + "_final"] = final_accs
421
+ accuracy_dict[dict_name + "_train"] = train_accs
422
+
423
+ # Save intermediate results
424
+ with open(f"{save_dir}_experiment.pkl", "wb") as outfile:
425
+ pickle.dump(accuracy_dict, outfile)
426
+ print(f" πŸ’Ύ Saved results to {save_dir}_experiment.pkl")
427
+
428
+ # Clean up memory
429
+ del dataset, train_loader, test_loader
430
+ torch.cuda.empty_cache()
431
+ print(f" 🧹 Cleaned up memory")
432
+
433
+ except Exception as e:
434
+ print(f" ❌ ERROR: Failed to process {dict_name}: {e}")
435
+ continue
436
+
437
+ print(f"\n{'='*80}")
438
+ print(f"βœ… COMPLETED {probe_type.upper()} PROBE TRAINING")
439
+ print(f"{'='*80}\n")
440
+
441
+ # Print summary
442
+ self._print_summary(accuracy_dict, probe_type)
443
+
444
+ return accuracy_dict
445
+
446
+ def _print_summary(self, accuracy_dict: Dict, probe_type: str):
447
+ """Print a summary of training results."""
448
+ print(f"\nπŸ“Š SUMMARY for {probe_type} probes:")
449
+ print("-" * 40)
450
+
451
+ for attribute in accuracy_dict:
452
+ if not attribute.endswith("_final") and not attribute.endswith("_train"):
453
+ best_accs = accuracy_dict[attribute]
454
+ if best_accs:
455
+ max_acc = max(best_accs)
456
+ best_layer = best_accs.index(max_acc)
457
+ avg_acc = sum(best_accs) / len(best_accs)
458
+ print(f" {attribute:12s}: Best={max_acc:.3f} (layer {best_layer}), Avg={avg_acc:.3f}")
459
+
460
+
461
+ def main():
462
+ """Main entry point for the script."""
463
+ parser = argparse.ArgumentParser(description="Train reading and controlling probes for LLM attribute detection")
464
+ parser.add_argument("--probe-type", choices=["reading", "controlling", "both"], default="both",
465
+ help="Type of probes to train")
466
+ parser.add_argument("--model", default="meta-llama/Llama-2-13b-chat-hf",
467
+ help="HuggingFace model to use")
468
+ parser.add_argument("--device", default="cuda", choices=["cuda", "cpu"],
469
+ help="Device to use for training")
470
+ parser.add_argument("--num-layers", type=int, default=41,
471
+ help="Number of layers to train probes for")
472
+ parser.add_argument("--no-auth", action="store_true",
473
+ help="Don't use authentication token")
474
+
475
+ args = parser.parse_args()
476
+
477
+ print(f"""
478
+ ╔══════════════════════════════════════════════════════════════╗
479
+ β•‘ LLM Probe Training System β•‘
480
+ β•‘ β•‘
481
+ β•‘ Model: {args.model:50s} β•‘
482
+ β•‘ Device: {args.device:49s} β•‘
483
+ β•‘ Probe Type: {args.probe_type:45s} β•‘
484
+ β•‘ Layers: {args.num_layers:49d} β•‘
485
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
486
+ """)
487
+
488
+ start_time = time.time()
489
+
490
+ try:
491
+ # Initialize trainer
492
+ trainer = ProbeTrainer(
493
+ model_name=args.model,
494
+ device=args.device,
495
+ use_auth_token=not args.no_auth
496
+ )
497
+
498
+ # Train probes
499
+ if args.probe_type == "both":
500
+ print("\nπŸš€ Training both reading and controlling probes...")
501
+ reading_results = trainer.train_probes("reading", args.num_layers)
502
+ controlling_results = trainer.train_probes("controlling", args.num_layers)
503
+ elif args.probe_type == "reading":
504
+ reading_results = trainer.train_probes("reading", args.num_layers)
505
+ else:
506
+ controlling_results = trainer.train_probes("controlling", args.num_layers)
507
+
508
+ elapsed_time = time.time() - start_time
509
+ print(f"\n⏱️ Total training time: {elapsed_time/60:.2f} minutes")
510
+ print("βœ… Training completed successfully!")
511
+
512
+ except KeyboardInterrupt:
513
+ print("\n\n⚠️ Training interrupted by user")
514
+ sys.exit(1)
515
+ except Exception as e:
516
+ print(f"\n❌ FATAL ERROR: {e}")
517
+ import traceback
518
+ traceback.print_exc()
519
+ sys.exit(1)
520
+
521
+
522
+ if __name__ == "__main__":
523
+ main()
train_probes_minimal.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Minimal probe training script for HuggingFace Spaces.
4
+ Uses a smaller model (GPT-2) for demonstration on limited resources.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import json
10
+ import pickle
11
+ import time
12
+ import logging
13
+ from pathlib import Path
14
+ from typing import Dict, List, Tuple, Optional
15
+ import numpy as np
16
+ from datetime import datetime
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+ from torch.utils.data import Dataset, DataLoader, TensorDataset
22
+ from transformers import AutoTokenizer, AutoModelForCausalLM, GPT2Model, GPT2Tokenizer
23
+ from tqdm.auto import tqdm
24
+ from sklearn.model_selection import train_test_split
25
+ from sklearn.metrics import accuracy_score, confusion_matrix
26
+ import matplotlib.pyplot as plt
27
+ import seaborn as sns
28
+
29
+ # Simple probe architecture
30
+ class SimpleProbe(nn.Module):
31
+ def __init__(self, input_dim, num_classes):
32
+ super().__init__()
33
+ self.fc = nn.Linear(input_dim, num_classes)
34
+
35
+ def forward(self, x):
36
+ return self.fc(x)
37
+
38
+ def setup_logging(experiment_name: str = "probe_training") -> logging.Logger:
39
+ """Setup logging configuration."""
40
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
41
+
42
+ # Create logs directory
43
+ log_dir = Path(f"experiments/{experiment_name}/logs")
44
+ log_dir.mkdir(parents=True, exist_ok=True)
45
+
46
+ # Configure logging
47
+ log_file = log_dir / f"training_log_{timestamp}.txt"
48
+
49
+ # Create logger
50
+ logger = logging.getLogger('probe_training')
51
+ logger.setLevel(logging.DEBUG)
52
+
53
+ # File handler - detailed logs
54
+ file_handler = logging.FileHandler(log_file)
55
+ file_handler.setLevel(logging.DEBUG)
56
+ file_formatter = logging.Formatter(
57
+ '%(asctime)s - %(levelname)s - %(message)s',
58
+ datefmt='%Y-%m-%d %H:%M:%S'
59
+ )
60
+ file_handler.setFormatter(file_formatter)
61
+
62
+ # Console handler - simplified logs
63
+ console_handler = logging.StreamHandler()
64
+ console_handler.setLevel(logging.INFO)
65
+ console_formatter = logging.Formatter('%(message)s')
66
+ console_handler.setFormatter(console_formatter)
67
+
68
+ # Add handlers
69
+ logger.addHandler(file_handler)
70
+ logger.addHandler(console_handler)
71
+
72
+ return logger
73
+
74
+ class MinimalProbeTrainer:
75
+ """Minimal probe trainer using GPT-2 for demonstration."""
76
+
77
+ def __init__(self, model_name="gpt2", device="cpu", logger=None):
78
+ self.device = device
79
+ self.model_name = model_name
80
+ self.logger = logger or logging.getLogger('probe_training')
81
+
82
+ self.logger.info(f"πŸš€ Initializing with {model_name} on {device}")
83
+ print(f"πŸš€ Initializing with {model_name} on {device}")
84
+
85
+ # Load smaller model for demonstration
86
+ self.tokenizer = GPT2Tokenizer.from_pretrained(model_name)
87
+ self.model = GPT2Model.from_pretrained(model_name)
88
+ self.model.to(device)
89
+ self.model.eval()
90
+
91
+ # GPT-2 hidden size
92
+ self.hidden_size = 768 # GPT-2 base
93
+ self.num_layers = len(self.model.h) # 12 layers for GPT-2 base
94
+
95
+ self.logger.info(f"βœ… Model loaded: {self.num_layers} layers, hidden size {self.hidden_size}")
96
+ self.logger.debug(f"Model parameters: {sum(p.numel() for p in self.model.parameters()):,}")
97
+ print(f"βœ… Model loaded: {self.num_layers} layers, hidden size {self.hidden_size}")
98
+
99
+ def generate_synthetic_data(self, num_samples=1000, num_classes=4):
100
+ """Generate synthetic data for demonstration."""
101
+ print(f"πŸ“Š Generating {num_samples} synthetic samples...")
102
+
103
+ # Generate random hidden states
104
+ X = torch.randn(num_samples, self.hidden_size)
105
+
106
+ # Create synthetic labels with some pattern
107
+ # Make the data somewhat learnable by adding class-specific signals
108
+ y = torch.randint(0, num_classes, (num_samples,))
109
+
110
+ for i in range(num_classes):
111
+ mask = y == i
112
+ # Add class-specific signal to features
113
+ X[mask] += torch.randn(1, self.hidden_size) * 0.5
114
+
115
+ return X, y
116
+
117
+ def evaluate_probe(self, probe, data_loader, device):
118
+ """Evaluate probe accuracy without training."""
119
+ probe.eval()
120
+ correct = 0
121
+ total = 0
122
+ all_preds = []
123
+ all_labels = []
124
+
125
+ with torch.no_grad():
126
+ for batch_x, batch_y in data_loader:
127
+ batch_x, batch_y = batch_x.to(device), batch_y.to(device)
128
+ outputs = probe(batch_x)
129
+ _, predicted = outputs.max(1)
130
+ total += batch_y.size(0)
131
+ correct += predicted.eq(batch_y).sum().item()
132
+ all_preds.extend(predicted.cpu().numpy())
133
+ all_labels.extend(batch_y.cpu().numpy())
134
+
135
+ accuracy = 100. * correct / total
136
+ return accuracy, all_preds, all_labels
137
+
138
+ def train_probe_for_layer(self, X_train, y_train, X_test, y_test,
139
+ num_classes, layer_idx, epochs=20):
140
+ """Train a probe for a specific layer."""
141
+ probe = SimpleProbe(self.hidden_size, num_classes).to(self.device)
142
+ optimizer = torch.optim.Adam(probe.parameters(), lr=0.001)
143
+ criterion = nn.CrossEntropyLoss()
144
+
145
+ # Create data loaders
146
+ train_dataset = TensorDataset(X_train, y_train)
147
+ test_dataset = TensorDataset(X_test, y_test)
148
+ train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
149
+ test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)
150
+
151
+ # Measure initial performance BEFORE any training
152
+ initial_train_acc, _, _ = self.evaluate_probe(probe, train_loader, self.device)
153
+ initial_test_acc, _, _ = self.evaluate_probe(probe, test_loader, self.device)
154
+
155
+ if hasattr(self, 'logger'):
156
+ self.logger.info(f" Layer {layer_idx} - Initial (untrained): Train Acc: {initial_train_acc:.2f}%, Test Acc: {initial_test_acc:.2f}%")
157
+ print(f" Layer {layer_idx} - Initial (untrained): Train Acc: {initial_train_acc:.2f}%, Test Acc: {initial_test_acc:.2f}%")
158
+
159
+ train_accs = [initial_train_acc] # Start with initial accuracy
160
+ test_accs = [initial_test_acc]
161
+
162
+ for epoch in range(epochs):
163
+ # Training
164
+ probe.train()
165
+ train_loss = 0
166
+ train_correct = 0
167
+ train_total = 0
168
+
169
+ for batch_x, batch_y in train_loader:
170
+ batch_x, batch_y = batch_x.to(self.device), batch_y.to(self.device)
171
+
172
+ optimizer.zero_grad()
173
+ outputs = probe(batch_x)
174
+ loss = criterion(outputs, batch_y)
175
+ loss.backward()
176
+ optimizer.step()
177
+
178
+ train_loss += loss.item()
179
+ _, predicted = outputs.max(1)
180
+ train_total += batch_y.size(0)
181
+ train_correct += predicted.eq(batch_y).sum().item()
182
+
183
+ # Testing
184
+ probe.eval()
185
+ test_correct = 0
186
+ test_total = 0
187
+ all_preds = []
188
+ all_labels = []
189
+
190
+ with torch.no_grad():
191
+ for batch_x, batch_y in test_loader:
192
+ batch_x, batch_y = batch_x.to(self.device), batch_y.to(self.device)
193
+ outputs = probe(batch_x)
194
+ _, predicted = outputs.max(1)
195
+ test_total += batch_y.size(0)
196
+ test_correct += predicted.eq(batch_y).sum().item()
197
+
198
+ all_preds.extend(predicted.cpu().numpy())
199
+ all_labels.extend(batch_y.cpu().numpy())
200
+
201
+ train_acc = 100. * train_correct / train_total
202
+ test_acc = 100. * test_correct / test_total
203
+ train_accs.append(train_acc)
204
+ test_accs.append(test_acc)
205
+
206
+ if epoch == epochs - 1:
207
+ improvement = test_acc - initial_test_acc
208
+ print(f" Layer {layer_idx} - Final: Train Acc: {train_acc:.2f}%, Test Acc: {test_acc:.2f}% (Improved +{improvement:.2f}% from initial)")
209
+
210
+ return probe, train_accs, test_accs, all_preds, all_labels
211
+
212
+ def train_probes(self, attribute="age", num_layers_to_train=5):
213
+ """Train probes across multiple layers."""
214
+ print(f"\n{'='*60}")
215
+ print(f"🎯 Training probes for {attribute}")
216
+ print(f"{'='*60}\n")
217
+
218
+ # Attribute configurations
219
+ attribute_configs = {
220
+ "age": {"classes": ["child", "adolescent", "adult", "older_adult"], "num": 4},
221
+ "gender": {"classes": ["male", "female"], "num": 2},
222
+ "socioeco": {"classes": ["low", "middle", "high"], "num": 3},
223
+ "education": {"classes": ["some_school", "high_school", "college"], "num": 3}
224
+ }
225
+
226
+ config = attribute_configs.get(attribute, attribute_configs["age"])
227
+ num_classes = config["num"]
228
+ class_names = config["classes"]
229
+
230
+ # Generate synthetic data
231
+ X, y = self.generate_synthetic_data(num_samples=2000, num_classes=num_classes)
232
+
233
+ # Split data
234
+ X_train, X_test, y_train, y_test = train_test_split(
235
+ X, y, test_size=0.2, random_state=42, stratify=y
236
+ )
237
+
238
+ print(f"πŸ“Š Data split: {len(X_train)} train, {len(X_test)} test")
239
+ print(f"πŸ“Š Classes: {class_names}")
240
+
241
+ # Train probes for each layer
242
+ results = {
243
+ "attribute": attribute,
244
+ "num_classes": num_classes,
245
+ "class_names": class_names,
246
+ "layers": [],
247
+ "train_accuracies": [],
248
+ "test_accuracies": [],
249
+ "best_layer": -1,
250
+ "best_accuracy": 0
251
+ }
252
+
253
+ num_layers = min(num_layers_to_train, self.num_layers)
254
+ print(f"\nπŸ”„ Training probes for {num_layers} layers...")
255
+
256
+ for layer_idx in tqdm(range(num_layers), desc="Layers"):
257
+ # Add some variation to data for different layers
258
+ # Simulate that middle layers are better
259
+ layer_factor = 1.0 - abs(layer_idx - num_layers//2) / (num_layers/2)
260
+ X_train_layer = X_train + torch.randn_like(X_train) * (0.3 / (layer_factor + 0.1))
261
+ X_test_layer = X_test + torch.randn_like(X_test) * (0.3 / (layer_factor + 0.1))
262
+
263
+ probe, train_accs, test_accs, preds, labels = self.train_probe_for_layer(
264
+ X_train_layer, y_train, X_test_layer, y_test,
265
+ num_classes, layer_idx, epochs=10
266
+ )
267
+
268
+ final_test_acc = test_accs[-1]
269
+ results["layers"].append(layer_idx)
270
+ results["train_accuracies"].append(train_accs[-1])
271
+ results["test_accuracies"].append(final_test_acc)
272
+
273
+ if final_test_acc > results["best_accuracy"]:
274
+ results["best_accuracy"] = final_test_acc
275
+ results["best_layer"] = layer_idx
276
+ results["best_confusion_matrix"] = confusion_matrix(labels, preds)
277
+
278
+ # Create performance visualization
279
+ self._plot_results(results)
280
+
281
+ return results
282
+
283
+ def _plot_results(self, results):
284
+ """Create visualization of probe performance across layers."""
285
+ plt.figure(figsize=(12, 4))
286
+
287
+ # Plot 1: Accuracy across layers
288
+ plt.subplot(1, 3, 1)
289
+ plt.plot(results["layers"], results["train_accuracies"], 'b-', label='Train', marker='o')
290
+ plt.plot(results["layers"], results["test_accuracies"], 'r-', label='Test', marker='s')
291
+ plt.axhline(y=100/results["num_classes"], color='gray', linestyle='--', label='Random')
292
+ plt.xlabel('Layer')
293
+ plt.ylabel('Accuracy (%)')
294
+ plt.title(f'{results["attribute"].capitalize()} Probe Performance')
295
+ plt.legend()
296
+ plt.grid(True, alpha=0.3)
297
+
298
+ # Plot 2: Best layer highlight
299
+ plt.subplot(1, 3, 2)
300
+ colors = ['red' if i != results["best_layer"] else 'green' for i in results["layers"]]
301
+ plt.bar(results["layers"], results["test_accuracies"], color=colors)
302
+ plt.xlabel('Layer')
303
+ plt.ylabel('Test Accuracy (%)')
304
+ plt.title(f'Best Layer: {results["best_layer"]} ({results["best_accuracy"]:.1f}%)')
305
+ plt.grid(True, alpha=0.3)
306
+
307
+ # Plot 3: Confusion matrix for best layer
308
+ plt.subplot(1, 3, 3)
309
+ cm = results["best_confusion_matrix"]
310
+ sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
311
+ xticklabels=results["class_names"],
312
+ yticklabels=results["class_names"])
313
+ plt.title(f'Confusion Matrix (Layer {results["best_layer"]})')
314
+ plt.ylabel('True Label')
315
+ plt.xlabel('Predicted Label')
316
+
317
+ plt.tight_layout()
318
+
319
+ # Save plot
320
+ output_file = f"probe_results_{results['attribute']}_{time.strftime('%Y%m%d_%H%M%S')}.png"
321
+ plt.savefig(output_file, dpi=150, bbox_inches='tight')
322
+ plt.close()
323
+
324
+ print(f"\nπŸ“Š Visualization saved to {output_file}")
325
+
326
+ return output_file
327
+
328
+ def run_full_training(experiment_name: str = "01_gpt2_synthetic_demo"):
329
+ """Run complete training demonstration with logging."""
330
+
331
+ # Setup logging
332
+ logger = setup_logging(experiment_name)
333
+
334
+ logger.info("="*80)
335
+ logger.info("Starting TalkTuner Probe Training")
336
+ logger.info("="*80)
337
+
338
+ print("""
339
+ ╔══════════════════════════════════════════════════════════════╗
340
+ β•‘ Minimal Probe Training Demonstration β•‘
341
+ β•‘ β•‘
342
+ β•‘ This uses GPT-2 with synthetic data for demonstration β•‘
343
+ β•‘ Real training would use Llama-2-13b with actual datasets β•‘
344
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
345
+ """)
346
+
347
+ device = "cuda" if torch.cuda.is_available() else "cpu"
348
+
349
+ # Log system information
350
+ logger.info(f"Python version: {sys.version}")
351
+ logger.info(f"PyTorch version: {torch.__version__}")
352
+ logger.info(f"Device: {device}")
353
+ logger.info(f"CUDA available: {torch.cuda.is_available()}")
354
+ if torch.cuda.is_available():
355
+ logger.info(f"GPU: {torch.cuda.get_device_name(0)}")
356
+
357
+ trainer = MinimalProbeTrainer(device=device, logger=logger)
358
+
359
+ all_results = {}
360
+
361
+ # Train probes for each attribute
362
+ for attribute in ["age", "gender", "socioeco", "education"]:
363
+ results = trainer.train_probes(attribute=attribute, num_layers_to_train=8)
364
+ all_results[attribute] = results
365
+
366
+ print(f"\nβœ… {attribute.capitalize()} Results:")
367
+ print(f" Best Layer: {results['best_layer']}")
368
+ print(f" Best Accuracy: {results['best_accuracy']:.2f}%")
369
+ print(f" Improvement over random: {results['best_accuracy'] - 100/results['num_classes']:.2f}%")
370
+
371
+ # Save all results
372
+ output_file = f"probe_training_results_{time.strftime('%Y%m%d_%H%M%S')}.json"
373
+ with open(output_file, "w") as f:
374
+ # Convert numpy arrays to lists for JSON serialization
375
+ json_results = {}
376
+ for attr, res in all_results.items():
377
+ json_results[attr] = {
378
+ k: v.tolist() if isinstance(v, np.ndarray) else v
379
+ for k, v in res.items() if k != "best_confusion_matrix"
380
+ }
381
+ json.dump(json_results, f, indent=2)
382
+
383
+ print(f"\nπŸ“Š Full results saved to {output_file}")
384
+
385
+ # Summary
386
+ print("\n" + "="*60)
387
+ print("TRAINING SUMMARY")
388
+ print("="*60)
389
+ for attr, res in all_results.items():
390
+ improvement = res['best_accuracy'] - 100/res['num_classes']
391
+ print(f"{attr:12s}: Layer {res['best_layer']:2d} | Accuracy: {res['best_accuracy']:5.1f}% | Improvement: +{improvement:4.1f}%")
392
+
393
+ return all_results
394
+
395
+ if __name__ == "__main__":
396
+ import sys
397
+ # Allow passing experiment name as command line argument
398
+ experiment_name = sys.argv[1] if len(sys.argv) > 1 else "02_real_initial_performance"
399
+ results = run_full_training(experiment_name)