Utils Callbacks#
callbacks
#
| CLASS | DESCRIPTION |
|---|---|
BaseCallback |
Abstract base class for PyTorch Lightning callbacks with enhanced functionality. |
TrainingCallback |
Training callback for logging and saving training metrics. |
ParameterAnnealingCallback |
PyTorch Lightning callback for annealing temperature during training. |
| FUNCTION | DESCRIPTION |
|---|---|
model_complexity_extractor |
Extract model complexity metrics. |
memory_usage_extractor |
Extract GPU memory usage. |
gradient_norm_extractor |
Extract gradient norms. |
kernel_params_extractor |
Universal kernel parameter extractor. |
eigenvalue_extractor |
Factory function to create eigenvalue extractor for parametric models. |
create_basic_training_callback |
Create a basic training callback with standard logging. |
create_training_callback |
Create a training callback with custom extractors. |
create_callback_from_config |
Create a callback instance from configuration dictionary. |
get_default_callbacks |
Get a default set of callbacks. |
create_callback_from_template |
Create callbacks from predefined templates. |
get_callback_config_schema |
Get configuration schema for all available callbacks. |
Classes#
BaseCallback(enabled: bool = True, log_every_n_epochs: int = 1)
#
Bases: Callback, ABC
Abstract base class for PyTorch Lightning callbacks with enhanced functionality.
Provides common functionality for all callbacks including configuration management, robust metric extraction, and device-aware computations.
| PARAMETER | DESCRIPTION |
|---|---|
enabled
|
Whether the callback is active during training.
TYPE:
|
log_every_n_epochs
|
Frequency of logging in epochs. Must be positive.
TYPE:
|
Notes
Subclasses must implement the abstract method get_callback_type() to
identify the callback type for configuration and factory systems.
| METHOD | DESCRIPTION |
|---|---|
get_callback_type |
Return the callback type identifier. |
should_log_this_epoch |
Check if logging should occur this epoch. |
safe_tensor_extract |
Safely extract scalar value from tensors or other types. |
from_config |
Create callback instance from configuration dictionary. |
to_config |
Export callback configuration to dictionary. |
validate_config |
Validate callback configuration. |
Source code in spectre/utils/callbacks.py
Functions#
get_callback_type() -> str
abstractmethod
#
Return the callback type identifier.
Used by factory methods and configuration systems to identify the specific callback class.
| RETURNS | DESCRIPTION |
|---|---|
str
|
Unique identifier for this callback type. |
Source code in spectre/utils/callbacks.py
should_log_this_epoch(trainer) -> bool
#
Check if logging should occur this epoch.
| PARAMETER | DESCRIPTION |
|---|---|
trainer
|
The PyTorch Lightning trainer instance.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if logging should occur this epoch. |
Source code in spectre/utils/callbacks.py
safe_tensor_extract(value: Any) -> float | None
#
Safely extract scalar value from tensors or other types.
Handles PyTorch tensors, NumPy arrays, and scalar values with proper error handling and device management.
| PARAMETER | DESCRIPTION |
|---|---|
value
|
Value to extract scalar from.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float | None
|
Extracted scalar value as float, or None if extraction fails. |
Source code in spectre/utils/callbacks.py
from_config(config: dict[str, Any]) -> BaseCallback
classmethod
#
Create callback instance from configuration dictionary.
This base implementation only handles common parameters. Subclasses should override this method to properly handle their specific parameters.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Configuration dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BaseCallback
|
Configured callback instance. |
Source code in spectre/utils/callbacks.py
to_config() -> dict[str, Any]
#
Export callback configuration to dictionary.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any]
|
Configuration dictionary. |
Source code in spectre/utils/callbacks.py
validate_config(config: dict[str, Any]) -> None
#
Validate callback configuration.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Configuration to validate.
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If configuration is invalid. |
Source code in spectre/utils/callbacks.py
TrainingCallback(save_path: str | Path | None = None, save_format: str = 'pickle', metric_prefix: str | None = None, custom_extractors: dict[str, Callable] | None = None, static_extractors: dict[str, Callable] | None = None, track_lr: bool = False, track_epoch_time: bool = False, max_history: int | None = None, **kwargs)
#
Bases: BaseCallback
Training callback for logging and saving training metrics.
Supports flexible metric collection, custom value extraction, and multiple save formats.
| PARAMETER | DESCRIPTION |
|---|---|
save_path
|
Path to save metrics file.
TYPE:
|
save_format
|
Format to save metrics ('pickle', 'json').
TYPE:
|
metric_prefix
|
Prefix to filter metrics by name.
TYPE:
|
custom_extractors
|
Custom functions to extract time-varying values from trainer/module, called every epoch.
TYPE:
|
static_extractors
|
Custom functions to extract constant values from trainer/module, called only once at training start (e.g., model_complexity_extractor).
TYPE:
|
track_lr
|
Whether to track learning rate.
TYPE:
|
track_epoch_time
|
Whether to track epoch duration.
TYPE:
|
max_history
|
Maximum number of epochs to keep in history. If None, keeps all history. Useful for long training runs to prevent unbounded memory growth.
TYPE:
|
Examples:
Track both static and dynamic metrics:
>>> from spectre.utils.callbacks import (
... TrainingCallback,
... model_complexity_extractor,
... gradient_norm_extractor,
... )
>>> callback = TrainingCallback(
... static_extractors={
... "model_complexity_extractor": model_complexity_extractor,
... },
... custom_extractors={"gradient_norm_extractor": gradient_norm_extractor},
... track_lr=True,
... )
>>> # After training, access metrics:
>>> callback.static_metrics # {'total_params': 1000, 'trainable_params': 900}
>>> callback.metrics["gradient_norm_extractor"] # [0.5, 0.3, 0.2, ...]
| METHOD | DESCRIPTION |
|---|---|
from_config |
Create TrainingCallback instance from configuration dictionary. |
on_train_start |
Log static metrics at the start of training. |
on_train_epoch_start |
Track epoch start time if requested. |
on_train_epoch_end |
Log metrics at the end of each training epoch. |
on_validation_epoch_end |
Log validation metrics. |
add_custom_extractor |
Add a custom metric extractor function. |
get_metric |
Get a specific metric by name. |
get_latest_metrics |
Get the most recent values for all metrics. |
clear_metrics |
Clear all stored metrics. |
save |
Save metrics to file. |
load |
Load metrics from file. |
Source code in spectre/utils/callbacks.py
Functions#
from_config(config: dict[str, Any]) -> TrainingCallback
classmethod
#
Create TrainingCallback instance from configuration dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Configuration dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
TrainingCallback
|
Configured callback instance. |
Source code in spectre/utils/callbacks.py
on_train_start(trainer, pl_module) -> None
#
Log static metrics at the start of training.
Source code in spectre/utils/callbacks.py
on_train_epoch_start(trainer, pl_module) -> None
#
on_train_epoch_end(trainer, pl_module) -> None
#
Log metrics at the end of each training epoch.
Source code in spectre/utils/callbacks.py
on_validation_epoch_end(trainer, pl_module) -> None
#
Log validation metrics.
Source code in spectre/utils/callbacks.py
add_custom_extractor(name: str, extractor_fn: Callable) -> None
#
Add a custom metric extractor function.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Name of the metric to log.
TYPE:
|
extractor_fn
|
Function that takes (trainer, pl_module) and returns a value.
TYPE:
|
Source code in spectre/utils/callbacks.py
get_metric(name: str) -> list[Any]
#
get_latest_metrics() -> dict[str, Any]
#
clear_metrics() -> None
#
save(filename: str | Path, format: str | None = None) -> None
#
Save metrics to file.
| PARAMETER | DESCRIPTION |
|---|---|
filename
|
Output file path.
TYPE:
|
format
|
Save format ("pickle" or "json"). If None, uses
TYPE:
|
Notes
Saves both time-varying metrics (in metrics) and static metrics
(in static_metrics) to the same file with separate keys.
For JSON format, tensors and arrays are automatically converted to Python native types (scalars or lists) for proper JSON serialization.
Format auto-detection rules:
.jsonextension → JSON format.pkl,.pickleextension → pickle format- Otherwise → uses
save_formatattribute (default: pickle)
Examples:
>>> callback = TrainingCallback()
>>> callback.save("metrics.json") # Auto-detects JSON format
>>> callback.save("metrics.pkl") # Auto-detects pickle format
>>> callback.save("data", format="json") # Explicit format
Source code in spectre/utils/callbacks.py
load(filename: str | Path, format: str | None = None) -> None
#
Load metrics from file.
| PARAMETER | DESCRIPTION |
|---|---|
filename
|
Input file path.
TYPE:
|
format
|
Load format ("pickle" or "json"). If None, auto-detects from
file extension or uses
TYPE:
|
Source code in spectre/utils/callbacks.py
ParameterAnnealingCallback(target_attr: str = 'temperature', start_temperature: float = 1.0, end_temperature: float = 0.01, total_epochs: int | None = None, schedule: str = 'cosine', warmup_epochs: int = 0, **kwargs)
#
Bases: BaseCallback
PyTorch Lightning callback for annealing temperature during training.
Gradually reduces temperature parameter in loss modules that support temperature-based weighting. This enables exploration-to-exploitation transition in soft-argmax computations.
Supports multiple annealing schedules:
- Linear: T(t) = T_start + (T_end - T_start) * (t / T_total)
- Exponential: T(t) = T_start * (T_end / T_start)^(t / T_total)
- Cosine: T(t) = T_end + 0.5 * (T_start - T_end) * (1 + cos(Ï€ * t / T_total))
| PARAMETER | DESCRIPTION |
|---|---|
target_attr
|
Name of the temperature attribute to update in the loss module. The loss module must have a settable attribute with this name.
TYPE:
|
start_temperature
|
Initial temperature value at epoch 0 (or after warmup). Higher values create broader/smoother distributions.
TYPE:
|
end_temperature
|
Final temperature value at the last epoch. Lower values create sharper/more focused distributions.
TYPE:
|
total_epochs
|
Total number of epochs for annealing schedule. If None, automatically
inferred from
TYPE:
|
schedule
|
Annealing schedule type:
TYPE:
|
warmup_epochs
|
Number of initial epochs to keep temperature constant at
TYPE:
|
Examples:
Linear annealing with AdaptiveEigenvalueLoss:
>>> from spectre.loss import AdaptiveEigenvalueLoss
>>> from spectre.utils.callbacks import ParameterAnnealingCallback
>>> from spectre.parametric import SpectralMap
>>> loss = AdaptiveEigenvalueLoss(temperature=1.0, min_states=2, max_states=10)
>>> callback = ParameterAnnealingCallback(
... start_temperature=1.0,
... end_temperature=0.05,
... total_epochs=100,
... schedule="linear",
... )
>>> sm = SpectralMap(loss_fn=loss, n_eigen=10)
>>> sm.fit(X, n_epochs=100, callbacks=[callback])
Cosine annealing with warmup for stable training:
>>> callback = ParameterAnnealingCallback(
... start_temperature=2.0,
... end_temperature=0.01,
... total_epochs=50,
... schedule="cosine",
... warmup_epochs=5,
... )
Multiple loss parameters can be annealed separately:
>>> temp_callback = ParameterAnnealingCallback(
... target_attr="temperature",
... start_temperature=1.0,
... end_temperature=0.05,
... )
>>> alpha_callback = ParameterAnnealingCallback(
... target_attr="adaptive_weight",
... start_temperature=0.3,
... end_temperature=1.0,
... )
>>> sm.fit(X, callbacks=[temp_callback, alpha_callback])
Notes
In soft-argmax with weights = softmax(values / temperature):
- High temperature (T >> 1): Uniform weighting across all values
- Low temperature (T -> 0): Winner-take-all, focuses on maximum value
- Annealing: Starts with exploration (broad), ends with exploitation (focused)
| METHOD | DESCRIPTION |
|---|---|
get_callback_type |
Return callback type identifier. |
from_config |
Create ParameterAnnealingCallback instance from configuration dictionary. |
on_train_start |
Check for temperature mismatch at training start. |
on_train_epoch_start |
Update temperature at the start of each training epoch. |
to_config |
Export callback configuration. |
Source code in spectre/utils/callbacks.py
Functions#
get_callback_type() -> str
#
from_config(config: dict[str, Any]) -> ParameterAnnealingCallback
classmethod
#
Create ParameterAnnealingCallback instance from configuration dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Configuration dictionary.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ParameterAnnealingCallback
|
Configured callback instance. |
Source code in spectre/utils/callbacks.py
on_train_start(trainer, pl_module) -> None
#
Check for temperature mismatch at training start.
Issues a warning if the callback's start_temperature differs from the
current value of the target attribute in the loss module.
Source code in spectre/utils/callbacks.py
on_train_epoch_start(trainer, pl_module) -> None
#
Update temperature at the start of each training epoch.
Computes new temperature based on current epoch, schedule, and warmup settings, then updates the target attribute in the loss module.
Source code in spectre/utils/callbacks.py
to_config() -> dict[str, Any]
#
Export callback configuration.
Source code in spectre/utils/callbacks.py
Functions#
model_complexity_extractor(trainer, pl_module) -> dict[str, int]
#
Extract model complexity metrics.
Source code in spectre/utils/callbacks.py
memory_usage_extractor(trainer, pl_module) -> dict[str, int]
#
Extract GPU memory usage.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, int]
|
Dictionary with memory usage in bytes. Returns zeros if CUDA is unavailable or if model is not on GPU. |
Source code in spectre/utils/callbacks.py
gradient_norm_extractor(trainer, pl_module) -> float
#
Extract gradient norms.
Source code in spectre/utils/callbacks.py
kernel_params_extractor(trainer, pl_module) -> dict
#
Universal kernel parameter extractor.
Works with any kernel type through unified get_param_summary() interface.
Automatically handles scalar vs vector/matrix parameters.
| PARAMETER | DESCRIPTION |
|---|---|
trainer
|
PyTorch Lightning trainer instance.
TYPE:
|
pl_module
|
Module containing
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict
|
Dictionary of kernel parameters and metadata:
|
Examples:
With GaussianKernel (scalar bandwidth):
>>> from spectre.kernel import GaussianKernel
>>> kernel = GaussianKernel(bw_method=torch.tensor(1.5))
>>> # Returns: {'bandwidth': 1.5, 'kernel_type': 'GaussianKernel',
>>> # 'kernel_learnable': False}
With TKernel (vector alpha, scalar beta):
>>> from spectre.kernel import TKernel
>>> kernel = TKernel(alpha=torch.ones(10, 1), beta=torch.tensor(2.0))
>>> # Returns: {'alpha_mean': 1.0, 'alpha_std': 0.0, 'alpha_min': 1.0,
>>> # 'alpha_max': 1.0, 'beta': 2.0, 'kernel_type': 'TKernel',
>>> # 'kernel_learnable': False}
Notes
- Requires
pl_moduleto havekernel_fnattribute - Kernel must implement
get_param_summary()method - Returns empty dict if kernel_fn not found
Source code in spectre/utils/callbacks.py
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 | |
eigenvalue_extractor(n_eigen: int | None = None) -> Callable
#
Factory function to create eigenvalue extractor for parametric models.
Creates an extractor that retrieves learned eigenvalues from models
that compute spectral decompositions during training. Supports
eigenvalues attributes.
| PARAMETER | DESCRIPTION |
|---|---|
n_eigen
|
Number of eigenvalues to extract. If None, extracts all available
eigenvalues. If specified, extracts only the first
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable
|
Extractor function with signature |
Examples:
Extract all eigenvalues:
>>> from spectre.parametric import SpectralMap
>>> from spectre.utils.callbacks import TrainingCallback, eigenvalue_extractor
>>> sm = SpectralMap(...)
>>> callback = TrainingCallback(
... custom_extractors={"eigenvalues": eigenvalue_extractor(n_eigen=10)},
... )
>>> # After training, metrics will contain all 10 eigenvalues:
>>> # {'eigenvalue_0': 0.95, 'eigenvalue_1': 0.82, ..., 'eigenvalue_9': 0.10}
Notes
- Returns empty dict if module has no eigenvalue attributes
- If
n_eigenexceeds available eigenvalues, returns all available
Source code in spectre/utils/callbacks.py
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 | |
kernel_metrics_extractor(metrics: list[str] | None = None, effective_rank_method: str = 'threshold', effective_rank_threshold: float = 0.99) -> Callable
#
Factory function to create kernel metrics extractor for parametric models.
Creates an extractor that computes kernel quality metrics from the stored loss context. Supports effective rank, kernel alignment, and reconstruction error metrics.
Requires parametric models to be initialized with store_loss_context=True.
| PARAMETER | DESCRIPTION |
|---|---|
metrics
|
List of metrics to compute. If None, defaults to ["effective_rank"]. Available metrics:
TYPE:
|
effective_rank_method
|
Method for computing effective rank. Options:
TYPE:
|
effective_rank_threshold
|
Threshold for cumulative eigenvalue sum (used with method="threshold").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable
|
Extractor function with signature |
Examples:
Extract effective rank with default settings:
>>> from spectre.parametric import SpectralMap
>>> from spectre.utils.callbacks import TrainingCallback, kernel_metrics_extractor
>>> sm = SpectralMap(..., store_loss_context=True)
>>> callback = TrainingCallback(
... custom_extractors={"kernel_metrics_extractor": kernel_metrics_extractor()},
... )
>>> # After training, metrics will contain: {'effective_rank': 15.2, ...}
Extract multiple kernel metrics:
>>> callback = TrainingCallback(
... custom_extractors={
... "kernel_metrics_extractor": kernel_metrics_extractor(
... metrics=["effective_rank", "kernel_trace", "kernel_frobenius"],
... effective_rank_method="entropy",
... )
... },
... )
Notes
- Returns empty dict if module has no
loss_contextattribute - Requires
store_loss_context=Truewhen initializing parametric models
Source code in spectre/utils/callbacks.py
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 | |
generic_metrics_extractor(metrics: dict[str, Callable] | list[Callable], parameter_mappings: dict[str, dict[str, str]] | None = None, default_params: dict[str, Any] | None = None, metric_params: dict[str, dict[str, Any]] | None = None) -> Callable
#
Factory function to create generic metric extractor from loss_context.
Automatically inspects metric function signatures and computes metrics only when all required parameters are available in the loss context. Supports flexible parameter mapping to handle naming mismatches between context keys and function parameters.
Requires parametric models to be initialized with store_loss_context=True.
| PARAMETER | DESCRIPTION |
|---|---|
metrics
|
Metric functions to compute. If dict, keys are metric names and values
are callable metric functions. If list, each element should be a callable
with a
TYPE:
|
parameter_mappings
|
Map context keys to function parameter names for each metric. Format: {metric_name: {context_key: param_name}} Example: { "kernel_alignment": {"K": "K1", "K_ref": "K2"}, "effective_rank": {"K": "K"} }
TYPE:
|
default_params
|
Default values for parameters across all metrics. These values are used when parameters are not found in context and have no default in signature.
TYPE:
|
metric_params
|
Per-metric default parameters that override
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable
|
Extractor function with signature |
Examples:
Simple usage with automatic parameter matching:
>>> from spectre.metrics.kernel import effective_rank, kernel_alignment
>>> extractor = generic_metrics_extractor(
... metrics=[effective_rank],
... )
Advanced usage with parameter mappings and defaults:
>>> extractor = generic_metrics_extractor(
... metrics={
... "eff_rank": effective_rank,
... "k_align": kernel_alignment,
... },
... parameter_mappings={
... "k_align": {"K": "K1"}, # Map context K to param K1
... },
... default_params={"K2": torch.eye(10)}, # Provide K2 for alignment
... metric_params={"eff_rank": {"method": "entropy"}},
... )
Using with TrainingCallback:
>>> from spectre.parametric import SpectralMap
>>> sm = SpectralMap(..., store_loss_context=True)
>>> callback = TrainingCallback(custom_extractors={"metrics": extractor})
>>> sm.fit(X, callbacks=[callback])
Notes
- Returns empty dict if module has no
loss_contextattribute - Requires
store_loss_context=Truewhen initializing parametric models - Metrics are computed independently; failure in one doesn't affect others
- Only metrics with all required parameters available are computed
Source code in spectre/utils/callbacks.py
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 | |
create_basic_training_callback(save_path: str = 'metrics.pkl') -> TrainingCallback
#
Create a basic training callback with standard logging.
create_training_callback(save_path: str = 'advanced_metrics.json') -> TrainingCallback
#
Create a training callback with custom extractors.
Source code in spectre/utils/callbacks.py
register_callback(name: str, callback_class: BaseCallback) -> None
#
Register a new callback type in the factory.
| PARAMETER | DESCRIPTION |
|---|---|
name
|
Unique identifier for the callback type.
TYPE:
|
callback_class
|
Callback class that inherits from BaseCallback.
TYPE:
|
Examples:
Register a custom callback:
>>> class MyCallback(BaseCallback):
... def get_callback_type(self) -> str:
... return "my_custom"
>>> register_callback("my_custom", MyCallback)
Source code in spectre/utils/callbacks.py
list_available_callbacks() -> list[str]
#
List all available callback types.
| RETURNS | DESCRIPTION |
|---|---|
list[str]
|
List of registered callback type names. |
create_callback_from_config(config: dict[str, Any]) -> BaseCallback
#
Create a callback instance from configuration dictionary.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Configuration dictionary containing 'type' field and callback parameters.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BaseCallback
|
Configured callback instance. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If callback type is not recognized or configuration is invalid. |
Examples:
Create a spectral gap callback:
>>> config = {"type": "spectral_gap", "n_eigen": 15, "log_every_n_epochs": 2}
>>> callback = create_callback_from_config(config)
Create metrics callback with custom extractors:
>>> config = {
... "type": "training_callback",
... "save_path": "metrics.json",
... "save_format": "json",
... "track_lr": True,
... }
>>> callback = create_callback_from_config(config)
Source code in spectre/utils/callbacks.py
get_default_callbacks(save_path: str | None = None) -> list[BaseCallback]
#
Get a default set of callbacks.
| PARAMETER | DESCRIPTION |
|---|---|
save_path
|
Path to save metrics. If provided, enables metrics saving.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[BaseCallback]
|
List of default callbacks (empty list if no save_path). |
Examples:
Get basic callbacks:
Get callbacks with metrics saving:
Source code in spectre/utils/callbacks.py
create_callback_from_template(template_name: str, **kwargs) -> BaseCallback | list[BaseCallback]
#
Create callbacks from predefined templates.
| PARAMETER | DESCRIPTION |
|---|---|
template_name
|
Name of the callback template.
TYPE:
|
**kwargs
|
Template-specific parameters.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
BaseCallback | list[BaseCallback]
|
Callback instance(s) from template. |
Examples:
Create from template:
>>> cb = create_callback_from_template(
... "training_callback",
... save_path="metrics.json",
... )
Source code in spectre/utils/callbacks.py
get_callback_config_schema() -> dict[str, dict[str, Any]]
#
Get configuration schema for all available callbacks.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, dict[str, Any]]
|
Schema dictionary with callback types as keys and parameter specifications as values. |
Source code in spectre/utils/callbacks.py
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 | |