model
This module provides the core LighterModule class that extends PyTorch Lightning's LightningModule. Users implement abstract step methods while the framework handles automatic dual logging.
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]
|
|