Полная документация пакета¶
embeddings_squeeze: Vector Quantization for Segmentation Model Compression
Classes¶
VQWithProjection ¶
VQWithProjection(
input_dim,
codebook_size=512,
bottleneck_dim=64,
decay=0.99,
commitment_weight=0.25,
)
Bases: BaseQuantizer
Vector Quantization (VQ-VAE) with projections
Uses EMA for codebook updates (no gradients needed for codebook) ~9 bits per vector at codebook_size=512
Source code in embeddings_squeeze\models\quantizers.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
|
FSQWithProjection ¶
FSQWithProjection(input_dim, levels=None)
Bases: BaseQuantizer
Finite Scalar Quantization (FSQ)
Quantization without codebook - each dimension quantized independently ~10 bits per vector at levels=[8,5,5,5]
Source code in embeddings_squeeze\models\quantizers.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
|
LFQWithProjection ¶
LFQWithProjection(
input_dim,
codebook_size=512,
entropy_loss_weight=0.1,
diversity_gamma=0.1,
spherical=False,
)
Bases: BaseQuantizer
Lookup-Free Quantization (LFQ)
Uses entropy loss for code diversity ~9 bits per vector at codebook_size=512
Source code in embeddings_squeeze\models\quantizers.py
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 |
|
ResidualVQWithProjection ¶
ResidualVQWithProjection(
input_dim,
num_quantizers=4,
codebook_size=256,
bottleneck_dim=64,
decay=0.99,
commitment_weight=0.25,
)
Bases: BaseQuantizer
Residual Vector Quantization (RVQ)
Multi-level quantization - each level quantizes the residual of the previous 32 bits per vector at num_quantizers=4, codebook_size=256 (4*8 bits)
Source code in embeddings_squeeze\models\quantizers.py
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 |
|
BaseQuantizer ¶
BaseQuantizer(input_dim)
Bases: Module
Base class for all quantizers
Source code in embeddings_squeeze\models\quantizers.py
14 15 16 |
|
Functions¶
quantize_spatial ¶
quantize_spatial(features)
Quantize spatial features [B, C, H, W]
Parameters:
Name | Type | Description | Default |
---|---|---|---|
features
|
Tensor
|
Tensor of shape [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
quantized |
Quantized features [B, C, H, W] |
|
loss |
Quantization loss (scalar) |
Source code in embeddings_squeeze\models\quantizers.py
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 |
|
SegmentationBackbone ¶
SegmentationBackbone()
Bases: Module
, ABC
Abstract base class for segmentation backbones.
All segmentation backbones should inherit from this class and implement the required methods for feature extraction and full segmentation.
Source code in embeddings_squeeze\models\backbones\base.py
17 18 |
|
Attributes¶
Functions¶
extract_features
abstractmethod
¶
extract_features(images, detach=True)
Extract features from input images.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required | |
detach
|
Whether to detach gradients from backbone |
True
|
Returns:
Name | Type | Description |
---|---|---|
features |
Feature maps [B, feature_dim, H', W'] |
Source code in embeddings_squeeze\models\backbones\base.py
20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
forward
abstractmethod
¶
forward(images)
Full forward pass for segmentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\backbones\base.py
34 35 36 37 38 39 40 41 42 43 44 45 |
|
VQSqueezeModule ¶
VQSqueezeModule(
backbone,
quantizer=None,
num_classes=21,
learning_rate=0.0001,
vq_loss_weight=0.1,
loss_type="ce",
class_weights=None,
add_adapter=False,
feature_dim=2048,
clearml_logger=None,
**kwargs
)
Bases: LightningModule
PyTorch Lightning module for VQ compression training.
Features: - Multiple quantizer support (VQ, FSQ, LFQ, RVQ) - Adapter layers for fine-tuning frozen backbones - Advanced loss functions (CE, Dice, Focal, Combined) - Embedding extraction and saving
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
Functions¶
forward ¶
forward(images)
Forward pass through backbone + optional quantizer + decoder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
|
quant_loss |
Quantization loss (0 if no quantizer) |
|
original_features |
Extracted features (before quantization) |
|
quantized_features |
Features after quantization (same as original if no quantizer) |
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
training_step ¶
training_step(batch, batch_idx)
Training step.
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
validation_step ¶
validation_step(batch, batch_idx)
Validation step.
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
on_validation_epoch_start ¶
on_validation_epoch_start()
Clear accumulated embeddings at the start of each validation epoch.
Source code in embeddings_squeeze\models\lightning_module.py
270 271 272 273 |
|
on_validation_epoch_end ¶
on_validation_epoch_end()
Called after validation epoch ends - log Plotly visualizations and save embeddings.
Source code in embeddings_squeeze\models\lightning_module.py
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 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 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 |
|
configure_optimizers ¶
configure_optimizers()
Configure optimizer - only trainable parameters.
Source code in embeddings_squeeze\models\lightning_module.py
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
|
on_train_start ¶
on_train_start()
Ensure frozen backbone stays in eval mode.
Source code in embeddings_squeeze\models\lightning_module.py
494 495 496 497 |
|
BaselineSegmentationModule ¶
BaselineSegmentationModule(
backbone,
num_classes=21,
learning_rate=0.0001,
loss_type="ce",
class_weights=None,
clearml_logger=None,
**kwargs
)
Bases: LightningModule
PyTorch Lightning module for baseline segmentation training.
Wraps segmentation backbone without Vector Quantization for comparison.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
Functions¶
forward ¶
forward(images)
Forward pass through backbone.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\baseline_module.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
|
training_step ¶
training_step(batch, batch_idx)
Training step.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
validation_step ¶
validation_step(batch, batch_idx)
Validation step.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
on_validation_epoch_end ¶
on_validation_epoch_end()
Called after validation epoch ends - log Plotly visualizations.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
configure_optimizers ¶
configure_optimizers()
Configure optimizer.
Source code in embeddings_squeeze\models\baseline_module.py
228 229 230 231 232 |
|
predict ¶
predict(images)
Predict segmentation masks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
predictions |
Segmentation predictions [B, H, W] |
Source code in embeddings_squeeze\models\baseline_module.py
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
|
predict_logits ¶
predict_logits(images)
Predict segmentation logits.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
logits |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\baseline_module.py
250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
|
BaseDataModule ¶
BaseDataModule(
data_path,
batch_size=4,
num_workers=0,
pin_memory=True,
**kwargs
)
Bases: LightningDataModule
, ABC
Abstract base class for data modules.
All dataset-specific data modules should inherit from this class.
Source code in embeddings_squeeze\data\base.py
17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
Functions¶
setup
abstractmethod
¶
setup(stage=None)
Setup datasets for training/validation/testing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stage
|
str
|
'fit', 'validate', 'test', or None |
None
|
Source code in embeddings_squeeze\data\base.py
31 32 33 34 35 36 37 38 39 |
|
train_dataloader
abstractmethod
¶
train_dataloader(max_batches=None)
Return training dataloader.
Source code in embeddings_squeeze\data\base.py
41 42 43 44 |
|
val_dataloader
abstractmethod
¶
val_dataloader(max_batches=None)
Return validation dataloader.
Source code in embeddings_squeeze\data\base.py
46 47 48 49 |
|
test_dataloader
abstractmethod
¶
test_dataloader(max_batches=None)
Return test dataloader.
Source code in embeddings_squeeze\data\base.py
51 52 53 54 |
|
ClearMLLogger ¶
ClearMLLogger(task)
Wrapper for ClearML logging compatible with PyTorch Lightning. Supports scalar metrics, plots, images, and text logging.
Source code in embeddings_squeeze\loggers\clearml_logger.py
124 125 126 |
|
Functions¶
log_metrics ¶
log_metrics(metrics, step=None)
Log metrics to ClearML.
Source code in embeddings_squeeze\loggers\clearml_logger.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
|
log_scalar ¶
log_scalar(title, series, value, iteration)
Log a single scalar value to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Graph title (e.g., "loss", "accuracy") |
required |
series
|
str
|
Series name within the graph (e.g., "train", "val") |
required |
value
|
float
|
Scalar value to log |
required |
iteration
|
int
|
Iteration/step number |
required |
Example
logger.log_scalar("loss", "train", 0.5, iteration=100) logger.log_scalar("loss", "val", 0.3, iteration=100)
Source code in embeddings_squeeze\loggers\clearml_logger.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
|
log_image ¶
log_image(title, series, image, iteration)
Log an image to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Image title/group |
required |
series
|
str
|
Series name (e.g., "predictions", "ground_truth") |
required |
image
|
Image as numpy array (H, W) or (H, W, C) for grayscale/RGB Supports uint8 (0-255) or float (0-1) |
required | |
iteration
|
int
|
Iteration/step number |
required |
Example
Grayscale image¶
img = np.eye(256, 256, dtype=np.uint8) * 255 logger.log_image("predictions", "epoch_1", img, iteration=0)
RGB image¶
img_rgb = np.zeros((256, 256, 3), dtype=np.uint8) img_rgb[:, :, 0] = 255 # Red channel logger.log_image("predictions", "epoch_1_rgb", img_rgb, iteration=0)
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
log_images_batch ¶
log_images_batch(title, series, images, iteration)
Log multiple images to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Image title/group |
required |
series
|
str
|
Series name |
required |
images
|
list
|
List of images (numpy arrays) |
required |
iteration
|
int
|
Iteration/step number |
required |
Example
images = [img1, img2, img3] logger.log_images_batch("samples", "batch_0", images, iteration=0)
Source code in embeddings_squeeze\loggers\clearml_logger.py
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
|
log_text ¶
log_text(text, title='Info')
Log text to ClearML.
Source code in embeddings_squeeze\loggers\clearml_logger.py
228 229 230 231 232 |
|
report_text ¶
report_text(text)
Report text to ClearML (alias for log_text with default title).
Source code in embeddings_squeeze\loggers\clearml_logger.py
234 235 236 |
|
report_plotly ¶
report_plotly(title, series, iteration, figure)
Report a Plotly figure to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Plot title/group |
required |
series
|
str
|
Series name |
required |
iteration
|
int
|
Iteration/step number |
required |
figure
|
Plotly figure object |
required |
Example
import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter(x=[1,2,3], y=[4,5,6], mode='lines', name='data')) fig.update_layout(title="My Plot", xaxis_title="x", yaxis_title="y") logger.report_plotly("metrics", "loss", iteration=0, figure=fig)
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
finalize ¶
finalize()
Finalize logging and close task.
Source code in embeddings_squeeze\loggers\clearml_logger.py
265 266 267 268 |
|
Functions¶
setup_clearml ¶
setup_clearml(project_name, task_name, auto_connect=True)
Setup ClearML with credentials from config file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
project_name
|
str
|
ClearML project name |
required |
task_name
|
str
|
ClearML task name |
required |
auto_connect
|
bool
|
If True, automatically connect frameworks |
True
|
Returns:
Type | Description |
---|---|
Task object |
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
Modules¶
cli ¶
configs ¶
Configuration management for the package.
Classes¶
ModelConfig
dataclass
¶
ModelConfig(
backbone="vit",
num_classes=21,
freeze_backbone=True,
vit_weights="IMAGENET1K_V1",
deeplab_weights="COCO_WITH_VOC_LABELS_V1",
add_adapter=False,
feature_dim=768,
loss_type="ce",
class_weights=None,
)
Model architecture configuration.
TrainingConfig
dataclass
¶
TrainingConfig(
epochs=10,
batch_size=4,
max_batches=None,
learning_rate=0.0001,
vq_loss_weight=0.1,
num_workers=4,
pin_memory=True,
optimizer="adam",
weight_decay=0.0,
log_every_n_steps=50,
val_check_interval=1.0,
save_top_k=3,
monitor="val/loss",
mode="min",
)
Training configuration.
DataConfig
dataclass
¶
DataConfig(
dataset="oxford_pet",
data_path="./data",
image_size=224,
subset_size=None,
normalize_mean=(0.485, 0.456, 0.406),
normalize_std=(0.229, 0.224, 0.225),
)
Data configuration.
ExperimentConfig
dataclass
¶
ExperimentConfig(
model=ModelConfig(),
training=TrainingConfig(),
data=DataConfig(),
quantizer=QuantizerConfig(),
logger=LoggerConfig(),
experiment_name="vq_squeeze",
output_dir="./outputs",
seed=42,
initialize_codebook=True,
max_init_samples=50000,
)
Complete experiment configuration.
Functions¶
get_default_config ¶
get_default_config()
Get default configuration.
Source code in embeddings_squeeze\configs\default.py
122 123 124 |
|
Modules¶
default ¶
Default configuration classes and settings.
Classes¶
dataclass
¶QuantizerConfig(
enabled=True,
type="vq",
codebook_size=512,
bottleneck_dim=64,
decay=0.99,
commitment_weight=0.25,
levels=(lambda: [8, 5, 5, 5])(),
entropy_loss_weight=0.1,
diversity_gamma=0.1,
spherical=False,
num_quantizers=4,
)
Quantizer configuration.
dataclass
¶LoggerConfig(
use_clearml=True,
use_tensorboard=False,
project_name="embeddings_squeeze",
task_name="vq_compression",
credentials_file="clearml_credentials.yaml",
)
Logger configuration.
dataclass
¶ModelConfig(
backbone="vit",
num_classes=21,
freeze_backbone=True,
vit_weights="IMAGENET1K_V1",
deeplab_weights="COCO_WITH_VOC_LABELS_V1",
add_adapter=False,
feature_dim=768,
loss_type="ce",
class_weights=None,
)
Model architecture configuration.
dataclass
¶TrainingConfig(
epochs=10,
batch_size=4,
max_batches=None,
learning_rate=0.0001,
vq_loss_weight=0.1,
num_workers=4,
pin_memory=True,
optimizer="adam",
weight_decay=0.0,
log_every_n_steps=50,
val_check_interval=1.0,
save_top_k=3,
monitor="val/loss",
mode="min",
)
Training configuration.
dataclass
¶DataConfig(
dataset="oxford_pet",
data_path="./data",
image_size=224,
subset_size=None,
normalize_mean=(0.485, 0.456, 0.406),
normalize_std=(0.229, 0.224, 0.225),
)
Data configuration.
dataclass
¶ExperimentConfig(
model=ModelConfig(),
training=TrainingConfig(),
data=DataConfig(),
quantizer=QuantizerConfig(),
logger=LoggerConfig(),
experiment_name="vq_squeeze",
output_dir="./outputs",
seed=42,
initialize_codebook=True,
max_init_samples=50000,
)
Complete experiment configuration.
Functions¶
get_default_config()
Get default configuration.
Source code in embeddings_squeeze\configs\default.py
122 123 124 |
|
update_config_from_args(config, args)
Update configuration from command line arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config
|
ExperimentConfig
|
Base configuration |
required |
args
|
Dict[str, Any]
|
Command line arguments |
required |
Returns:
Type | Description |
---|---|
ExperimentConfig
|
Updated configuration |
Source code in embeddings_squeeze\configs\default.py
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 |
|
data ¶
Data modules for different datasets.
Classes¶
BaseDataModule ¶
BaseDataModule(
data_path,
batch_size=4,
num_workers=0,
pin_memory=True,
**kwargs
)
Bases: LightningDataModule
, ABC
Abstract base class for data modules.
All dataset-specific data modules should inherit from this class.
Source code in embeddings_squeeze\data\base.py
17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
Functions¶
abstractmethod
¶setup(stage=None)
Setup datasets for training/validation/testing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stage
|
str
|
'fit', 'validate', 'test', or None |
None
|
Source code in embeddings_squeeze\data\base.py
31 32 33 34 35 36 37 38 39 |
|
abstractmethod
¶train_dataloader(max_batches=None)
Return training dataloader.
Source code in embeddings_squeeze\data\base.py
41 42 43 44 |
|
abstractmethod
¶val_dataloader(max_batches=None)
Return validation dataloader.
Source code in embeddings_squeeze\data\base.py
46 47 48 49 |
|
abstractmethod
¶test_dataloader(max_batches=None)
Return test dataloader.
Source code in embeddings_squeeze\data\base.py
51 52 53 54 |
|
OxfordPetDataModule ¶
OxfordPetDataModule(
data_path="./data",
batch_size=4,
num_workers=4,
pin_memory=True,
image_size=224,
subset_size=None,
**kwargs
)
Bases: BaseDataModule
Data module for Oxford-IIIT Pet segmentation dataset.
Source code in embeddings_squeeze\data\oxford_pet.py
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 |
|
Functions¶
setup(stage=None)
Setup datasets.
Source code in embeddings_squeeze\data\oxford_pet.py
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 |
|
train_dataloader(max_batches=None)
Return training dataloader.
Source code in embeddings_squeeze\data\oxford_pet.py
120 121 122 123 124 125 126 127 128 129 |
|
val_dataloader(max_batches=None)
Return validation dataloader.
Source code in embeddings_squeeze\data\oxford_pet.py
131 132 133 134 135 136 137 138 139 140 |
|
test_dataloader(max_batches=None)
Return test dataloader.
Source code in embeddings_squeeze\data\oxford_pet.py
142 143 144 145 146 147 148 149 150 151 |
|
Modules¶
base ¶
Base data module for PyTorch Lightning.
Classes¶
BaseDataModule(
data_path,
batch_size=4,
num_workers=0,
pin_memory=True,
**kwargs
)
Bases: LightningDataModule
, ABC
Abstract base class for data modules.
All dataset-specific data modules should inherit from this class.
Source code in embeddings_squeeze\data\base.py
17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
abstractmethod
¶setup(stage=None)
Setup datasets for training/validation/testing.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stage
|
str
|
'fit', 'validate', 'test', or None |
None
|
Source code in embeddings_squeeze\data\base.py
31 32 33 34 35 36 37 38 39 |
|
abstractmethod
¶train_dataloader(max_batches=None)
Return training dataloader.
Source code in embeddings_squeeze\data\base.py
41 42 43 44 |
|
abstractmethod
¶val_dataloader(max_batches=None)
Return validation dataloader.
Source code in embeddings_squeeze\data\base.py
46 47 48 49 |
|
abstractmethod
¶test_dataloader(max_batches=None)
Return test dataloader.
Source code in embeddings_squeeze\data\base.py
51 52 53 54 |
|
oxford_pet ¶
Oxford-IIIT Pet dataset data module.
Classes¶
PetSegmentationDataset(
pet_dataset, transform_image, transform_mask
)
Wrapper for Oxford-IIIT Pet dataset with proper transforms.
Source code in embeddings_squeeze\data\oxford_pet.py
17 18 19 20 |
|
OxfordPetDataModule(
data_path="./data",
batch_size=4,
num_workers=4,
pin_memory=True,
image_size=224,
subset_size=None,
**kwargs
)
Bases: BaseDataModule
Data module for Oxford-IIIT Pet segmentation dataset.
Source code in embeddings_squeeze\data\oxford_pet.py
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 |
|
setup(stage=None)
Setup datasets.
Source code in embeddings_squeeze\data\oxford_pet.py
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 |
|
train_dataloader(max_batches=None)
Return training dataloader.
Source code in embeddings_squeeze\data\oxford_pet.py
120 121 122 123 124 125 126 127 128 129 |
|
val_dataloader(max_batches=None)
Return validation dataloader.
Source code in embeddings_squeeze\data\oxford_pet.py
131 132 133 134 135 136 137 138 139 140 |
|
test_dataloader(max_batches=None)
Return test dataloader.
Source code in embeddings_squeeze\data\oxford_pet.py
142 143 144 145 146 147 148 149 150 151 |
|
loggers ¶
Logger integrations for embeddings_squeeze.
Classes¶
ClearMLLogger ¶
ClearMLLogger(task)
Wrapper for ClearML logging compatible with PyTorch Lightning. Supports scalar metrics, plots, images, and text logging.
Source code in embeddings_squeeze\loggers\clearml_logger.py
124 125 126 |
|
Functions¶
log_metrics(metrics, step=None)
Log metrics to ClearML.
Source code in embeddings_squeeze\loggers\clearml_logger.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
|
log_scalar(title, series, value, iteration)
Log a single scalar value to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Graph title (e.g., "loss", "accuracy") |
required |
series
|
str
|
Series name within the graph (e.g., "train", "val") |
required |
value
|
float
|
Scalar value to log |
required |
iteration
|
int
|
Iteration/step number |
required |
Example
logger.log_scalar("loss", "train", 0.5, iteration=100) logger.log_scalar("loss", "val", 0.3, iteration=100)
Source code in embeddings_squeeze\loggers\clearml_logger.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
|
log_image(title, series, image, iteration)
Log an image to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Image title/group |
required |
series
|
str
|
Series name (e.g., "predictions", "ground_truth") |
required |
image
|
Image as numpy array (H, W) or (H, W, C) for grayscale/RGB Supports uint8 (0-255) or float (0-1) |
required | |
iteration
|
int
|
Iteration/step number |
required |
Example
Grayscale image¶
img = np.eye(256, 256, dtype=np.uint8) * 255 logger.log_image("predictions", "epoch_1", img, iteration=0)
RGB image¶
img_rgb = np.zeros((256, 256, 3), dtype=np.uint8) img_rgb[:, :, 0] = 255 # Red channel logger.log_image("predictions", "epoch_1_rgb", img_rgb, iteration=0)
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
log_images_batch(title, series, images, iteration)
Log multiple images to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Image title/group |
required |
series
|
str
|
Series name |
required |
images
|
list
|
List of images (numpy arrays) |
required |
iteration
|
int
|
Iteration/step number |
required |
Example
images = [img1, img2, img3] logger.log_images_batch("samples", "batch_0", images, iteration=0)
Source code in embeddings_squeeze\loggers\clearml_logger.py
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
|
log_text(text, title='Info')
Log text to ClearML.
Source code in embeddings_squeeze\loggers\clearml_logger.py
228 229 230 231 232 |
|
report_text(text)
Report text to ClearML (alias for log_text with default title).
Source code in embeddings_squeeze\loggers\clearml_logger.py
234 235 236 |
|
report_plotly(title, series, iteration, figure)
Report a Plotly figure to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Plot title/group |
required |
series
|
str
|
Series name |
required |
iteration
|
int
|
Iteration/step number |
required |
figure
|
Plotly figure object |
required |
Example
import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter(x=[1,2,3], y=[4,5,6], mode='lines', name='data')) fig.update_layout(title="My Plot", xaxis_title="x", yaxis_title="y") logger.report_plotly("metrics", "loss", iteration=0, figure=fig)
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
finalize()
Finalize logging and close task.
Source code in embeddings_squeeze\loggers\clearml_logger.py
265 266 267 268 |
|
ClearMLUploadCallback ¶
ClearMLUploadCallback(
task,
clearml_logger=None,
checkpoint_dir="checkpoints",
embedding_dir="embeddings",
)
Bases: Callback
PyTorch Lightning callback for logging checkpoint and embedding paths to ClearML.
Automatically logs local file paths for: - Latest checkpoint after each validation epoch - Per-epoch validation embeddings
Usage
from pytorch_lightning import Trainer from embeddings_squeeze.loggers import ClearMLUploadCallback, setup_clearml
task = setup_clearml(project_name="my_project", task_name="experiment_1") logger = ClearMLLogger(task) if task else None callback = ClearMLUploadCallback(task, logger, checkpoint_dir="checkpoints")
trainer = Trainer(callbacks=[callback], ...)
Initialize ClearML path logging callback.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
Task
|
ClearML Task object |
required |
clearml_logger
|
ClearMLLogger
|
ClearML logger for text reporting (optional) |
None
|
checkpoint_dir
|
str
|
Directory containing checkpoints |
'checkpoints'
|
embedding_dir
|
str
|
Directory containing embeddings |
'embeddings'
|
Source code in embeddings_squeeze\loggers\clearml_logger.py
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
|
Functions¶
on_validation_epoch_end(trainer, pl_module)
Called after validation epoch ends.
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
Functions¶
setup_clearml ¶
setup_clearml(project_name, task_name, auto_connect=True)
Setup ClearML with credentials from config file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
project_name
|
str
|
ClearML project name |
required |
task_name
|
str
|
ClearML task name |
required |
auto_connect
|
bool
|
If True, automatically connect frameworks |
True
|
Returns:
Type | Description |
---|---|
Task object |
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
Modules¶
clearml_logger ¶
ClearML logger integration with credentials management.
Usage Examples
Setup ClearML¶
task = setup_clearml(project_name="my_project", task_name="experiment_1") logger = ClearMLLogger(task)
Log scalar metrics (creates unified graphs)¶
for i in range(100): logger.log_scalar("loss", "train", 1.0/(i+1), iteration=i) logger.log_scalar("loss", "val", 0.5/(i+1), iteration=i)
Log images (grayscale)¶
import numpy as np img = np.eye(256, 256, dtype=np.uint8) * 255 logger.log_image("predictions", "sample_1", img, iteration=0)
Log RGB images¶
img_rgb = np.zeros((256, 256, 3), dtype=np.uint8) img_rgb[:, :, 0] = 255 # Red channel logger.log_image("predictions", "sample_rgb", img_rgb, iteration=0)
Log multiple images at once¶
images = [img1, img2, img3] logger.log_images_batch("batch_samples", "epoch_1", images, iteration=0)
Log text¶
logger.log_text("Training started successfully!")
Finalize¶
logger.finalize()
Classes¶
ClearMLLogger(task)
Wrapper for ClearML logging compatible with PyTorch Lightning. Supports scalar metrics, plots, images, and text logging.
Source code in embeddings_squeeze\loggers\clearml_logger.py
124 125 126 |
|
log_metrics(metrics, step=None)
Log metrics to ClearML.
Source code in embeddings_squeeze\loggers\clearml_logger.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
|
log_scalar(title, series, value, iteration)
Log a single scalar value to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Graph title (e.g., "loss", "accuracy") |
required |
series
|
str
|
Series name within the graph (e.g., "train", "val") |
required |
value
|
float
|
Scalar value to log |
required |
iteration
|
int
|
Iteration/step number |
required |
Example
logger.log_scalar("loss", "train", 0.5, iteration=100) logger.log_scalar("loss", "val", 0.3, iteration=100)
Source code in embeddings_squeeze\loggers\clearml_logger.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
|
log_image(title, series, image, iteration)
Log an image to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Image title/group |
required |
series
|
str
|
Series name (e.g., "predictions", "ground_truth") |
required |
image
|
Image as numpy array (H, W) or (H, W, C) for grayscale/RGB Supports uint8 (0-255) or float (0-1) |
required | |
iteration
|
int
|
Iteration/step number |
required |
Example
Grayscale image¶
img = np.eye(256, 256, dtype=np.uint8) * 255 logger.log_image("predictions", "epoch_1", img, iteration=0)
RGB image¶
img_rgb = np.zeros((256, 256, 3), dtype=np.uint8) img_rgb[:, :, 0] = 255 # Red channel logger.log_image("predictions", "epoch_1_rgb", img_rgb, iteration=0)
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
log_images_batch(title, series, images, iteration)
Log multiple images to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Image title/group |
required |
series
|
str
|
Series name |
required |
images
|
list
|
List of images (numpy arrays) |
required |
iteration
|
int
|
Iteration/step number |
required |
Example
images = [img1, img2, img3] logger.log_images_batch("samples", "batch_0", images, iteration=0)
Source code in embeddings_squeeze\loggers\clearml_logger.py
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
|
log_text(text, title='Info')
Log text to ClearML.
Source code in embeddings_squeeze\loggers\clearml_logger.py
228 229 230 231 232 |
|
report_text(text)
Report text to ClearML (alias for log_text with default title).
Source code in embeddings_squeeze\loggers\clearml_logger.py
234 235 236 |
|
report_plotly(title, series, iteration, figure)
Report a Plotly figure to ClearML.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
title
|
str
|
Plot title/group |
required |
series
|
str
|
Series name |
required |
iteration
|
int
|
Iteration/step number |
required |
figure
|
Plotly figure object |
required |
Example
import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter(x=[1,2,3], y=[4,5,6], mode='lines', name='data')) fig.update_layout(title="My Plot", xaxis_title="x", yaxis_title="y") logger.report_plotly("metrics", "loss", iteration=0, figure=fig)
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
finalize()
Finalize logging and close task.
Source code in embeddings_squeeze\loggers\clearml_logger.py
265 266 267 268 |
|
ClearMLUploadCallback(
task,
clearml_logger=None,
checkpoint_dir="checkpoints",
embedding_dir="embeddings",
)
Bases: Callback
PyTorch Lightning callback for logging checkpoint and embedding paths to ClearML.
Automatically logs local file paths for: - Latest checkpoint after each validation epoch - Per-epoch validation embeddings
Usage
from pytorch_lightning import Trainer from embeddings_squeeze.loggers import ClearMLUploadCallback, setup_clearml
task = setup_clearml(project_name="my_project", task_name="experiment_1") logger = ClearMLLogger(task) if task else None callback = ClearMLUploadCallback(task, logger, checkpoint_dir="checkpoints")
trainer = Trainer(callbacks=[callback], ...)
Initialize ClearML path logging callback.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
task
|
Task
|
ClearML Task object |
required |
clearml_logger
|
ClearMLLogger
|
ClearML logger for text reporting (optional) |
None
|
checkpoint_dir
|
str
|
Directory containing checkpoints |
'checkpoints'
|
embedding_dir
|
str
|
Directory containing embeddings |
'embeddings'
|
Source code in embeddings_squeeze\loggers\clearml_logger.py
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
|
on_validation_epoch_end(trainer, pl_module)
Called after validation epoch ends.
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
Functions¶
load_credentials(config_dir=None)
Load ClearML credentials from YAML file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config_dir
|
str
|
Directory containing clearml_credentials.yaml If None, uses the configs directory in embeddings_squeeze |
None
|
Returns:
Name | Type | Description |
---|---|---|
dict |
Credentials dictionary |
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
setup_clearml(project_name, task_name, auto_connect=True)
Setup ClearML with credentials from config file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
project_name
|
str
|
ClearML project name |
required |
task_name
|
str
|
ClearML task name |
required |
auto_connect
|
bool
|
If True, automatically connect frameworks |
True
|
Returns:
Type | Description |
---|---|
Task object |
Source code in embeddings_squeeze\loggers\clearml_logger.py
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 |
|
models ¶
Model architectures and components.
Classes¶
VQWithProjection ¶
VQWithProjection(
input_dim,
codebook_size=512,
bottleneck_dim=64,
decay=0.99,
commitment_weight=0.25,
)
Bases: BaseQuantizer
Vector Quantization (VQ-VAE) with projections
Uses EMA for codebook updates (no gradients needed for codebook) ~9 bits per vector at codebook_size=512
Source code in embeddings_squeeze\models\quantizers.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
|
FSQWithProjection ¶
FSQWithProjection(input_dim, levels=None)
Bases: BaseQuantizer
Finite Scalar Quantization (FSQ)
Quantization without codebook - each dimension quantized independently ~10 bits per vector at levels=[8,5,5,5]
Source code in embeddings_squeeze\models\quantizers.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
|
LFQWithProjection ¶
LFQWithProjection(
input_dim,
codebook_size=512,
entropy_loss_weight=0.1,
diversity_gamma=0.1,
spherical=False,
)
Bases: BaseQuantizer
Lookup-Free Quantization (LFQ)
Uses entropy loss for code diversity ~9 bits per vector at codebook_size=512
Source code in embeddings_squeeze\models\quantizers.py
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 |
|
ResidualVQWithProjection ¶
ResidualVQWithProjection(
input_dim,
num_quantizers=4,
codebook_size=256,
bottleneck_dim=64,
decay=0.99,
commitment_weight=0.25,
)
Bases: BaseQuantizer
Residual Vector Quantization (RVQ)
Multi-level quantization - each level quantizes the residual of the previous 32 bits per vector at num_quantizers=4, codebook_size=256 (4*8 bits)
Source code in embeddings_squeeze\models\quantizers.py
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 |
|
BaseQuantizer ¶
BaseQuantizer(input_dim)
Bases: Module
Base class for all quantizers
Source code in embeddings_squeeze\models\quantizers.py
14 15 16 |
|
Functions¶
quantize_spatial(features)
Quantize spatial features [B, C, H, W]
Parameters:
Name | Type | Description | Default |
---|---|---|---|
features
|
Tensor
|
Tensor of shape [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
quantized |
Quantized features [B, C, H, W] |
|
loss |
Quantization loss (scalar) |
Source code in embeddings_squeeze\models\quantizers.py
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 |
|
DiceLoss ¶
DiceLoss(smooth=1.0)
Bases: Module
Dice Loss for multi-class segmentation
Source code in embeddings_squeeze\models\losses.py
13 14 15 |
|
FocalLoss ¶
FocalLoss(alpha=1.0, gamma=2.0, reduction='mean')
Bases: Module
Focal Loss for handling class imbalance (multi-class via CE per-pixel)
Source code in embeddings_squeeze\models\losses.py
40 41 42 43 44 |
|
CombinedLoss ¶
CombinedLoss(
ce_weight=1.0,
dice_weight=1.0,
focal_weight=0.5,
class_weights=None,
)
Bases: Module
Combined loss: CE + Dice + Focal. Returns (total, ce, dice, focal).
Source code in embeddings_squeeze\models\losses.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
|
SegmentationBackbone ¶
SegmentationBackbone()
Bases: Module
, ABC
Abstract base class for segmentation backbones.
All segmentation backbones should inherit from this class and implement the required methods for feature extraction and full segmentation.
Source code in embeddings_squeeze\models\backbones\base.py
17 18 |
|
Attributes¶
Functions¶
abstractmethod
¶extract_features(images, detach=True)
Extract features from input images.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required | |
detach
|
Whether to detach gradients from backbone |
True
|
Returns:
Name | Type | Description |
---|---|---|
features |
Feature maps [B, feature_dim, H', W'] |
Source code in embeddings_squeeze\models\backbones\base.py
20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
abstractmethod
¶forward(images)
Full forward pass for segmentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\backbones\base.py
34 35 36 37 38 39 40 41 42 43 44 45 |
|
VQSqueezeModule ¶
VQSqueezeModule(
backbone,
quantizer=None,
num_classes=21,
learning_rate=0.0001,
vq_loss_weight=0.1,
loss_type="ce",
class_weights=None,
add_adapter=False,
feature_dim=2048,
clearml_logger=None,
**kwargs
)
Bases: LightningModule
PyTorch Lightning module for VQ compression training.
Features: - Multiple quantizer support (VQ, FSQ, LFQ, RVQ) - Adapter layers for fine-tuning frozen backbones - Advanced loss functions (CE, Dice, Focal, Combined) - Embedding extraction and saving
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
Functions¶
forward(images)
Forward pass through backbone + optional quantizer + decoder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
|
quant_loss |
Quantization loss (0 if no quantizer) |
|
original_features |
Extracted features (before quantization) |
|
quantized_features |
Features after quantization (same as original if no quantizer) |
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
training_step(batch, batch_idx)
Training step.
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
validation_step(batch, batch_idx)
Validation step.
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
on_validation_epoch_start()
Clear accumulated embeddings at the start of each validation epoch.
Source code in embeddings_squeeze\models\lightning_module.py
270 271 272 273 |
|
on_validation_epoch_end()
Called after validation epoch ends - log Plotly visualizations and save embeddings.
Source code in embeddings_squeeze\models\lightning_module.py
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 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 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 |
|
configure_optimizers()
Configure optimizer - only trainable parameters.
Source code in embeddings_squeeze\models\lightning_module.py
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
|
on_train_start()
Ensure frozen backbone stays in eval mode.
Source code in embeddings_squeeze\models\lightning_module.py
494 495 496 497 |
|
BaselineSegmentationModule ¶
BaselineSegmentationModule(
backbone,
num_classes=21,
learning_rate=0.0001,
loss_type="ce",
class_weights=None,
clearml_logger=None,
**kwargs
)
Bases: LightningModule
PyTorch Lightning module for baseline segmentation training.
Wraps segmentation backbone without Vector Quantization for comparison.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
Functions¶
forward(images)
Forward pass through backbone.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\baseline_module.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
|
training_step(batch, batch_idx)
Training step.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
validation_step(batch, batch_idx)
Validation step.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
on_validation_epoch_end()
Called after validation epoch ends - log Plotly visualizations.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
configure_optimizers()
Configure optimizer.
Source code in embeddings_squeeze\models\baseline_module.py
228 229 230 231 232 |
|
predict(images)
Predict segmentation masks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
predictions |
Segmentation predictions [B, H, W] |
Source code in embeddings_squeeze\models\baseline_module.py
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
|
predict_logits(images)
Predict segmentation logits.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
logits |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\baseline_module.py
250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
|
Modules¶
backbones ¶
Segmentation backbone implementations.
Classes¶
SegmentationBackbone()
Bases: Module
, ABC
Abstract base class for segmentation backbones.
All segmentation backbones should inherit from this class and implement the required methods for feature extraction and full segmentation.
Source code in embeddings_squeeze\models\backbones\base.py
17 18 |
|
abstractmethod
¶extract_features(images, detach=True)
Extract features from input images.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required | |
detach
|
Whether to detach gradients from backbone |
True
|
Returns:
Name | Type | Description |
---|---|---|
features |
Feature maps [B, feature_dim, H', W'] |
Source code in embeddings_squeeze\models\backbones\base.py
20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
abstractmethod
¶forward(images)
Full forward pass for segmentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\backbones\base.py
34 35 36 37 38 39 40 41 42 43 44 45 |
|
ViTSegmentationBackbone(
model_fn=vit_b_32,
weights=ViT_B_32_Weights.IMAGENET1K_V1,
num_classes=21,
freeze_backbone=True,
)
Bases: SegmentationBackbone
ViT-based segmentation backbone.
Uses ViT-B/32 as backbone with custom segmentation head.
Source code in embeddings_squeeze\models\backbones\vit.py
66 67 68 69 70 71 72 73 74 75 76 77 78 |
|
extract_features(images, detach=True)
Extract ViT backbone feature maps.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required | |
detach
|
Whether to detach gradients from backbone |
True
|
Returns:
Name | Type | Description |
---|---|---|
features |
Feature maps [B, hidden_dim, H/patch, W/patch] |
Source code in embeddings_squeeze\models\backbones\vit.py
80 81 82 83 84 85 86 87 88 89 90 91 92 |
|
forward(images)
Full ViT segmentation forward pass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\backbones\vit.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
|
DeepLabV3SegmentationBackbone(
weights_name="COCO_WITH_VOC_LABELS_V1",
num_classes=21,
freeze_backbone=True,
)
Bases: SegmentationBackbone
DeepLabV3-ResNet50 segmentation backbone.
Uses pre-trained DeepLabV3-ResNet50 for segmentation.
Source code in embeddings_squeeze\models\backbones\deeplab.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
extract_features(images, detach=True)
Extract DeepLabV3 backbone features.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required | |
detach
|
Whether to detach gradients from backbone |
True
|
Returns:
Name | Type | Description |
---|---|---|
features |
Feature maps [B, 2048, H/8, W/8] |
Source code in embeddings_squeeze\models\backbones\deeplab.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
|
forward(images)
Full DeepLabV3 segmentation forward pass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\backbones\deeplab.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
|
Modules¶
Abstract base class for segmentation backbones.
SegmentationBackbone()
Bases: Module
, ABC
Abstract base class for segmentation backbones.
All segmentation backbones should inherit from this class and implement the required methods for feature extraction and full segmentation.
Source code in embeddings_squeeze\models\backbones\base.py
17 18 |
|
abstractmethod
¶extract_features(images, detach=True)
Extract features from input images.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required | |
detach
|
Whether to detach gradients from backbone |
True
|
Returns:
Name | Type | Description |
---|---|---|
features |
Feature maps [B, feature_dim, H', W'] |
Source code in embeddings_squeeze\models\backbones\base.py
20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
abstractmethod
¶forward(images)
Full forward pass for segmentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\backbones\base.py
34 35 36 37 38 39 40 41 42 43 44 45 |
|
DeepLabV3-ResNet50 segmentation backbone implementation.
DeepLabV3SegmentationBackbone(
weights_name="COCO_WITH_VOC_LABELS_V1",
num_classes=21,
freeze_backbone=True,
)
Bases: SegmentationBackbone
DeepLabV3-ResNet50 segmentation backbone.
Uses pre-trained DeepLabV3-ResNet50 for segmentation.
Source code in embeddings_squeeze\models\backbones\deeplab.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
extract_features(images, detach=True)
Extract DeepLabV3 backbone features.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required | |
detach
|
Whether to detach gradients from backbone |
True
|
Returns:
Name | Type | Description |
---|---|---|
features |
Feature maps [B, 2048, H/8, W/8] |
Source code in embeddings_squeeze\models\backbones\deeplab.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
|
forward(images)
Full DeepLabV3 segmentation forward pass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\backbones\deeplab.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
|
ViT-based segmentation backbone implementation.
ViTSegmentationBackbone(
model_fn=vit_b_32,
weights=ViT_B_32_Weights.IMAGENET1K_V1,
num_classes=21,
freeze_backbone=True,
)
Bases: SegmentationBackbone
ViT-based segmentation backbone.
Uses ViT-B/32 as backbone with custom segmentation head.
Source code in embeddings_squeeze\models\backbones\vit.py
66 67 68 69 70 71 72 73 74 75 76 77 78 |
|
extract_features(images, detach=True)
Extract ViT backbone feature maps.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required | |
detach
|
Whether to detach gradients from backbone |
True
|
Returns:
Name | Type | Description |
---|---|---|
features |
Feature maps [B, hidden_dim, H/patch, W/patch] |
Source code in embeddings_squeeze\models\backbones\vit.py
80 81 82 83 84 85 86 87 88 89 90 91 92 |
|
forward(images)
Full ViT segmentation forward pass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\backbones\vit.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
|
baseline_module ¶
PyTorch Lightning module for baseline segmentation training without VQ.
Classes¶
BaselineSegmentationModule(
backbone,
num_classes=21,
learning_rate=0.0001,
loss_type="ce",
class_weights=None,
clearml_logger=None,
**kwargs
)
Bases: LightningModule
PyTorch Lightning module for baseline segmentation training.
Wraps segmentation backbone without Vector Quantization for comparison.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
forward(images)
Forward pass through backbone.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\baseline_module.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
|
training_step(batch, batch_idx)
Training step.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
validation_step(batch, batch_idx)
Validation step.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
on_validation_epoch_end()
Called after validation epoch ends - log Plotly visualizations.
Source code in embeddings_squeeze\models\baseline_module.py
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 |
|
configure_optimizers()
Configure optimizer.
Source code in embeddings_squeeze\models\baseline_module.py
228 229 230 231 232 |
|
predict(images)
Predict segmentation masks.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
predictions |
Segmentation predictions [B, H, W] |
Source code in embeddings_squeeze\models\baseline_module.py
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
|
predict_logits(images)
Predict segmentation logits.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
logits |
Segmentation logits [B, num_classes, H, W] |
Source code in embeddings_squeeze\models\baseline_module.py
250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
|
lightning_module ¶
PyTorch Lightning module for VQ compression training with advanced features. Supports multiple quantizers (VQ, FSQ, LFQ, RVQ), adapters, and loss functions.
Classes¶
VQSqueezeModule(
backbone,
quantizer=None,
num_classes=21,
learning_rate=0.0001,
vq_loss_weight=0.1,
loss_type="ce",
class_weights=None,
add_adapter=False,
feature_dim=2048,
clearml_logger=None,
**kwargs
)
Bases: LightningModule
PyTorch Lightning module for VQ compression training.
Features: - Multiple quantizer support (VQ, FSQ, LFQ, RVQ) - Adapter layers for fine-tuning frozen backbones - Advanced loss functions (CE, Dice, Focal, Combined) - Embedding extraction and saving
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
forward(images)
Forward pass through backbone + optional quantizer + decoder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images
|
Input images [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
output |
Segmentation logits [B, num_classes, H, W] |
|
quant_loss |
Quantization loss (0 if no quantizer) |
|
original_features |
Extracted features (before quantization) |
|
quantized_features |
Features after quantization (same as original if no quantizer) |
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
training_step(batch, batch_idx)
Training step.
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
validation_step(batch, batch_idx)
Validation step.
Source code in embeddings_squeeze\models\lightning_module.py
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 |
|
on_validation_epoch_start()
Clear accumulated embeddings at the start of each validation epoch.
Source code in embeddings_squeeze\models\lightning_module.py
270 271 272 273 |
|
on_validation_epoch_end()
Called after validation epoch ends - log Plotly visualizations and save embeddings.
Source code in embeddings_squeeze\models\lightning_module.py
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 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 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 |
|
configure_optimizers()
Configure optimizer - only trainable parameters.
Source code in embeddings_squeeze\models\lightning_module.py
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
|
on_train_start()
Ensure frozen backbone stays in eval mode.
Source code in embeddings_squeeze\models\lightning_module.py
494 495 496 497 |
|
losses ¶
Loss functions for segmentation tasks. Includes: Cross Entropy, Dice Loss, Focal Loss, and Combined Loss.
Classes¶
DiceLoss(smooth=1.0)
Bases: Module
Dice Loss for multi-class segmentation
Source code in embeddings_squeeze\models\losses.py
13 14 15 |
|
FocalLoss(alpha=1.0, gamma=2.0, reduction='mean')
Bases: Module
Focal Loss for handling class imbalance (multi-class via CE per-pixel)
Source code in embeddings_squeeze\models\losses.py
40 41 42 43 44 |
|
CombinedLoss(
ce_weight=1.0,
dice_weight=1.0,
focal_weight=0.5,
class_weights=None,
)
Bases: Module
Combined loss: CE + Dice + Focal. Returns (total, ce, dice, focal).
Source code in embeddings_squeeze\models\losses.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
|
quantizers ¶
Vector Quantization implementations using vector_quantize_pytorch library. Supports: VQ-VAE, FSQ, LFQ, and Residual VQ.
Classes¶
BaseQuantizer(input_dim)
Bases: Module
Base class for all quantizers
Source code in embeddings_squeeze\models\quantizers.py
14 15 16 |
|
quantize_spatial(features)
Quantize spatial features [B, C, H, W]
Parameters:
Name | Type | Description | Default |
---|---|---|---|
features
|
Tensor
|
Tensor of shape [B, C, H, W] |
required |
Returns:
Name | Type | Description |
---|---|---|
quantized |
Quantized features [B, C, H, W] |
|
loss |
Quantization loss (scalar) |
Source code in embeddings_squeeze\models\quantizers.py
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 |
|
VQWithProjection(
input_dim,
codebook_size=512,
bottleneck_dim=64,
decay=0.99,
commitment_weight=0.25,
)
Bases: BaseQuantizer
Vector Quantization (VQ-VAE) with projections
Uses EMA for codebook updates (no gradients needed for codebook) ~9 bits per vector at codebook_size=512
Source code in embeddings_squeeze\models\quantizers.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
|
FSQWithProjection(input_dim, levels=None)
Bases: BaseQuantizer
Finite Scalar Quantization (FSQ)
Quantization without codebook - each dimension quantized independently ~10 bits per vector at levels=[8,5,5,5]
Source code in embeddings_squeeze\models\quantizers.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
|
LFQWithProjection(
input_dim,
codebook_size=512,
entropy_loss_weight=0.1,
diversity_gamma=0.1,
spherical=False,
)
Bases: BaseQuantizer
Lookup-Free Quantization (LFQ)
Uses entropy loss for code diversity ~9 bits per vector at codebook_size=512
Source code in embeddings_squeeze\models\quantizers.py
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 |
|
ResidualVQWithProjection(
input_dim,
num_quantizers=4,
codebook_size=256,
bottleneck_dim=64,
decay=0.99,
commitment_weight=0.25,
)
Bases: BaseQuantizer
Residual Vector Quantization (RVQ)
Multi-level quantization - each level quantizes the residual of the previous 32 bits per vector at num_quantizers=4, codebook_size=256 (4*8 bits)
Source code in embeddings_squeeze\models\quantizers.py
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 |
|
squeeze ¶
CLI script for VQ compression training.
Usage
python squeeze.py --model vit --dataset oxford_pet --num_vectors 128 --epochs 3
Functions¶
create_quantizer ¶
create_quantizer(config)
Create quantizer based on config.
Source code in embeddings_squeeze\squeeze.py
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 |
|
create_backbone ¶
create_backbone(config)
Create segmentation backbone based on config.
Source code in embeddings_squeeze\squeeze.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
|
create_data_module ¶
create_data_module(config)
Create data module based on config.
Source code in embeddings_squeeze\squeeze.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
|
setup_logging_and_callbacks ¶
setup_logging_and_callbacks(config)
Setup logging and callbacks.
Source code in embeddings_squeeze\squeeze.py
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 |
|
main ¶
main()
Main training function.
Source code in embeddings_squeeze\squeeze.py
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 |
|
test_integration ¶
Test script to verify the complete VQ visualization workflow.
This script tests the integration of all components without running full training.
Functions¶
test_model_creation ¶
test_model_creation()
Test that models can be created successfully.
Source code in embeddings_squeeze\test_integration.py
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 |
|
test_data_loading ¶
test_data_loading()
Test that data can be loaded successfully.
Source code in embeddings_squeeze\test_integration.py
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 |
|
test_model_inference ¶
test_model_inference(vq_model, baseline_model, test_loader)
Test that models can run inference.
Source code in embeddings_squeeze\test_integration.py
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 |
|
test_visualization_utilities ¶
test_visualization_utilities()
Test visualization utilities.
Source code in embeddings_squeeze\test_integration.py
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 |
|
main ¶
main()
Run all tests.
Source code in embeddings_squeeze\test_integration.py
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 |
|
test_simplified_baseline ¶
Test script to verify the simplified baseline training approach.
Functions¶
test_backbone_classifier_training ¶
test_backbone_classifier_training()
Test that backbone classifiers are trainable when backbone is frozen.
Source code in embeddings_squeeze\test_simplified_baseline.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
|
test_optimizer_creation ¶
test_optimizer_creation()
Test that optimizers can be created.
Source code in embeddings_squeeze\test_simplified_baseline.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
|
main ¶
main()
Run all tests.
Source code in embeddings_squeeze\test_simplified_baseline.py
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 |
|
train_baseline ¶
CLI script for baseline segmentation training without VQ.
This script directly uses the existing backbone's trainable classifier head while keeping the backbone frozen.
Usage
python train_baseline.py --model vit --dataset oxford_pet --epochs 3
Functions¶
create_backbone ¶
create_backbone(config)
Create segmentation backbone based on config.
Source code in embeddings_squeeze\train_baseline.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
|
create_data_module ¶
create_data_module(config)
Create data module based on config.
Source code in embeddings_squeeze\train_baseline.py
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
|
setup_logging_and_callbacks ¶
setup_logging_and_callbacks(config)
Setup logging and callbacks.
Source code in embeddings_squeeze\train_baseline.py
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 |
|
main ¶
main()
Main training function.
Source code in embeddings_squeeze\train_baseline.py
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 |
|
utils ¶
Utility functions for VQ compression.
Functions¶
measure_compression ¶
measure_compression(
vq_model, backbone, test_loader, device
)
Measure compression ratio achieved by VQ.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vq_model
|
VectorQuantizer model |
required | |
backbone
|
Segmentation backbone |
required | |
test_loader
|
Test data loader |
required | |
device
|
Device to run on |
required |
Returns:
Name | Type | Description |
---|---|---|
compression_ratio |
Compression ratio achieved |
Source code in embeddings_squeeze\utils\compression.py
10 11 12 13 14 15 16 17 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 |
|
compute_iou_metrics ¶
compute_iou_metrics(
predictions, targets, num_classes, ignore_index=255
)
Compute IoU metrics for segmentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predictions
|
Predicted masks [B, H, W] |
required | |
targets
|
Ground truth masks [B, H, W] |
required | |
num_classes
|
Number of classes |
required | |
ignore_index
|
Index to ignore in computation |
255
|
Returns:
Name | Type | Description |
---|---|---|
metrics |
Dictionary with IoU metrics |
Source code in embeddings_squeeze\utils\compression.py
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 |
|
initialize_codebook_from_data ¶
initialize_codebook_from_data(
vq_model,
backbone,
train_loader,
device,
max_samples=50000,
)
Initialize codebook using k-means clustering on real data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vq_model
|
VectorQuantizer model |
required | |
backbone
|
Segmentation backbone |
required | |
train_loader
|
Training data loader |
required | |
device
|
Device to run on |
required | |
max_samples
|
int
|
Maximum number of samples for k-means |
50000
|
Source code in embeddings_squeeze\utils\initialization.py
11 12 13 14 15 16 17 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 |
|
compute_sample_iou ¶
compute_sample_iou(
prediction, target, num_classes, ignore_index=255
)
Compute IoU for a single sample.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prediction
|
Tensor
|
Predicted mask [H, W] |
required |
target
|
Tensor
|
Ground truth mask [H, W] |
required |
num_classes
|
int
|
Number of classes |
required |
ignore_index
|
int
|
Index to ignore in computation |
255
|
Returns:
Name | Type | Description |
---|---|---|
iou |
float
|
Mean IoU across all classes |
Source code in embeddings_squeeze\utils\comparison.py
13 14 15 16 17 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 |
|
evaluate_model ¶
evaluate_model(model, dataloader, device, num_classes=21)
Evaluate model on dataset and collect results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Model to evaluate |
required | |
dataloader
|
Data loader |
required | |
device
|
Device to run on |
required | |
num_classes
|
int
|
Number of classes |
21
|
Returns:
Name | Type | Description |
---|---|---|
results |
List[Tuple[int, float, Tensor, Tensor, Tensor]]
|
List of (sample_idx, iou, image, mask, prediction) tuples |
Source code in embeddings_squeeze\utils\comparison.py
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 |
|
find_best_worst_samples ¶
find_best_worst_samples(results, n_best=5, n_worst=5)
Find best and worst samples based on IoU.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
results
|
List[Tuple[int, float, Tensor, Tensor, Tensor]]
|
List of (sample_idx, iou, image, mask, prediction) tuples |
required |
n_best
|
int
|
Number of best samples to return |
5
|
n_worst
|
int
|
Number of worst samples to return |
5
|
Returns:
Name | Type | Description |
---|---|---|
best_samples |
List
|
List of best sample tuples |
worst_samples |
List
|
List of worst sample tuples |
Source code in embeddings_squeeze\utils\comparison.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
|
prepare_visualization_data ¶
prepare_visualization_data(
vq_model,
baseline_model,
dataloader,
device,
num_classes=21,
n_best=5,
n_worst=5,
)
Prepare data for visualization by running both models and ranking results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vq_model
|
VQ model |
required | |
baseline_model
|
Baseline model |
required | |
dataloader
|
Data loader |
required | |
device
|
Device to run on |
required | |
num_classes
|
int
|
Number of classes |
21
|
n_best
|
int
|
Number of best samples |
5
|
n_worst
|
int
|
Number of worst samples |
5
|
Returns:
Name | Type | Description |
---|---|---|
best_samples |
List of best sample tuples with both predictions |
|
worst_samples |
List of worst sample tuples with both predictions |
Source code in embeddings_squeeze\utils\comparison.py
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 |
|
visualize_comparison ¶
visualize_comparison(
samples, title, output_path, num_classes=21
)
Create visualization comparing baseline and VQ predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
samples
|
List[Tuple[int, float, Tensor, Tensor, Tensor, Tensor]]
|
List of (idx, iou, image, mask, pred_baseline, pred_vq) tuples |
required |
title
|
str
|
Figure title |
required |
output_path
|
str
|
Path to save figure |
required |
num_classes
|
int
|
Number of classes |
21
|
Source code in embeddings_squeeze\utils\comparison.py
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 |
|
Modules¶
comparison ¶
Comparison utilities for VQ vs baseline segmentation evaluation.
Functions¶
compute_sample_iou(
prediction, target, num_classes, ignore_index=255
)
Compute IoU for a single sample.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prediction
|
Tensor
|
Predicted mask [H, W] |
required |
target
|
Tensor
|
Ground truth mask [H, W] |
required |
num_classes
|
int
|
Number of classes |
required |
ignore_index
|
int
|
Index to ignore in computation |
255
|
Returns:
Name | Type | Description |
---|---|---|
iou |
float
|
Mean IoU across all classes |
Source code in embeddings_squeeze\utils\comparison.py
13 14 15 16 17 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 |
|
evaluate_model(model, dataloader, device, num_classes=21)
Evaluate model on dataset and collect results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model
|
Model to evaluate |
required | |
dataloader
|
Data loader |
required | |
device
|
Device to run on |
required | |
num_classes
|
int
|
Number of classes |
21
|
Returns:
Name | Type | Description |
---|---|---|
results |
List[Tuple[int, float, Tensor, Tensor, Tensor]]
|
List of (sample_idx, iou, image, mask, prediction) tuples |
Source code in embeddings_squeeze\utils\comparison.py
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 |
|
find_best_worst_samples(results, n_best=5, n_worst=5)
Find best and worst samples based on IoU.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
results
|
List[Tuple[int, float, Tensor, Tensor, Tensor]]
|
List of (sample_idx, iou, image, mask, prediction) tuples |
required |
n_best
|
int
|
Number of best samples to return |
5
|
n_worst
|
int
|
Number of worst samples to return |
5
|
Returns:
Name | Type | Description |
---|---|---|
best_samples |
List
|
List of best sample tuples |
worst_samples |
List
|
List of worst sample tuples |
Source code in embeddings_squeeze\utils\comparison.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 |
|
prepare_visualization_data(
vq_model,
baseline_model,
dataloader,
device,
num_classes=21,
n_best=5,
n_worst=5,
)
Prepare data for visualization by running both models and ranking results.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vq_model
|
VQ model |
required | |
baseline_model
|
Baseline model |
required | |
dataloader
|
Data loader |
required | |
device
|
Device to run on |
required | |
num_classes
|
int
|
Number of classes |
21
|
n_best
|
int
|
Number of best samples |
5
|
n_worst
|
int
|
Number of worst samples |
5
|
Returns:
Name | Type | Description |
---|---|---|
best_samples |
List of best sample tuples with both predictions |
|
worst_samples |
List of worst sample tuples with both predictions |
Source code in embeddings_squeeze\utils\comparison.py
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 |
|
denormalize_image(
image,
mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225),
)
Denormalize image for visualization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image
|
Tensor
|
Normalized image tensor [C, H, W] |
required |
mean
|
Tuple[float, float, float]
|
Normalization mean |
(0.485, 0.456, 0.406)
|
std
|
Tuple[float, float, float]
|
Normalization std |
(0.229, 0.224, 0.225)
|
Returns:
Name | Type | Description |
---|---|---|
denormalized |
Tensor
|
Denormalized image tensor |
Source code in embeddings_squeeze\utils\comparison.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
|
create_segmentation_colormap(num_classes=21)
Create a colormap for segmentation visualization.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_classes
|
int
|
Number of classes |
21
|
Returns:
Name | Type | Description |
---|---|---|
colormap |
ListedColormap
|
Matplotlib colormap |
Source code in embeddings_squeeze\utils\comparison.py
186 187 188 189 190 191 192 193 194 195 196 197 198 199 |
|
visualize_comparison(
samples, title, output_path, num_classes=21
)
Create visualization comparing baseline and VQ predictions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
samples
|
List[Tuple[int, float, Tensor, Tensor, Tensor, Tensor]]
|
List of (idx, iou, image, mask, pred_baseline, pred_vq) tuples |
required |
title
|
str
|
Figure title |
required |
output_path
|
str
|
Path to save figure |
required |
num_classes
|
int
|
Number of classes |
21
|
Source code in embeddings_squeeze\utils\comparison.py
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 |
|
compression ¶
Compression analysis and metrics utilities.
Functions¶
measure_compression(
vq_model, backbone, test_loader, device
)
Measure compression ratio achieved by VQ.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vq_model
|
VectorQuantizer model |
required | |
backbone
|
Segmentation backbone |
required | |
test_loader
|
Test data loader |
required | |
device
|
Device to run on |
required |
Returns:
Name | Type | Description |
---|---|---|
compression_ratio |
Compression ratio achieved |
Source code in embeddings_squeeze\utils\compression.py
10 11 12 13 14 15 16 17 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 |
|
compute_iou_metrics(
predictions, targets, num_classes, ignore_index=255
)
Compute IoU metrics for segmentation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predictions
|
Predicted masks [B, H, W] |
required | |
targets
|
Ground truth masks [B, H, W] |
required | |
num_classes
|
Number of classes |
required | |
ignore_index
|
Index to ignore in computation |
255
|
Returns:
Name | Type | Description |
---|---|---|
metrics |
Dictionary with IoU metrics |
Source code in embeddings_squeeze\utils\compression.py
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 |
|
initialization ¶
Codebook initialization utilities.
Functions¶
initialize_codebook_from_data(
vq_model,
backbone,
train_loader,
device,
max_samples=50000,
)
Initialize codebook using k-means clustering on real data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vq_model
|
VectorQuantizer model |
required | |
backbone
|
Segmentation backbone |
required | |
train_loader
|
Training data loader |
required | |
device
|
Device to run on |
required | |
max_samples
|
int
|
Maximum number of samples for k-means |
50000
|
Source code in embeddings_squeeze\utils\initialization.py
11 12 13 14 15 16 17 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 |
|
visualize ¶
Visualization script for comparing VQ vs baseline segmentation results.
Usage
python visualize.py --vq_checkpoint ./outputs/vq_squeeze/version_0/last.ckpt --baseline_checkpoint ./outputs/baseline_segmentation_baseline/version_0/last.ckpt
Functions¶
create_backbone ¶
create_backbone(config)
Create segmentation backbone based on config.
Source code in embeddings_squeeze\visualize.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
create_data_module ¶
create_data_module(config)
Create data module based on config.
Source code in embeddings_squeeze\visualize.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
|
load_models ¶
load_models(
vq_checkpoint_path,
baseline_checkpoint_path,
config,
device,
)
Load VQ and baseline models from checkpoints.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
vq_checkpoint_path
|
str
|
Path to VQ model checkpoint |
required |
baseline_checkpoint_path
|
str
|
Path to baseline model checkpoint |
required |
config
|
Configuration object |
required | |
device
|
Device to load models on |
required |
Returns:
Name | Type | Description |
---|---|---|
vq_model |
Loaded VQ model |
|
baseline_model |
Loaded baseline model |
Source code in embeddings_squeeze\visualize.py
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 |
|
main ¶
main()
Main visualization function.
Source code in embeddings_squeeze\visualize.py
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 |
|