Utils API¶
deeplens.utils.analysis
¶
AnalysisUtils
¶
Unified analysis utilities for model logits and SAE features.
This class provides methods for visualizing and analyzing transformer model outputs, including logit heatmaps, token probability distributions, and sparse autoencoder (SAE) feature extraction.
Source code in deeplens\utils\analysis.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | |
__init__(hf_model=None, sae_model=None, sae_config=None, layer=None, cache_dir='cache')
¶
Initialize the AnalysisUtils class for analyzing sparse autoencoder results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hf_model
|
str
|
Name or path of the HuggingFace model for extracting
MLP activations (e.g., "gpt2", "meta-llama/Llama-2-7b"). Required for
|
None
|
sae_model
|
str
|
Path to the trained sparse autoencoder model weights
file. Required for |
None
|
sae_config
|
str | dict
|
Path to the YAML configuration file or a
dictionary containing SAE hyperparameters. Required for
|
None
|
layer
|
int
|
Index of the transformer layer to extract activations
from (0-indexed). Required for |
None
|
cache_dir
|
str
|
Directory to cache downloaded models. Defaults to 'cache'. |
'cache'
|
Source code in deeplens\utils\analysis.py
generate_logit_heatmap(logits, save_name=None, k=None)
¶
Generate and display a heatmap visualization of logits across token positions.
Creates a color-coded heatmap showing the distribution of logit values across the vocabulary for each token position in a sequence. Uses the 'inferno' colormap for visualization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Logits tensor with shape (sequence_length, vocab_size) or similar. Will be automatically squeezed and moved to CPU if needed. |
required |
save_name
|
str
|
Filename (without extension) to save the plot. If provided, saves the figure as a PNG file with 300 DPI. If None, only displays the plot. Defaults to None. |
None
|
k
|
int
|
top k vocabulary indexes to plot. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
Displays the plot and optionally saves it to disk. |
Note
The figure size is set to (20, 6) for optimal visualization of typical sequence lengths and vocabulary sizes.
Source code in deeplens\utils\analysis.py
get_most_active_features(sentences, target=None, k=None, case_sensitive=True, return_values=False)
¶
Extract SAE latent features for specific tokens across multiple sentences.
This method processes a list of sentences through a transformer model and sparse autoencoder to extract active features at specified token positions. Useful for analyzing which SAE features activate for particular tokens or syntactic patterns.
Note
Requires hf_model, layer, sae_model, and sae_config to be set during
class initialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sentences
|
list[str]
|
List of input sentences to process. Each sentence will be tokenized and processed independently. |
required |
target
|
int | str | None
|
Specifies which token positions to analyze. - If int: Token position index (supports negative indexing, e.g., -1 for last token). - If str: Token string to match (e.g., "What"). Will find all occurrences. - If None: Extracts features for all token positions. Defaults to None. |
None
|
k
|
int | None
|
If provided, returns only the top-k most active features by activation magnitude. If None, returns all non-zero features. Defaults to None. |
None
|
case_sensitive
|
bool
|
Whether string matching for target tokens should be case-sensitive. Only applies when target is a string. Defaults to True. |
True
|
return_values
|
bool
|
Whether the function will return features and activation values of each feature. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, FeatureResult]
|
dict[str, FeatureResult]: Dictionary mapping descriptive keys to FeatureResult objects. Keys follow the format "sent_{idx}postok" where: - idx: 1-indexed sentence number - pos: 0-indexed token position within the sentence - token: The decoded token string (stripped of whitespace) Values are FeatureResult dataclass instances with: - features: Tensor containing indices of active/top-k features - values: Tensor of activation values (or None if return_values=False) |
Source code in deeplens\utils\analysis.py
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | |
get_top_k_tokens(logits, k=10, to_dataframe=True, verbose=False)
¶
Get the top-k predicted tokens and their probabilities for each position in a sequence.
Iterates through all positions in the sequence and extracts the k highest-scoring tokens at each position. Useful for detailed analysis of model predictions across the entire sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Logits tensor with shape (sequence_length, vocab_size) or similar. Will be automatically squeezed and moved to CPU if needed. |
required |
k
|
int
|
Number of top predictions to display per position. Defaults to 10. |
10
|
to_dataframe
|
bool
|
If True, returns the top-k predicted tokens at each position and their probabilities in a pandas DataFrame. Defaults to True. |
True
|
verbose
|
bool
|
If True, prints the results to the console. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame | list[dict]
|
pd.DataFrame | list[dict]: If to_dataframe=True, returns a DataFrame with columns 'position', 'rank', 'token', and 'probability'. Otherwise returns a list of dictionaries with the same fields. |
Example Output
Top-10 predicted tokens per position
Position 0: Token ('the'): 12.45 Token ('a'): 11.32 ...
Source code in deeplens\utils\analysis.py
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 | |
plot_topk_distribution(logits, k=20, position=0, save_name=None, use_softmax=True, title=None)
¶
Plot a bar chart showing the top-k most probable tokens at a specific sequence position.
Creates a horizontal bar chart displaying the highest-probability token predictions at a given position in the sequence. Useful for analyzing model predictions and understanding which tokens are most likely at specific positions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Logits tensor with shape (sequence_length, vocab_size) or similar. Will be automatically squeezed and moved to CPU if needed. |
required |
k
|
int
|
Number of top predictions to display in the bar chart. Defaults to 20. |
20
|
position
|
int
|
Token position in the sequence to analyze. Use 0-based indexing. Defaults to 0 (first token). |
0
|
save_name
|
str
|
Filename (without extension) to save the plot. If provided, saves the figure as a PNG file with 300 DPI. If None, only displays the plot. Defaults to None. |
None
|
use_softmax
|
bool
|
If True, applies softmax to convert logits to probabilities before plotting. If False, plots raw logit values. Defaults to True. |
True
|
title
|
str
|
Custom title for the plot. If None, no title is displayed. Defaults to None. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
Displays the plot and optionally saves it to disk. |
Note
Token labels are rotated 45 degrees for readability. The y-axis label changes based on use_softmax: shows probability notation if True, "Logit Value" if False.
Source code in deeplens\utils\analysis.py
deeplens.utils.dataset
¶
ActivationsDataset
¶
Bases: Dataset
Lightweight PyTorch Dataset wrapper for pre-computed activation tensors.
Provides a simple Dataset interface for tensors of neural network activations, enabling use with PyTorch DataLoader for batching and iteration.
Source code in deeplens\utils\dataset.py
__getitem__(idx)
¶
Retrieve activation tensor at the specified index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
int
|
Index of the sample to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
torch.Tensor: Activation tensor at the given index. |
Source code in deeplens\utils\dataset.py
__init__(activations)
¶
Initialize the dataset with activation tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
activations
|
Tensor
|
Tensor containing pre-computed activations with shape (num_samples, feature_dim). |
required |
Source code in deeplens\utils\dataset.py
__len__()
¶
Get the number of activation samples.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of samples in the dataset. |
ActivationsDatasetBuilder
¶
Builder class for creating DataLoaders from saved activation tensors.
Loads pre-computed activations from disk, applies optional normalization, and creates train/validation DataLoaders for training sparse autoencoders or other downstream models.
Source code in deeplens\utils\dataset.py
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | |
__init__(activations=None, splits=[0.8, 0.2], batch_size=16, norm=True)
¶
Initialize the builder and load activations from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
activations
|
Tensor | str
|
Path to a .pt file containing saved activation tensors, or a tensor directly. Defaults to None. |
None
|
splits
|
list
|
List of two floats representing train and validation split proportions. Must sum to 1.0. Defaults to [0.8, 0.2]. |
[0.8, 0.2]
|
batch_size
|
int
|
Number of samples per batch for DataLoaders. Defaults to 16. |
16
|
norm
|
bool
|
Whether to apply z-score normalization (standardization) to the activations. Defaults to True. |
True
|
Source code in deeplens\utils\dataset.py
get_dataloaders(ddp=False)
¶
Create train and validation DataLoaders from the activations.
Splits the dataset according to the specified proportions and creates two DataLoaders with appropriate settings for training and evaluation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ddp
|
bool
|
Turn to True if Distributed Data Parallel (DDP) training is intended. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[DataLoader, DataLoader]
|
A tuple containing (train_loader, eval_loader). Training loader has shuffle=True for randomized batching, evaluation loader has shuffle=False for consistent evaluation. |
Source code in deeplens\utils\dataset.py
normalize()
¶
Apply z-score normalization to the activations in-place.
Standardizes the activations by subtracting the mean and dividing by the standard deviation (computed along the batch dimension). Adds small epsilon (1e-8) to prevent division by zero. Only applies if norm=True was set during initialization.
Returns:
| Name | Type | Description |
|---|---|---|
None |
None
|
Modifies self.activations in-place. |
Source code in deeplens\utils\dataset.py
set_tensor_dataset()
¶
Create a PyTorch Dataset from the loaded activations.
Returns:
| Name | Type | Description |
|---|---|---|
Dataset |
Dataset
|
ActivationsDataset instance wrapping the activation tensors. |
AudioDatasetBuilder
¶
Bases: Dataset
PyTorch Dataset for loading and preprocessing audio files with optional mel spectrogram transformation.
This dataset handles audio files in various formats (WAV, MP3, FLAC), performs preprocessing operations like resampling, mono conversion, and padding, and optionally converts waveforms to mel spectrograms. Supports both labeled and unlabeled datasets.
Source code in deeplens\utils\dataset.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
__getitem__(index)
¶
Retrieve and preprocess an audio sample at the specified index.
Loads the audio file, applies preprocessing (resampling, mono conversion, padding/truncation), optionally transforms to mel spectrogram, and returns with label if annotations are available.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Index of the sample to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
Tensor | tuple[Tensor, int]
|
torch.Tensor | tuple[torch.Tensor, int]: If annotations are provided, returns a tuple of (processed_audio, label). Otherwise, returns only the processed audio tensor. Audio shape depends on transformation: (1, num_samples) for waveform or (1, n_mels, time_steps) for mel spectrogram. |
Source code in deeplens\utils\dataset.py
__init__(audio_dir=None, annotations_file=None, target_sample_rate=22050, num_samples=22050, device='auto', transformation_args={'n_fft': 1024, 'hop_length': 512, 'n_mels': 64})
¶
Initialize the AudioDatasetBuilder with audio preprocessing parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
audio_dir
|
str
|
Path to directory containing audio files. The directory should contain files with extensions .wav, .mp3, or .flac. Defaults to None. |
None
|
annotations_file
|
str
|
Path to CSV file containing annotations/labels. If None, dataset returns only audio without labels. Defaults to None. |
None
|
target_sample_rate
|
int
|
Target sampling rate in Hz for resampling. All audio will be resampled to this rate. Defaults to 22050. |
22050
|
num_samples
|
int
|
Target number of samples per audio clip. Audio will be truncated or zero-padded to this length. Defaults to 22050. |
22050
|
device
|
str
|
Device for tensor operations. Can be "auto" for automatic selection, "cuda", "mps", or "cpu". Defaults to "auto". |
'auto'
|
transformation_args
|
dict
|
Dictionary containing parameters for mel spectrogram transformation. Must include keys: "n_fft", "hop_length", "n_mels". If None, raw waveforms are returned without transformation. Defaults to {"n_fft": 1024, "hop_length": 512, "n_mels": 64}. |
{'n_fft': 1024, 'hop_length': 512, 'n_mels': 64}
|
Source code in deeplens\utils\dataset.py
__len__()
¶
Get the total number of samples in the dataset.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of audio samples. Returns length of annotations if provided, otherwise returns number of audio files in the directory. |
Source code in deeplens\utils\dataset.py
GetDataLoaders
¶
Utility class for creating train and test DataLoaders from a PyTorch Dataset.
Handles dataset splitting and DataLoader creation with consistent parameters.
Source code in deeplens\utils\dataset.py
__init__(dataset=None, splits=[0.8, 0.2], batch_size=16)
¶
Initialize the DataLoader factory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
Dataset
|
PyTorch Dataset to split and load. Defaults to None. |
None
|
splits
|
list
|
List of two floats representing train and test split proportions. Must sum to 1.0. Defaults to [0.8, 0.2]. |
[0.8, 0.2]
|
batch_size
|
int
|
Number of samples per batch. Defaults to 16. |
16
|
Source code in deeplens\utils\dataset.py
deeplens.utils.tools
¶
get_device(device='auto')
¶
Utility to set up the torch device. If 'auto', it selects the most appropriate device in your machine.
It can be set manually to 'mps', 'cuda', or 'cpu', but 'auto' is recommended.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str
|
The device in which the given process will be allocated. Defaults to 'auto'. |
'auto'
|
Returns:
| Type | Description |
|---|---|
device
|
torch.device: The selected device. |