Index
Lighter is a framework for streamlining deep learning experiments with configuration files.
LighterDataModule
Bases: LightningDataModule
A lightweight wrapper for organizing dataloaders in configuration files.
This class exists purely as a convenience helper - it wraps pre-configured PyTorch DataLoaders so you can use Lighter's configuration system without having to write a custom LightningDataModule from scratch.
When to use LighterDataModule: - Simple datasets that don't need complex preprocessing - Quick experiments where you want to configure dataloaders in YAML - Cases where your data pipeline is straightforward
When to write a custom LightningDataModule: - Complex data preparation (downloading, extraction, processing) - Multi-process data setup with prepare_data() and setup() - Advanced preprocessing pipelines - Data that requires stage-specific transformations - Sharing reusable data modules across projects
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_dataloader
|
DataLoader | None
|
DataLoader for training (used in fit stage) |
None
|
val_dataloader
|
DataLoader | None
|
DataLoader for validation (used in fit and validate stages) |
None
|
test_dataloader
|
DataLoader | None
|
DataLoader for testing (used in test stage) |
None
|
predict_dataloader
|
DataLoader | None
|
DataLoader for predictions (used in predict stage) |
None
|
Example
# config.yaml
data:
_target_: lighter.LighterDataModule
train_dataloader:
_target_: torch.utils.data.DataLoader
batch_size: 32
shuffle: true
dataset:
_target_: torchvision.datasets.CIFAR10
root: ./data
train: true
transform:
_target_: torchvision.transforms.ToTensor
val_dataloader:
_target_: torch.utils.data.DataLoader
batch_size: 32
shuffle: false
dataset:
_target_: torchvision.datasets.CIFAR10
root: ./data
train: false
transform:
_target_: torchvision.transforms.ToTensor
model:
_target_: project.MyModel
network: ...
optimizer: ...
trainer:
_target_: pytorch_lightning.Trainer
max_epochs: 10
Note
This is just a thin wrapper around PyTorch Lightning's LightningDataModule. It doesn't add any special logic - it simply holds your dataloaders and returns them when Lightning asks for them.
If you need more control (prepare_data, setup, etc.), write a custom LightningDataModule instead.
Source code in src/lighter/data.py
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 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 | |
predict_dataloader()
test_dataloader()
train_dataloader()
LighterModule
Bases: LightningModule
Minimal base class for deep learning models in Lighter.
Users should: - Subclass and implement the step methods they need (training_step, validation_step, etc.) - Define their own batch processing, loss computation, metric updates - Configure data separately using the 'data:' config key
Framework provides: - Automatic dual logging of losses (step + epoch) - Automatic dual logging of metrics (step + epoch) - Optimizer configuration
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network
|
Module
|
Neural network model |
required |
criterion
|
Callable | None
|
Loss function (optional, user can compute loss manually in step) |
None
|
optimizer
|
Optimizer | None
|
Optimizer (required for training) |
None
|
scheduler
|
LRScheduler | None
|
Learning rate scheduler (optional) |
None
|
train_metrics
|
Metric | MetricCollection | None
|
Training metrics (optional, user calls them in step) |
None
|
val_metrics
|
Metric | MetricCollection | None
|
Validation metrics (optional) |
None
|
test_metrics
|
Metric | MetricCollection | None
|
Test metrics (optional) |
None
|
Example
class MyModel(LighterModule): def training_step(self, batch, batch_idx): x, y = batch pred = self(x)
# Option 1: Use self.criterion if provided
loss = self.criterion(pred, y) if self.criterion else F.cross_entropy(pred, y)
# User calls metrics themselves
if self.train_metrics:
self.train_metrics(pred, y)
return {"loss": loss, "pred": pred, "target": y}
def validation_step(self, batch, batch_idx):
x, y = batch
pred = self(x)
loss = self.criterion(pred, y) if self.criterion else F.cross_entropy(pred, y)
if self.val_metrics:
self.val_metrics(pred, y)
return {"loss": loss, "pred": pred, "target": y}
def test_step(self, batch, batch_idx):
x, y = batch
pred = self(x)
if self.test_metrics:
self.test_metrics(pred, y)
return {"pred": pred, "target": y}
def predict_step(self, batch, batch_idx):
x, y = batch
pred = self(x)
return pred
Source code in src/lighter/model.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 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 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 | |
mode
property
Current execution mode.
Returns:
| Type | Description |
|---|---|
str
|
"train", "val", "test", or "predict" |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If called outside trainer context |
_log_loss(loss)
Log loss with dual pattern (step + epoch).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
loss
|
Tensor | dict[str, Any] | None
|
Loss tensor or dict from step method. If dict, must have 'total' key (validated in _normalize_output). |
required |
Source code in src/lighter/model.py
_log_metrics()
Log metrics with dual pattern (step + epoch).
User already called metrics in their step method. Handles both single Metric and MetricCollection.
Source code in src/lighter/model.py
_log_optimizer_stats(batch_idx)
Log optimizer stats once per epoch in train mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_idx
|
int
|
Current batch index |
required |
Source code in src/lighter/model.py
_log_outputs(outputs, batch_idx)
Log all outputs from a step.
Override this method to customize logging behavior. Default: dual logging (step + epoch) for loss and metrics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outputs
|
dict[str, Any]
|
Dict from user's step method |
required |
batch_idx
|
int
|
Current batch index |
required |
Source code in src/lighter/model.py
_normalize_output(output)
Normalize step output to dict format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
Tensor | dict[str, Any]
|
Either: - torch.Tensor: Loss value (normalized to {"loss": tensor}) - dict: Must contain outputs. Can include: - "loss": torch.Tensor or dict with "total" key - "pred", "target", "input": Additional data for callbacks |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with normalized structure |
Raises:
| Type | Description |
|---|---|
TypeError
|
If output is neither Tensor nor dict |
ValueError
|
If loss dict is missing 'total' key |
Source code in src/lighter/model.py
_on_batch_end(outputs, batch_idx)
Common batch-end logic for all modes.
_prepare_metrics(metrics)
Validate metrics - must be Metric or MetricCollection.
Source code in src/lighter/model.py
configure_optimizers()
Configure optimizer and scheduler.
Source code in src/lighter/model.py
forward(*args, **kwargs)
Forward pass - simply delegates to self.network.
Override if you need custom forward logic.
on_test_batch_end(outputs, batch, batch_idx, dataloader_idx=0)
Framework hook - automatically logs test outputs.
on_train_batch_end(outputs, batch, batch_idx)
on_validation_batch_end(outputs, batch, batch_idx, dataloader_idx=0)
Framework hook - automatically logs validation outputs.
predict_step(batch, batch_idx)
Define prediction logic.
User responsibilities: - Extract data from batch - Call self(input) for forward pass - Return predictions in desired format
No automatic logging happens in predict mode. Return any format you need (tensor, dict, list, etc.).
Source code in src/lighter/model.py
test_step(batch, batch_idx)
Define test logic.
Loss is optional. Call self.test_metrics(pred, target) if configured.
Returns:
| Name | Type | Description |
|---|---|---|
Either |
Tensor | dict[str, Any]
|
|
Source code in src/lighter/model.py
training_step(batch, batch_idx)
Define training logic.
User responsibilities: - Extract data from batch - Call self(input) for forward pass - Compute loss - Call self.train_metrics(pred, target) if configured - Return loss tensor or dict with 'loss' key
Framework automatically logs loss and metrics.
Returns:
| Name | Type | Description |
|---|---|---|
Either |
Tensor | dict[str, Any]
|
|
Source code in src/lighter/model.py
validation_step(batch, batch_idx)
Define validation logic.
Similar to training_step but typically without gradients. Call self.val_metrics(pred, target) if configured.
Returns:
| Name | Type | Description |
|---|---|---|
Either |
Tensor | dict[str, Any]
|
|
Source code in src/lighter/model.py
Runner
Orchestrates training stage execution by coordinating helper classes.
Runner delegates responsibilities to specialized helper classes: - ProjectImporter: Auto-discovers and imports user project modules via lighter.py marker - ConfigLoader: Loads and validates configurations using Sparkwheel
Runner focuses on resolving and validating components (model, trainer, datamodule) and executing the requested training stage.
Source code in src/lighter/engine/runner.py
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 | |
_execute(stage, model, trainer, datamodule, **stage_kwargs)
Execute the training stage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage
|
Stage
|
Stage to execute (fit, validate, test, predict) |
required |
model
|
LightningModule
|
Resolved model |
required |
trainer
|
Trainer
|
Resolved trainer |
required |
datamodule
|
LightningDataModule | None
|
Resolved datamodule (None if model defines its own dataloaders) |
required |
**stage_kwargs
|
Any
|
Additional keyword arguments from CLI (e.g., ckpt_path, verbose) |
{}
|
Source code in src/lighter/engine/runner.py
_resolve_datamodule(config, model)
Resolve and validate datamodule from config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Config
|
Configuration object |
required |
model
|
LightningModule
|
Resolved model (checked for built-in dataloaders) |
required |
Returns:
| Type | Description |
|---|---|
LightningDataModule | None
|
LightningDataModule instance or None if model defines its own dataloaders |
Raises:
| Type | Description |
|---|---|
TypeError
|
If data key exists but is not a LightningDataModule |
Source code in src/lighter/engine/runner.py
_resolve_model(config)
Resolve and validate model from config.
Source code in src/lighter/engine/runner.py
_resolve_trainer(config)
Resolve and validate trainer from config.
Source code in src/lighter/engine/runner.py
_save_config(config, trainer, model)
Save configuration to multiple destinations.
Saves the configuration to: - Model (for checkpoint access via model.hparams) - Logger (for experiment tracking via log_hyperparams) - Log directory (as config.yaml file)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Config
|
Configuration object to save |
required |
trainer
|
Trainer
|
Trainer (uses trainer.logger and trainer.log_dir) |
required |
model
|
LightningModule
|
Model to save hyperparameters to |
required |
Source code in src/lighter/engine/runner.py
run(stage, inputs, **stage_kwargs)
Run a training stage with configuration inputs.
Orchestrates the complete training workflow: 1. Loads configuration via ConfigLoader (delegates to Sparkwheel for auto-detection) 2. Auto-discovers and imports project modules via ProjectImporter 3. Resolves and validates model, trainer, and datamodule components 4. Saves configuration (to log directory, logger, and model hyperparameters) 5. Executes the requested training stage
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage
|
Stage
|
Stage to run (fit, validate, test, predict) |
required |
inputs
|
list
|
List of config file paths, dicts, and/or overrides. Passed to ConfigLoader.load() which delegates to Sparkwheel for auto-detection: - Strings without '=' → file paths - Strings with '=' → overrides - Dicts → merged into config |
required |
**stage_kwargs
|
Any
|
Additional keyword arguments from CLI (e.g., ckpt_path, verbose) passed directly to the trainer stage method |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If config validation fails or required components are missing |
TypeError
|
If model or trainer are not the correct type |