hartmax 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
hartmax/__init__.py ADDED
@@ -0,0 +1,147 @@
1
+ """Small, lazy convenience API for HARTMAX.
2
+
3
+ Everything else lives in its named module, for example ``hartmax.axial``,
4
+ ``hartmax.units`` and ``hartmax.q2d``. Keeping the package root deliberately
5
+ small makes supported concepts discoverable and avoids importing JAX-heavy
6
+ solver modules until a symbol is used.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import os
13
+ from importlib import import_module
14
+
15
+ __all__ = [
16
+ "Problem",
17
+ "Solver",
18
+ "Output",
19
+ "solve",
20
+ "duct",
21
+ "channel",
22
+ "fringe_duct",
23
+ "configure",
24
+ "enable_x64",
25
+ "enable_compilation_cache",
26
+ ]
27
+
28
+
29
+ def enable_x64() -> None:
30
+ """Enable float64 arrays process-wide; call before constructing meshes or tracing.
31
+
32
+ This also sets JAX's ``jax_default_matmul_precision`` to ``'highest'`` when
33
+ that option is unset. ``'highest'`` is the same level as ``'float32'``.
34
+ Unset, JAX lets Ampere and newer GPUs run float32 matrix products and
35
+ convolutions in TensorFloat-32. On an RTX A4000, float32 contractions then
36
+ differed from float64 by 3e-4 relative. With the pinned precision the
37
+ difference was 2.6-6.1e-7. CPUs and float64 arrays are unaffected.
38
+
39
+ A value the user already chose is kept, whether set through
40
+ ``jax.config.update`` or the ``JAX_DEFAULT_MATMUL_PRECISION`` environment
41
+ variable. Constructing a ``ChannelProblem`` or a ``Q2DProblem`` applies the same rule.
42
+ """
43
+ from jax import config
44
+
45
+ config.update("jax_enable_x64", True)
46
+ _pin_matmul_precision()
47
+
48
+
49
+ def configure(dtype: str | None = None, gpu_gemm: bool = False) -> None:
50
+ """Set the process-wide choices that importing the package leaves alone, each announced once on ``hartmax``.
51
+
52
+ ``dtype="float64"`` enables float64 and pins the matmul precision (:func:`enable_x64`); ``"float32"``
53
+ keeps JAX as it is. ``gpu_gemm=True`` adds ``--xla_gpu_enable_triton_gemm=false`` to ``XLA_FLAGS`` (cuBLAS
54
+ instead of Triton GEMMs halves the GPU compile of a steady solve, 9.4 s to 4.2 s on an RTX A4000, at about
55
+ 10 % warm cost); XLA reads the flag when the GPU backend starts, so call it before the first array is
56
+ made, and a flag the user already set is kept. :func:`hartmax.solve` calls ``configure(dtype=solver.dtype)``.
57
+ """
58
+ from jax import config
59
+
60
+ if dtype not in (None, "float32", "float64"):
61
+ raise ValueError("dtype is 'float32' or 'float64'")
62
+ if dtype == "float64" and not config.jax_enable_x64:
63
+ enable_x64()
64
+ logging.getLogger("hartmax").info("float64 enabled")
65
+ if gpu_gemm and "xla_gpu_enable_triton_gemm" not in os.environ.get("XLA_FLAGS", ""):
66
+ os.environ["XLA_FLAGS"] = (
67
+ os.environ.get("XLA_FLAGS", "") + " --xla_gpu_enable_triton_gemm=false"
68
+ ).strip()
69
+ logging.getLogger("hartmax").info("XLA_FLAGS gained --xla_gpu_enable_triton_gemm=false")
70
+
71
+
72
+ def _pin_matmul_precision() -> str:
73
+ """Set ``jax_default_matmul_precision`` to ``'highest'`` if unset; return the value in effect.
74
+
75
+ The option is part of JAX's compilation key, so functions traced before the
76
+ pin are traced again afterwards rather than silently keeping TensorFloat-32.
77
+ """
78
+ from jax import config
79
+
80
+ if config.jax_default_matmul_precision is None:
81
+ config.update("jax_default_matmul_precision", "highest")
82
+ _enable_default_cache(config)
83
+ return config.jax_default_matmul_precision
84
+
85
+
86
+ def _enable_default_cache(config) -> None:
87
+ """Keep compiled solves on disk unless the user chose otherwise, so a new process starts warm.
88
+
89
+ Programs are shared across field values, so a new Hartmann number on the same
90
+ mesh reuses them (compile 4.4 s to 0.45 s on an A4000) at a 35-60 % warm cost.
91
+ Only compiles over one second are kept, in at most 2 GiB. ``HARTMAX_COMPILATION_CACHE=0``
92
+ disables it; a path in it sets the directory. It stays off on macOS with jaxlib
93
+ older than 0.10, which can crash reading back a large cached CPU program.
94
+ """
95
+ choice = os.environ.get("HARTMAX_COMPILATION_CACHE", "")
96
+ if choice == "0" or config.jax_compilation_cache_dir or _cache_read_unsafe():
97
+ return
98
+ from ._programs import enable_compilation_cache
99
+
100
+ enable_compilation_cache(choice or None, min_compile_time_secs=1.0, share_across_values=True)
101
+ config.update("jax_compilation_cache_max_size", 2**31)
102
+
103
+
104
+ def _cache_read_unsafe() -> bool:
105
+ import platform
106
+
107
+ import jaxlib
108
+
109
+ major, minor = (int(part) for part in jaxlib.__version__.split(".")[:2])
110
+ return platform.system() == "Darwin" and (major, minor) < (0, 10)
111
+
112
+
113
+ _EXPORTS = {
114
+ "enable_compilation_cache": ("hartmax._programs", "enable_compilation_cache"),
115
+ "solve": ("hartmax.solver", "solve"),
116
+ "Problem": ("hartmax.problem", "Problem"),
117
+ "channel": ("hartmax.problem", "channel"),
118
+ "duct": ("hartmax.problem", "duct"),
119
+ "fringe_duct": ("hartmax.problem", "fringe_duct"),
120
+ "Solver": ("hartmax.solver", "Solver"),
121
+ "Output": ("hartmax.output", "Output"),
122
+ }
123
+
124
+
125
+ def __getattr__(name: str):
126
+ """Load a root export, ``__version__`` or a submodule on first access."""
127
+
128
+ if name == "__version__":
129
+ from importlib.metadata import version
130
+
131
+ value = version("hartmax")
132
+ elif name in _EXPORTS:
133
+ module_name, attr_name = _EXPORTS[name]
134
+ value = getattr(import_module(module_name), attr_name)
135
+ else:
136
+ try:
137
+ value = import_module(f"hartmax.{name}")
138
+ except ModuleNotFoundError as exc:
139
+ raise AttributeError(f"module 'hartmax' has no attribute {name!r}") from exc
140
+ globals()[name] = value
141
+ return value
142
+
143
+
144
+ def __dir__() -> list[str]:
145
+ """Return module globals plus the lazy public surface for discovery."""
146
+
147
+ return sorted(set(globals()) | set(__all__))
hartmax/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ from __future__ import annotations
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())