Training API¶
Auto-generated from docstrings.
ecgen.training.runner¶
YAML-driven training runner shared by all families.
Config sections::
experiment: {name, seed, runs_root}
model: {name | target, params} # registry name, e.g. "vae"
data: {dataset: {name | target, params}, batch_size, num_workers,
pin_memory, split_params}
checkpoint: {monitor, mode, save_top_k, save_last, filename}
callbacks: [{name | target, params}, ...]
trainer: {...} # pl.Trainer kwargs
wandb: {enabled, project, entity, run_name, tags, notes, log_model}
resume: path/to/checkpoint.ckpt | null
Outputs go to <runs_root>/<name>/seed_<seed>/ (checkpoints/, samples/,
metrics/, tb/, config_resolved.yaml, metadata.json). String values
may use ${run_dir}, ${name} and ${seed}; a callback that takes a
save_dir and gets none writes to ${run_dir}/samples.
parse_value
¶
Parse an override value as YAML, reading exponent notation as a float.
apply_overrides
¶
Apply dotted.key=value overrides; values are parsed as YAML.
model.params.lr=1e-3, trainer.devices=[1], callbacks.0.params.num_samples=2.
Source code in src/ecgen/training/runner.py
resolve_config
¶
Validate sections, fill defaults, and interpolate ${...} variables.
Source code in src/ecgen/training/runner.py
check_compatibility
¶
Fail early if the model and dataset disagree on leads, length, or conditions.
Source code in src/ecgen/training/runner.py
train
¶
train(cfg: Mapping[str, Any], overrides: Sequence[str] = (), config_path: Optional[str | Path] = None) -> pl.Trainer
Train a model from a config dict; returns the fitted pl.Trainer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
Mapping[str, Any]
|
Parsed experiment config. |
required |
overrides
|
Sequence[str]
|
|
()
|
config_path
|
Optional[str | Path]
|
Source YAML, recorded in the run metadata. |
None
|
Source code in src/ecgen/training/runner.py
ecgen.cli¶
Command-line interface:
ecgen train <config.yaml> [key=value ...]ecgen sample <checkpoint> -n 16 -o out --format csv [--cond field=value ...]ecgen evaluate <samples.npy> <config.yaml>ecgen list
parse_cond
¶
["a=1,2,nan", "report=Sinus rhythm"] -> {"a": [1.0, 2.0, nan], "report": "Sinus rhythm"}.
Source code in src/ecgen/cli.py
ecgen.registry¶
Name → class registries used to build components from YAML.
A component spec is a mapping with either a registry name or an import
path target, plus optional params::
{"name": "vae", "params": {...}}
{"target": "my_pkg.models.MyModel", "params": {...}}
target lets user code outside the library plug in without registering.
Registry
¶
Bases: Generic[T]
A named collection of classes (or factories) of one kind.
Example::
FAMILIES = Registry("family")
@FAMILIES.register("vae")
class VAELightning(...): ...
FAMILIES.get("vae") # -> VAELightning
Source code in src/ecgen/registry.py
resolve
¶
Return the class named by a spec's name or target.
Source code in src/ecgen/registry.py
build
¶
Instantiate resolve(spec)(**spec['params'], **extra).
name_of
¶
Registered name of obj (or of its class), if any.
import_from_string
¶
Import package.module.attr and return attr.
Source code in src/ecgen/registry.py
load_builtins
¶
Import the built-in modules so their @register decorators run.
Source code in src/ecgen/registry.py
training.losses.common¶
Common loss functions shared across model types.
mse_loss
¶
ecgen.families.vae.losses¶
vae_loss
¶
vae_loss(recon: Tensor, x: Tensor, mean: Tensor, logvar: Tensor, kl_weight: float = 0.0001) -> tuple[Tensor, Tensor, Tensor]
VAE loss function
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recon
|
Tensor
|
Reconstructed signal |
required |
x
|
Tensor
|
Original signal |
required |
mean
|
Tensor
|
Latent mean |
required |
logvar
|
Tensor
|
Latent log variance |
required |
kl_weight
|
float
|
Weight for KL divergence term |
0.0001
|
Returns:
| Type | Description |
|---|---|
tuple[Tensor, Tensor, Tensor]
|
total_loss, recon_loss, kl_loss |
Source code in src/ecgen/families/vae/losses.py
gaussian_kl
¶
Summed KL(N(mean, var) || N(prior_mean, prior_var)).
Source code in src/ecgen/families/vae/losses.py
cvae_loss
¶
cvae_loss(recon: Tensor, x: Tensor, mean: Tensor, logvar: Tensor, prior_mean: Tensor, prior_logvar: Tensor, kl_weight: float = 0.0001, recon_mask: Tensor | None = None) -> tuple[Tensor, Tensor, Tensor]
Conditional VAE loss: MSE + kl_weight * KL to a (learned) prior.
The KL is normalized like :func:vae_loss (by B * C * T). With
recon_mask (1 = count), the MSE is averaged over masked entries only.
Source code in src/ecgen/families/vae/losses.py
ecgen.families.vqvae.losses¶
vqvae_loss
¶
VQ-VAE loss function.
Combines reconstruction loss with vector quantization loss. Unlike standard VAE, there's no KL divergence term since we use discrete codes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
recon
|
Tensor
|
Reconstructed signal [B, C, L] |
required |
x
|
Tensor
|
Original signal [B, C, L] |
required |
vq_loss
|
Tensor
|
Vector quantization loss (codebook + commitment) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
total_loss |
Tensor
|
Combined loss |
recon_loss |
Tensor
|
Reconstruction loss (MSE) |
vq_loss |
Tensor
|
Vector quantization loss |
Source code in src/ecgen/families/vqvae/losses.py
prior_loss
¶
Prior model loss function.
Cross-entropy loss for autoregressive prediction of discrete codes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Tensor
|
Predicted logits [B, num_embeddings, L] |
required |
targets
|
Tensor
|
Target indices [B, L] |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Cross-entropy loss |
Source code in src/ecgen/families/vqvae/losses.py
ecgen.families.gan.losses¶
Loss functions for ECG generation models.
wgan_discriminator_loss
¶
WGAN-GP discriminator loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_real
|
Tensor
|
Discriminator output on real samples |
required |
d_fake
|
Tensor
|
Discriminator output on fake samples |
required |
gp
|
Tensor
|
Gradient penalty |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Discriminator loss (minimize: fake - real + gp) |
Source code in src/ecgen/families/gan/losses.py
wgan_generator_loss
¶
WGAN-GP generator loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_fake
|
Tensor
|
Discriminator output on fake samples |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Generator loss (minimize: -d_fake) |
adversarial_loss
¶
Standard adversarial loss (BCE).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pred
|
Tensor
|
Discriminator predictions |
required |
target_is_real
|
bool
|
Whether targets should be real (1) or fake (0) |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Binary cross-entropy loss |
Source code in src/ecgen/families/gan/losses.py
least_squares_discriminator_loss
¶
Least squares GAN discriminator loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_real
|
Tensor
|
Discriminator output on real samples |
required |
d_fake
|
Tensor
|
Discriminator output on fake samples |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
LSGAN discriminator loss |
Source code in src/ecgen/families/gan/losses.py
least_squares_generator_loss
¶
Least squares GAN generator loss.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_fake
|
Tensor
|
Discriminator output on fake samples |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
LSGAN generator loss |
Source code in src/ecgen/families/gan/losses.py
ecgen.training.callbacks.checkpointing¶
Custom checkpoint callbacks (future implementation).
CustomCheckpointCallback
¶
Bases: Callback
Custom checkpoint callback for specialized checkpoint saving.
Future implementation for model-specific checkpointing strategies.
ecgen.training.callbacks.logging¶
Custom logging callbacks (future implementation).
CustomLoggingCallback
¶
Bases: Callback
Custom logging callback for specialized logging.
Future implementation for model-specific logging strategies.
ecgen.training.callbacks.visualization¶
Training callbacks for ECG generation models.
ECGVisualizationCallback
¶
Bases: Callback
Callback to visualize real vs generated ECG samples during training.
Source code in src/ecgen/training/callbacks/visualization.py
GeneratedSamplesCallback
¶
Bases: Callback
Callback to generate and save ECG samples periodically.
Source code in src/ecgen/training/callbacks/visualization.py
VAEVisualizationCallback
¶
Bases: Callback
Callback to visualize VAE reconstructions during training.
Saves comparison plots of real vs reconstructed ECG signals at specified intervals.
Source code in src/ecgen/training/callbacks/visualization.py
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 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 | |
training.metrics.reconstruction¶
training.metrics.generation¶
Generation quality metrics.
signal_to_noise_ratio
¶
Calculate signal-to-noise ratio.
Source code in training/metrics/generation.py
training.metrics.clinical¶
Metrics for ECG generation evaluation.
wasserstein_distance
¶
Compute Wasserstein distance estimate from discriminator outputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_real
|
Tensor
|
Discriminator output on real samples |
required |
d_fake
|
Tensor
|
Discriminator output on fake samples |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Wasserstein distance estimate (higher is better) |
Source code in training/metrics/clinical.py
gradient_penalty_loss
¶
gradient_penalty_loss(discriminator: Module, real_data: Tensor, fake_data: Tensor, lmbda: float = 10.0) -> Tensor
Compute WGAN-GP gradient penalty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
discriminator
|
Module
|
Discriminator network |
required |
real_data
|
Tensor
|
Real samples (B, C, L) |
required |
fake_data
|
Tensor
|
Fake samples (B, C, L) |
required |
lmbda
|
float
|
Gradient penalty coefficient |
10.0
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Gradient penalty loss |