Models
LUME-torch provides several model classes for different use cases, from simple custom models to advanced probabilistic models.
Overview
All LUME-torch models inherit from LUMETorch and provide:
- Consistent input/output interface using dictionaries
- Variable validation
- Configuration file support (YAML)
- Serialization/deserialization
Base Model
LUMETorch
The foundation for all LUME models.
lume_torch.base.LUMETorch
Bases: BaseModel, ABC
Abstract base class for models using lume-torch variables.
Inheriting classes must define the _evaluate method and variable names must be unique. Models built using this framework will be compatible with the lume-epics EPICS server and associated tools.
Attributes
input_variables : list of ScalarVariable List defining the input variables and their order. output_variables : list of ScalarVariable List defining the output variables and their order. input_validation_config : dict of str to ConfigEnum, optional Determines the behavior during input validation by specifying the validation config for each input variable: {var_name: value}. Value can be "warn", "error", or "none". output_validation_config : dict of str to ConfigEnum, optional Determines the behavior during output validation by specifying the validation config for each output variable: {var_name: value}. Value can be "warn", "error", or "none".
Methods
evaluate(input_dict, kwargs) Main evaluation function that validates inputs, calls _evaluate, and validates outputs. input_validation(input_dict) Validates input dictionary values against input variable specifications. output_validation(output_dict) Validates output dictionary values against output variable specifications. yaml(base_key="", file_prefix="", save_models=False, save_jit=False) Serializes the model to a YAML formatted string. dump(file, base_key="", save_models=True, save_jit=False) Saves model configuration and associated files to disk. from_file(filename) Class method to load a model from a YAML file. from_yaml(yaml_obj) Class method to load a model from a YAML string or file object. register_to_mlflow(artifact_path, kwargs) Registers the model to MLflow for experiment tracking.
Notes
Subclasses must implement the abstract method _evaluate(input_dict, **kwargs) which performs
the actual model computation.
Source code in lume_torch/base.py
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 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 | |
__init__(*args, **kwargs)
Initializes LUMETorch.
Parameters
args : dict, str, or os.PathLike Accepts a single argument which is the model configuration as dictionary, YAML or JSON formatted string or file path. *kwargs See class attributes.
Raises
ValueError If both YAML config and keyword arguments are provided, or if more than one positional argument is provided.
Source code in lume_torch/base.py
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 | |
evaluate(input_dict, **kwargs)
Main evaluation function, child classes must implement the _evaluate method.
Source code in lume_torch/base.py
491 492 493 494 495 496 | |
_evaluate(input_dict, **kwargs)
abstractmethod
Source code in lume_torch/base.py
498 499 500 | |
input_validation(input_dict)
Validates input dictionary values against input variable specifications.
Parameters
input_dict : dict of str to Any Dictionary of input variable names to values.
Returns
dict of str to Any Validated input dictionary.
Source code in lume_torch/base.py
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | |
output_validation(output_dict)
Validates output dictionary values against output variable specifications.
Parameters
output_dict : dict of str to Any Dictionary of output variable names to values.
Returns
dict of str to Any Validated output dictionary.
Source code in lume_torch/base.py
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 | |
dump(file, base_key='', save_models=True, save_jit=False)
Returns and optionally saves YAML formatted string defining the model.
Parameters
file : str or os.PathLike File path to which the YAML formatted string and corresponding files are saved. base_key : str, optional Base key for serialization. save_models : bool, optional Determines whether models are saved to file. save_jit : bool, optional Determines whether the model is saved as TorchScript.
Source code in lume_torch/base.py
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 | |
Creating Custom Models
To create a custom model, inherit from LUMETorch and implement _evaluate:
from lume_torch.base import LUMETorch
from lume_torch.variables import ScalarVariable
class MyModel(LUMETorch):
"""Custom model implementing specific logic."""
def _evaluate(self, input_dict):
"""Implement your model logic here.
Parameters
----------
input_dict : dict
Dictionary mapping input variable names to values
Returns
-------
dict
Dictionary mapping output variable names to values
"""
x = input_dict["x"]
y = input_dict["y"]
return {
"sum": x + y,
"product": x * y
}
# Create model with variables
model = MyModel(
input_variables=[
ScalarVariable(name="x", value_range=[0, 10]),
ScalarVariable(name="y", value_range=[0, 10]),
],
output_variables=[
ScalarVariable(name="sum"),
ScalarVariable(name="product"),
]
)
# Use the model
result = model({"x": 3.0, "y": 4.0})
PyTorch Models
TorchModel
Wrapper for PyTorch neural networks.
lume_torch.models.torch_model.TorchModel
Bases: LUMETorch
LUME-model class for torch models.
By default, the models are assumed to be fixed, so all gradient computation is deactivated and the model and transformers are put in evaluation mode.
Attributes
model : torch.nn.Module
The underlying torch model.
input_variables : list of ScalarVariable
List defining the input variables and their order.
output_variables : list of ScalarVariable
List defining the output variables and their order.
input_transformers : list of callable or modules
Transformer objects applied to the inputs before passing to the model.
output_transformers : list of callable or modules
Transformer objects applied to the outputs of the model.
output_format : {"tensor", "variable", "raw"}
Determines format of outputs.
device : torch.device or str
Device on which the model will be evaluated. Defaults to "cpu".
fixed_model : bool
If True, the model and transformers are put in evaluation mode and
all gradient computation is deactivated.
precision : {"double", "single"}
Precision of the model, either "double" or "single".
Methods
evaluate(input_dict, **kwargs) Evaluate the model on a dictionary of inputs and return outputs. input_validation(input_dict) Validate and normalize the input dictionary before evaluation. output_validation(output_dict) Validate the output dictionary after evaluation. random_input(n_samples=1) Generate random inputs consistent with the input variable ranges. random_evaluate(n_samples=1) Evaluate the model on random inputs. to(device) Move the model, transformers, and default values to a given device.
Source code in lume_torch/models/torch_model.py
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 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 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 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 | |
__init__(*args, **kwargs)
Initializes TorchModel.
Parameters
args : dict, str, or Path Accepts a single argument which is the model configuration as dictionary, YAML or JSON formatted string or file path. *kwargs See class attributes.
Source code in lume_torch/models/torch_model.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 | |
_evaluate(input_dict)
Evaluate the model on the given input dictionary.
Parameters
input_dict : dict of str to float or torch.Tensor Input dictionary on which to evaluate the model.
Returns
dict of str to float or torch.Tensor Dictionary of output variable names to values.
Source code in lume_torch/models/torch_model.py
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 | |
lume_torch.models.torch_model.InputDictModel
Bases: BaseModel
Pydantic model for input dictionary validation.
Attributes
input_dict : dict of str to torch.Tensor or float Input dictionary to validate.
Source code in lume_torch/models/utils.py
64 65 66 67 68 69 70 71 72 73 74 75 76 | |
Usage Example
from lume_torch.models.torch_model import TorchModel
from lume_torch.variables import ScalarVariable
import torch.nn as nn
# Create a neural network
network = nn.Sequential(
nn.Linear(2, 10),
nn.ReLU(),
nn.Linear(10, 1)
)
# Wrap in TorchModel
model = TorchModel(
model=network,
input_variables=[
ScalarVariable(name="x1", value_range=[-5, 5]),
ScalarVariable(name="x2", value_range=[-5, 5]),
],
output_variables=[
ScalarVariable(name="y"),
],
device="cpu",
precision="double"
)
# Evaluate
result = model({"x1": 1.0, "x2": 2.0})
TorchModule
PyTorch-compatible interface for LUME models.
lume_torch.models.torch_module.TorchModule
Bases: Module
Wrapper to allow a LUME TorchModel to be used like a torch.nn.Module.
As the base model within the TorchModel is assumed to be fixed during instantiation, so is the TorchModule.
Source code in lume_torch/models/torch_module.py
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 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 | |
__init__(*args, model=None, input_order=None, output_order=None)
Initializes TorchModule.
Parameters
*args : dict, str, or Path Accepts a single argument which is the model configuration as dictionary, YAML or JSON formatted string or file path. model : TorchModel, optional The TorchModel instance to wrap around. If config is None, this has to be defined. input_order : list of str, optional Input names in the order they are passed to the model. If None, the input order of the TorchModel is used. output_order : list of str, optional Output names in the order they are returned by the model. If None, the output order of the TorchModel is used.
Source code in lume_torch/models/torch_module.py
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 | |
forward(x)
Source code in lume_torch/models/torch_module.py
113 114 115 116 117 118 119 120 121 | |
Usage Example
from lume_torch.models.torch_module import TorchModule
import torch
# Wrap TorchModel in TorchModule
torch_module = TorchModule(model=model)
# Use like a PyTorch module
input_tensor = torch.tensor([[1.0, 2.0]])
output_tensor = torch_module(input_tensor)
# Integrate with PyTorch pipelines
optimizer = torch.optim.Adam(torch_module.parameters())
Probabilistic Models
For models that output distributions, see Probabilistic Models.
Serialization Functions
lume_torch.base.process_torch_module(module, base_key='', key='', file_prefix='', save_modules=True, save_jit=False)
Optionally saves the given torch module to file and returns the filename.
Parameters
module : torch.nn.Module The torch module to process. base_key : str, optional Base key at this stage of serialization. key : str, optional Key corresponding to the torch module. file_prefix : str or os.PathLike, optional Prefix for generated filenames. save_modules : bool, optional Determines whether torch modules are saved to file. save_jit : bool, optional Determines whether the model gets saved as TorchScript.
Returns
str Filename under which the torch module is (or would be) saved.
Source code in lume_torch/base.py
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 | |
lume_torch.base.model_kwargs_from_dict(config)
Processes model configuration and returns the corresponding keyword arguments for model constructor.
Parameters
config : dict Model configuration.
Returns
dict Configuration as keyword arguments for model constructor.
Source code in lume_torch/base.py
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | |
lume_torch.base.parse_config(config, model_fields=None)
Parses model configuration and returns keyword arguments for model constructor.
Parameters
config : dict, str, TextIOWrapper, or os.PathLike Model configuration as dictionary, YAML or JSON formatted string, file or file path. model_fields : dict, optional Fields expected by the model (required for replacing relative paths).
Returns
dict Configuration as keyword arguments for model constructor.
Source code in lume_torch/base.py
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 | |
lume_torch.base.recursive_serialize(v, base_key='', file_prefix='', save_models=True, save_jit=False)
Recursively performs custom serialization for the given object.
Parameters
v : dict of str to Any Object to serialize. base_key : str, optional Base key at this stage of serialization. file_prefix : str or os.PathLike, optional Prefix for generated filenames. save_models : bool, optional Determines whether models are saved to file. save_jit : bool, optional Determines whether the model is saved as TorchScript.
Returns
dict Serialized object.
Source code in lume_torch/base.py
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 | |
lume_torch.base.recursive_deserialize(v)
Recursively performs custom deserialization for the given object.
Parameters
v : dict Object to deserialize.
Returns
dict Deserialized object.
Source code in lume_torch/base.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |
lume_torch.base.json_dumps(v, *, base_key='', file_prefix='', save_models=True, save_jit=False)
Serializes variables before dumping with json.
Parameters
v : object Object to dump. base_key : str, optional Base key for serialization. file_prefix : str or os.PathLike, optional Prefix for generated filenames. save_models : bool, optional Determines whether models are saved to file. save_jit : bool, optional Determines whether the model is saved as TorchScript.
Returns
str JSON formatted string.
Source code in lume_torch/base.py
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 | |
lume_torch.base.json_loads(v)
Loads JSON formatted string and recursively deserializes the result.
Parameters
v : str JSON formatted string to load.
Returns
dict Deserialized object.
Source code in lume_torch/base.py
254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | |
Configuration Files
Models can be saved and loaded using YAML configuration files:
# Save model
model.dump("my_model.yml")
# Load model
loaded_model = MyModel("my_model.yml")
Example configuration file:
model_class: TorchModel
input_variables:
x1:
variable_class: ScalarVariable
default_value: 0.0
value_range: [-5.0, 5.0]
x2:
variable_class: ScalarVariable
default_value: 0.0
value_range: [-5.0, 5.0]
output_variables:
y:
variable_class: ScalarVariable
model: model.pt
device: cpu
precision: double
See Also
- Variables - Defining inputs and outputs
- Probabilistic Models - GP and ensemble models
- Examples - Example notebooks