Runtime, components, and databases¶
Physical constants¶
torch_flash.constants
¶
Runtime configuration¶
torch_flash.config
¶
Process-wide runtime configuration for native torch-flash models.
The configuration is intentionally read when model or data tensors are constructed, not inside thermodynamic kernels. Existing model instances are therefore unaffected by later configuration changes and hot-path calls do not pay for repeated policy lookups.
RuntimeConfig
dataclass
¶
RuntimeConfig(
device: device,
dtype: dtype,
num_threads: int,
num_interop_threads: int,
deterministic: bool,
deterministic_warn_only: bool,
)
Immutable snapshot of torch-flash's tensor and execution policy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
device
|
Device used by named model, component, standard-state, and characterization factories when no explicit device is supplied. |
required |
dtype
|
dtype
|
Floating-point dtype used by those factories. Float64 is the scientific default; float32 is available for explicit lower-precision studies. |
required |
num_threads
|
int
|
Current PyTorch CPU intra-operation thread count. |
required |
num_interop_threads
|
int
|
Current PyTorch CPU inter-operation thread count. |
required |
deterministic
|
bool
|
Whether PyTorch deterministic algorithms are enabled. |
required |
deterministic_warn_only
|
bool
|
Whether unavailable deterministic algorithms warn instead of raising. |
required |
accelerated
property
¶
Report whether the configured default device is an accelerator.
Returns:
| Type | Description |
|---|---|
bool
|
|
tensor_options
property
¶
Return configured tensor-factory keyword arguments.
Returns:
| Type | Description |
|---|---|
dict
|
Mapping containing |
tensor
¶
tensor(
data: Any,
*,
dtype: dtype | None = None,
device: device | str | None = None,
requires_grad: bool = False,
) -> Tensor
Construct a copied tensor using this runtime policy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
Any value accepted by :func: |
required |
dtype
|
dtype | None
|
Per-call overrides for configured defaults. |
None
|
device
|
dtype | None
|
Per-call overrides for configured defaults. |
None
|
requires_grad
|
bool
|
Whether autograd records operations on the new tensor. |
False
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Newly allocated tensor. |
Source code in src/torch_flash/config.py
as_tensor
¶
as_tensor(
data: Any,
*,
dtype: dtype | None = None,
device: device | str | None = None,
) -> Tensor
Convert data using this runtime policy without unnecessary copies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
Any value accepted by :func: |
required |
dtype
|
dtype | None
|
Per-call overrides for configured defaults. |
None
|
device
|
dtype | None
|
Per-call overrides for configured defaults. |
None
|
Returns:
| Type | Description |
|---|---|
Tensor
|
Converted tensor, sharing storage when PyTorch permits. |
Source code in src/torch_flash/config.py
get_config
¶
get_config() -> RuntimeConfig
Return a current immutable runtime-policy snapshot.
Returns:
| Type | Description |
|---|---|
RuntimeConfig
|
Configured device/dtype plus live PyTorch thread and deterministic settings. Mutating process-wide PyTorch settings outside torch-flash is reflected in the returned snapshot. |
Source code in src/torch_flash/config.py
configure
¶
configure(
*,
device: device | str | None = None,
dtype: dtype | None = None,
num_threads: int | None = None,
num_interop_threads: int | None = None,
deterministic: bool | None = None,
deterministic_warn_only: bool | None = None,
) -> RuntimeConfig
Set the process-wide torch-flash runtime policy before model creation.
device="auto" selects the first available CUDA, XPU, or MPS device
that supports the requested dtype, falling back to CPU. device="gpu"
performs the same search but raises if no accelerator supports the dtype.
The dtype becomes PyTorch's default floating dtype. The selected device is
applied only by torch-flash factories and :class:RuntimeConfig tensor
helpers; this function deliberately does not call
:func:torch.set_default_device, which adds overhead to every Python-level
PyTorch API call.
PyTorch thread counts and deterministic-algorithm flags are inherently
process-wide. In particular, num_interop_threads can be changed only
once and before inter-operation parallel work starts; PyTorch's failure is
reported with an actionable error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
device | str | None
|
Explicit PyTorch device, |
None
|
dtype
|
dtype | None
|
|
None
|
num_threads
|
int | None
|
Positive CPU intra-operation thread count. |
None
|
num_interop_threads
|
int | None
|
Positive CPU inter-operation thread count. PyTorch permits changing it only once before parallel work begins. |
None
|
deterministic
|
bool | None
|
Enable or disable PyTorch deterministic algorithms. |
None
|
deterministic_warn_only
|
bool | None
|
Warn instead of raising when a deterministic implementation is
unavailable. Requires |
None
|
Returns:
| Type | Description |
|---|---|
RuntimeConfig
|
New immutable runtime-policy snapshot. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a dtype, device type, thread count, or deterministic option is invalid. |
RuntimeError
|
If the requested device/dtype is unavailable or PyTorch can no longer change inter-operation threads. |
Source code in src/torch_flash/config.py
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 | |
resolve_tensor_options
¶
resolve_tensor_options(
dtype: dtype | None, device: device | str | None
) -> tuple[dtype, device | str]
Resolve optional tensor options against current runtime configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
dtype | None
|
Explicit options or |
required |
device
|
dtype | None
|
Explicit options or |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
Resolved dtype and device suitable for PyTorch tensor factories. |
Source code in src/torch_flash/config.py
Components¶
torch_flash.components
¶
Canonical component names and shared SI property databases.
DEFAULT_COMPONENT_DATABASE
module-attribute
¶
DEFAULT_COMPONENT_DATABASE = load_component_database()
Validated bundled component database used by default constructors.
COMPONENTS
module-attribute
¶
COMPONENTS: dict[str, Component] = {}
Canonical-name and alias lookup mapping for bundled component records.
Component
dataclass
¶
Component(
name: str,
critical_temperature: float,
critical_pressure: float,
acentric_factor: float | None,
molar_mass: float,
critical_volume: float | None = None,
aliases: tuple[str, ...] = (),
critical_density: float | None = None,
)
Shared pure-component properties in SI units.
acentric_factor may be unavailable for components whose bundled use is
restricted to a model-specific multiparameter equation. Such a record can be
resolved by name but cannot be used to construct a cubic EoS until the user
supplies a complete custom component database or :class:ComponentSet.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Canonical lowercase snake-case component identifier. |
critical_temperature |
float
|
Critical temperature in K. |
critical_pressure |
float
|
Critical pressure in Pa. |
acentric_factor |
float | None
|
Dimensionless acentric factor, or |
molar_mass |
float
|
Molar mass in kg/mol. |
critical_volume |
float | None
|
Critical molar volume in m3/mol, or |
aliases |
tuple[str, ...]
|
Accepted alternative names, normalized only at API lookup boundaries. |
critical_density |
float | None
|
Critical molar density in mol/m3, or |
ComponentDatabase
dataclass
¶
ComponentDatabase(
identifier: str,
revision: str,
components: tuple[Component, ...],
units: Mapping[str, str],
references: tuple[Mapping[str, str], ...] = (),
source: str = "<api>",
)
Validated immutable canonical component database.
Attributes:
| Name | Type | Description |
|---|---|---|
identifier |
str
|
Stable database identifier. |
revision |
str
|
Database revision string. |
components |
tuple[Component, ...]
|
Pure-component records in database order. |
units |
Mapping[str, str]
|
Read-only mapping of property names to declared SI units. |
references |
tuple[Mapping[str, str], ...]
|
Read-only source records applying to the database. |
source |
str
|
Bundled resource label, custom YAML path, or |
Raises:
| Type | Description |
|---|---|
ParameterDatabaseError
|
If identifiers, units, records, aliases, or required positive properties are invalid. |
names
property
¶
Return canonical component names in database order.
Returns:
| Type | Description |
|---|---|
tuple
|
Immutable sequence of canonical identifiers. |
lookup
¶
lookup(name: str) -> Component
Resolve a canonical name or alias.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name or alias; matching is case-insensitive and treats spaces and hyphens as underscores. |
required |
Returns:
| Type | Description |
|---|---|
Component
|
Matching immutable component record. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no component or alias matches. |
Source code in src/torch_flash/components.py
ComponentSet
dataclass
¶
ComponentSet(
names: tuple[str, ...],
critical_temperature: Tensor,
critical_pressure: Tensor,
acentric_factor: Tensor,
molar_mass: Tensor,
critical_volume: Tensor | None = None,
critical_density: Tensor | None = None,
)
Vectorized component constants used by native PyTorch models.
All tensor fields have shape (ncomponents,) and share a dtype/device.
Component order defines the final axis of every associated composition
tensor.
Attributes:
| Name | Type | Description |
|---|---|---|
names |
tuple[str, ...]
|
Canonical component names in tensor order. |
critical_temperature |
Tensor
|
Critical temperatures in K. |
critical_pressure |
Tensor
|
Critical pressures in Pa. |
acentric_factor |
Tensor
|
Dimensionless acentric factors. |
molar_mass |
Tensor
|
Molar masses in kg/mol. |
critical_volume |
Tensor | None
|
Critical molar volumes in m3/mol, or |
critical_density |
Tensor | None
|
Critical molar densities in mol/m3, or |
ncomponents
property
¶
Return the component-axis length.
Returns:
| Type | Description |
|---|---|
int
|
Number of entries in :attr: |
to
¶
to(
*,
dtype: dtype | None = None,
device: device | str | None = None,
) -> ComponentSet
Return a component set with all tensors converted together.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dtype
|
dtype | None
|
Target floating dtype. |
None
|
device
|
device | str | None
|
Target PyTorch device. |
None
|
Returns:
| Type | Description |
|---|---|
ComponentSet
|
New immutable record; the original is unchanged. |
Source code in src/torch_flash/components.py
load_component_database
¶
load_component_database(
source: str | Path | ComponentDatabase | None = None,
) -> ComponentDatabase
Load and validate a bundled, custom, or explicit component database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | ComponentDatabase | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
ComponentDatabase
|
Immutable validated database. Parsed files are cached by resolved path. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If a custom path does not exist. |
ParameterDatabaseError
|
If the YAML schema, unit declarations, or component records are invalid. |
Source code in src/torch_flash/components.py
clear_component_caches
¶
Clear cached bundled and custom component YAML documents.
Use this after intentionally modifying a custom database in a long-running
process. Existing :class:ComponentSet and model instances are unaffected.
Returns:
| Type | Description |
|---|---|
None
|
The next database load reparses its source. |
Source code in src/torch_flash/components.py
canonical_component_name
¶
canonical_component_name(
name: str,
*,
database: str | Path | ComponentDatabase | None = None,
strict: bool = True,
) -> str
Resolve a component name or alias to the canonical identifier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Canonical name or declared alias. |
required |
database
|
str | Path | ComponentDatabase | None
|
Bundled/custom database selection accepted by
:func: |
None
|
strict
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
str
|
Canonical database name or, in non-strict mode, normalized input. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
Source code in src/torch_flash/components.py
component
¶
component(
name: str,
*,
database: str | Path | ComponentDatabase | None = None,
) -> Component
Look up one pure-component record by canonical name or alias.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Canonical name or alias to resolve. |
required |
database
|
str | Path | ComponentDatabase | None
|
Bundled/custom database selection. |
None
|
Returns:
| Type | Description |
|---|---|
Component
|
Immutable record from the selected database. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If the component is absent from the selected database. |
Source code in src/torch_flash/components.py
component_set
¶
component_set(
names: Iterable[str],
*,
dtype: dtype | None = None,
device: device | str | None = None,
database: str | Path | ComponentDatabase | None = None,
) -> ComponentSet
Build vectorized cubic-EoS constants from a component database.
Omitted tensor options follow the process-wide :mod:torch_flash.config
policy. Explicit dtype or device arguments override that policy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
names
|
Iterable[str]
|
Nonempty iterable of canonical names or aliases. Order is preserved. |
required |
dtype
|
dtype | None
|
Tensor options. Omitted values use the configured runtime policy. |
None
|
device
|
dtype | None
|
Tensor options. Omitted values use the configured runtime policy. |
None
|
database
|
str | Path | ComponentDatabase | None
|
Bundled/custom database selection. |
None
|
Returns:
| Type | Description |
|---|---|
ComponentSet
|
Vectorized SI constants in the requested order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no components are requested. |
KeyError
|
If a name is unknown. |
ParameterDatabaseError
|
If a requested component lacks the acentric factor required by cubic EoS construction. |
Source code in src/torch_flash/components.py
Model parameter documents¶
torch_flash.database
¶
Versioned YAML parameter-database loading.
Bundled model parameter sets are immutable scientific inputs. YAML documents are parsed and validated once per process, while model constructors copy their values into independent PyTorch tensors with the requested dtype, device, and trainability.
ModelParameterSet
dataclass
¶
ModelParameterSet(
identifier: str,
model_kind: str,
model: str,
version: str,
parameters: ParameterDocument,
units: ParameterDocument = dict(),
references: tuple[ParameterDocument, ...] = (),
description: str = "",
source: str = "<api>",
)
Validated model parameter set independent of tensor dtype and device.
Parameters can be supplied directly through this dataclass, read from a
custom YAML path, or selected from the bundled database by identifier.
The stored mappings are recursively read-only. Use :meth:as_dict when a
mutable deep copy is needed.
Attributes:
| Name | Type | Description |
|---|---|---|
identifier |
str
|
Stable lowercase parameter-set identifier. |
model_kind |
str
|
Scientific domain such as |
model |
str
|
Model/form name declared by the document. |
version |
str
|
Parameter-set version or revision. |
parameters |
ParameterDocument
|
Recursively read-only numerical/scientific payload. |
units |
ParameterDocument
|
Recursively read-only units mapping. |
references |
tuple[ParameterDocument, ...]
|
Source records for equations, coefficients, or fits. |
description |
str
|
Human-readable parameter-set scope. |
source |
str
|
Bundled resource label, custom path, or |
from_document
classmethod
¶
from_document(
document: Mapping[str, Any], *, source: str = "<api>"
) -> ModelParameterSet
Validate a model-parameter YAML document represented as a mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
document
|
Mapping[str, Any]
|
Parsed YAML mapping following the torch-flash model-parameter schema. |
required |
source
|
str
|
Label used in diagnostics and stored provenance. |
'<api>'
|
Returns:
| Type | Description |
|---|---|
ModelParameterSet
|
Immutable validated parameter document. |
Raises:
| Type | Description |
|---|---|
ParameterDatabaseError
|
If required headers, identifiers, mappings, units, or references are invalid. |
Source code in src/torch_flash/database.py
as_dict
¶
Return a mutable deep copy of the numerical parameter payload.
Returns:
| Type | Description |
|---|---|
dict
|
Deeply mutable copy. Mutating it cannot alter the cached parameter set or any existing model tensors. |
Source code in src/torch_flash/database.py
load_model_parameters
¶
load_model_parameters(
source: ParameterSource,
) -> ModelParameterSet
Load a bundled identifier, custom YAML path, or explicit parameter set.
Parsed bundled and custom files are cached by identifier or resolved path.
Call :func:clear_parameter_caches after intentionally modifying a custom
file in a long-running process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
ParameterSource
|
Bundled identifier or alias, custom YAML path, or an explicit
:class: |
required |
Returns:
| Type | Description |
|---|---|
ModelParameterSet
|
Immutable validated parameter set. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If a string is neither a bundled identifier/alias nor a YAML path. |
FileNotFoundError
|
If a custom YAML path does not exist. |
ParameterDatabaseError
|
If the document does not satisfy the schema. |
Source code in src/torch_flash/database.py
available_parameter_sets
¶
Return bundled parameter-set identifiers, optionally filtered by kind.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_kind
|
str | None
|
Exact model-kind filter, for example |
None
|
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
Sorted immutable tuple of matching identifiers. An unknown kind yields an empty tuple. |
Source code in src/torch_flash/database.py
clear_parameter_caches
¶
Clear parsed model-parameter YAML caches.
Use this after intentionally modifying a custom file in a long-running process. Existing model instances and tensors are unaffected.
Returns:
| Type | Description |
|---|---|
None
|
The next parameter load reparses its source. |
Source code in src/torch_flash/database.py
Exceptions and warnings¶
torch_flash.exceptions
¶
Package-specific exceptions and warnings.
TorchFlashError
¶
Bases: Exception
Base class for torch-flash domain-specific errors.
Catch this type when an application wants to handle all package-defined calculation and parameter errors without intercepting unrelated Python exceptions.
InvalidStateError
¶
Bases: TorchFlashError, ValueError
Indicate that a thermodynamic state is outside a model's domain.
Typical causes include nonpositive temperature or pressure, inadmissible volume, and mechanically unstable response functions.
ConvergenceError
¶
Bases: TorchFlashError, RuntimeError
Indicate that an iterative thermodynamic calculation failed.
The originating API should include a physically meaningful residual or iteration context in the exception message.
ModelCapabilityError
¶
Bases: TorchFlashError, NotImplementedError
Indicate that a model or optional backend lacks a requested operation.
This is distinct from numerical non-convergence of an implemented capability.
ParameterDatabaseError
¶
Bases: TorchFlashError, ValueError
Indicate an invalid component or model parameter document.
Examples include schema, unit, model-identity, provenance, and coefficient consistency failures.
ConvergenceWarning
¶
Bases: RuntimeWarning
Warn that a returned iterative result did not meet its tolerance.
APIs emitting this warning also mark the associated result non-converged; callers must not silently treat it as a valid solution.
ExperimentalModelWarning
¶
Bases: UserWarning
Warn that an implemented model path has limited validation scope.
The warning concerns scientific maturity or automated phase discovery, not necessarily numerical failure at the requested state.