Repository navigation
Little model improvements here and there. #565
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
6a0dd58
775c9e3
8f0871b
53b0945
e9db729
f79c510
11b9934
3bbec0a
2e2dc62
dbd6289
03820b9
e568f1d
cf66763
3658042
95bbacb
2279b8c
4ad3fa5
319e4e9
5ccc263
afc12e3
d716e5a
cfd10e7
8b54852
b69e48b
3bc671a
f39cef5
2585884
f0dd60e
7b8c3e1
ace5312
4d094aa
3539e1b
1957a72
039d0c1
e27653b
b318a6d
a2bce39
4664496
7ec04ef
8f5a4f7
5a4c144
ce32f96
5dba4ec
cadea8e
0e5ecb4
111a16f
d0b6235
4ff11ad
ddc66fa
071a3ff
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| import warnings | ||
| from typing import List, Literal, Optional, Union | ||
|
|
||
| from pydantic import ( | ||
|
|
@@ -6,6 +7,7 @@ | |
| NonNegativeFloat, | ||
| PositiveFloat, | ||
| PositiveInt, | ||
| model_validator, | ||
| ) | ||
|
|
||
|
|
||
|
|
@@ -15,7 +17,7 @@ class GaussianBasisConfig(BaseModel, extra="forbid"): | |
|
|
||
| Parameters | ||
| ---------- | ||
| n_basis : PositiveInt, default = 7 | ||
| n_basis : PositiveInt, default = 12 | ||
| Number of uncontracted basis functions. | ||
| r_min : NonNegativeFloat, default = 0.5 | ||
| Position of the first uncontracted basis function's mean. | ||
|
|
@@ -28,7 +30,7 @@ class GaussianBasisConfig(BaseModel, extra="forbid"): | |
| """ | ||
|
|
||
| name: Literal["gaussian"] = "gaussian" | ||
| n_basis: PositiveInt = 7 | ||
| n_basis: PositiveInt = 12 | ||
| r_min: NonNegativeFloat = 0.5 | ||
| r_max: PositiveFloat = 6.0 | ||
| spacing: Literal["linear", "exponential"] = "linear" | ||
|
|
@@ -40,14 +42,14 @@ class BesselBasisConfig(BaseModel, extra="forbid"): | |
|
|
||
| Parameters | ||
| ---------- | ||
| n_basis : PositiveInt, default = 16 | ||
| n_basis : PositiveInt, default = 12 | ||
| Number of uncontracted basis functions. | ||
| r_max : PositiveFloat, default = 5.0 | ||
| Cutoff radius of the descriptor. | ||
| """ | ||
|
|
||
| name: Literal["bessel"] = "bessel" | ||
| n_basis: PositiveInt = 16 | ||
| n_basis: PositiveInt = 12 | ||
| r_max: PositiveFloat = 5.0 | ||
|
|
||
|
|
||
|
|
@@ -110,8 +112,27 @@ class Correction(BaseModel, extra="forbid"): | |
|
|
||
|
|
||
| class ZBLRepulsion(Correction, extra="forbid"): | ||
| """ | ||
| .. deprecated:: | ||
| Use the NLH repulsion (``name: nlh``) instead: it is strictly more expressive (per element-pair | ||
| triple-exponential screening instead of one universal ZBL screening function). Kept so existing models | ||
| still load. | ||
| """ | ||
|
|
||
| name: Literal["zbl"] | ||
| r_max: NonNegativeFloat = 1.5 | ||
| # Coulomb constant e^2/(4*pi*eps0) = 14.4 eV*Ang (=1 in Hartree/Bohr). | ||
| initial_rep_scale: PositiveFloat = 14.4 | ||
|
|
||
| @model_validator(mode="after") | ||
| def _deprecated(self): | ||
| warnings.warn( | ||
| "The ZBL correction is deprecated: the NLH repulsion (name: nlh) is strictly more expressive. " | ||
| "Use it instead.", | ||
| FutureWarning, | ||
| stacklevel=2, | ||
| ) | ||
| return self | ||
|
|
||
|
|
||
| class ExponentialRepulsion(Correction, extra="forbid"): | ||
|
|
@@ -126,7 +147,31 @@ class LatentEwald(Correction, extra="forbid"): | |
| use_property: str = "charges" | ||
|
|
||
|
|
||
| EmpiricalCorrection = Union[ZBLRepulsion, ExponentialRepulsion, LatentEwald] | ||
| class NLHRepulsion(Correction, extra="forbid"): | ||
| name: Literal["nlh"] | ||
| r_max: PositiveFloat = 6.0 | ||
| # path to triple-exponential coeffs; None -> bundled apax/data/nlh_coeffs.dat | ||
| coeffs_file: Optional[str] = None | ||
|
|
||
| @model_validator(mode="before") | ||
| @classmethod | ||
| def _removed_fields(cls, values): | ||
| return _drop_removed(values, "poly_degree", 0, "the learnable NLH modulation was neutral") | ||
|
|
||
|
|
||
| class PairEnvelope(Correction, extra="forbid"): | ||
| """ | ||
| Attractive pair envelope -sum_pairs X_ij 0.5 (1 + cos(pi r / r_max)), X_ij = (X_i + X_j) / 2 with learnable | ||
| per-element amplitudes, least-squares initialised from the training data. With isolated-atom shifts it carries the bulk of the | ||
| cohesive energy, so the network learns a zero-centred residual. | ||
| """ | ||
|
|
||
| name: Literal["pair_envelope"] | ||
| r_max: PositiveFloat = 5.0 | ||
| trainable: bool = True | ||
|
|
||
|
|
||
| EmpiricalCorrection = Union[ZBLRepulsion, ExponentialRepulsion, LatentEwald, NLHRepulsion, PairEnvelope] | ||
|
|
||
|
|
||
| class PropertyHead(BaseModel, extra="forbid"): | ||
|
|
@@ -173,8 +218,17 @@ class BaseModelConfig(BaseModel, extra="forbid"): | |
|
|
||
| Parameters | ||
| ---------- | ||
| basis : BasisConfig, default = GaussianBasisConfig() | ||
| basis : BasisConfig, default = BesselBasisConfig() | ||
| Configuration for primitive basis functions. | ||
| radial_transform : Literal["identity", "covalent"], default = "identity" | ||
| Transform applied to interatomic distances before featurization. | ||
| `"identity"` featurizes the physical distance unchanged (original | ||
| behavior). `"covalent"` applies a per-element-pair tanh transform | ||
| centered at the sum of covalent radii, reallocating basis resolution | ||
| toward the bonding region. | ||
| covalent_r0_scale : PositiveFloat, default = 1.0 | ||
| Centre of the covalent transform as a multiple of the summed covalent radii; the descriptor is flat in r | ||
| below roughly this distance minus 0.5 Å. | ||
| nn : List[PositiveInt], default = [256, 256] | ||
| Number of hidden layers and units in those layers. | ||
| w_init : Literal["normal", "lecun"], default = "lecun" | ||
|
|
@@ -188,6 +242,13 @@ class BaseModelConfig(BaseModel, extra="forbid"): | |
| input. | ||
| use_ntk : bool, default = False | ||
| Whether or not to use NTK parametrization. | ||
| use_bias : bool, default = False | ||
| Whether the readout layers have biases. Without biases an atom with no | ||
| neighbours gets exactly its isolated-atom energy shift. | ||
| readout_activation : Literal["identity", "swish", "elu"], default = "elu" | ||
| Activation applied to the readout output before the per-element scale. | ||
| All options are 0 at 0. `"elu"` is unbounded above and keeps the scale | ||
| small when isolated-atom energy shifts are used. | ||
| ensemble : Optional[EnsembleConfig], default = None | ||
| What kind of model ensemble to use (optional). | ||
| property_heads : list[PropertyHead], default = [] | ||
|
|
@@ -207,12 +268,16 @@ class BaseModelConfig(BaseModel, extra="forbid"): | |
| """ | ||
|
|
||
| basis: BasisConfig = Field(BesselBasisConfig(name="bessel"), discriminator="name") | ||
| radial_transform: Literal["identity", "covalent"] = "identity" | ||
| covalent_r0_scale: PositiveFloat = 1.0 | ||
|
|
||
| nn: List[PositiveInt] = [256, 256] | ||
| w_init: Literal["normal", "lecun"] = "lecun" | ||
| b_init: Literal["normal", "zeros"] = "zeros" | ||
| activation_fn: str = "variance_preserving_swish" | ||
| use_ntk: bool = False | ||
| use_bias: bool = False | ||
| readout_activation: Literal["identity", "swish", "elu"] = "elu" | ||
|
|
||
| ensemble: Optional[EnsembleConfig] = None | ||
|
|
||
|
|
@@ -229,25 +294,82 @@ class BaseModelConfig(BaseModel, extra="forbid"): | |
| scale_shift_dtype: Literal["fp32", "fp64"] = "fp64" | ||
|
|
||
|
|
||
| def _drop_removed(values, key, off_value, what): | ||
| """Saved configs of older models still carry removed fields; accept them only if the feature was off.""" | ||
| if isinstance(values, dict) and key in values: | ||
| if values[key] not in (off_value, None): | ||
| raise ValueError( | ||
| f"`{key}` was removed ({what}); this config enables it and cannot be loaded." | ||
| ) | ||
| values = {k: v for k, v in values.items() if k != key} | ||
| return values | ||
|
|
||
|
|
||
| class GMNNConfig(BaseModelConfig, extra="forbid"): | ||
| """ | ||
| Configuration for the model. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| n_radial : PositiveInt, default = 5 | ||
| Number of contracted basis functions. | ||
| n_radial : PositiveInt, default = 12 | ||
| Number of contracted radial channels (used by the l=0 moment). | ||
| n_radial_tensor : Optional[PositiveInt], default = 4 | ||
| Radial channels for the l>0 moments, a learned linear combination of the | ||
| `n_radial` channels (applied per pair). None uses all `n_radial` channels. | ||
| n_contr : int, default = 8 | ||
| How many gaussian moment contractions to use. | ||
| emb_init : Optional[str], default = "uniform" | ||
| Initialization scheme for embedding layer weights. | ||
| Initialization of the dense species-pair table (`radial_function: dense`). | ||
| radial_function : Literal["dense", "factorized"], default = "factorized" | ||
| How the radial coefficients depend on the element pair. `"dense"` learns an | ||
| independent table per element pair. `"factorized"` uses a rank-`radial_rank` | ||
| CP factorization over per-element embeddings, so pairs share radial shapes | ||
| (much better on unseen or rare element pairs; can underfit on data-rich | ||
| sets with few elements). | ||
| radial_rank : PositiveInt, default = 8 | ||
| Rank of the factorized radial function. | ||
| radial_emb_jitter : NonNegativeFloat, default = 0.1 | ||
| Spread of the factorized embeddings at init around 1, i.e. how far apart | ||
| the element pairs' radial functions start. | ||
| """ | ||
|
|
||
| name: Literal["gmnn"] = "gmnn" | ||
|
|
||
| n_radial: PositiveInt = 5 | ||
| n_radial: PositiveInt = 12 | ||
| n_radial_tensor: Optional[PositiveInt] = 4 | ||
| packed_moments: bool = False | ||
| drop_contractions: List[int] = [] | ||
| n_contr: int = 8 | ||
| emb_init: Optional[str] = "uniform" | ||
| radial_function: Literal["dense", "factorized"] = "factorized" | ||
| radial_rank: PositiveInt = 8 | ||
|
Comment on lines
+344
to
+345
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win 🔎 Supported by static analysis🏁 Script executed: #!/bin/bash
rg -nP 'model_dump|save_config|config\.yaml' apax/train apax/config -C2Repository: apax-hub/apax Length of output: 2509 🏁 Script executed: set -eu
printf '%s\n' '--- current model config declarations and validator ---'
nl -ba apax/config/model_config.py | sed -n '240,335p'
printf '%s\n' '--- pre-change model config declarations ---'
git show 8643a655c4b5aa1b1e00cd5ee1b83b0ed9ddc8f5:apax/config/model_config.py | nl -ba | sed -n '220,315p'
printf '%s\n' '--- radial configuration consumers ---'
rg -n -F --glob '*.py' -e 'radial_function' -e 'radial_rank' -e 'n_radial' -e 'pair_emb_' -e 'pair_core' apax | head -240
printf '%s\n' '--- config loading and restore references ---'
rg -n -F --glob '*.py' -e 'yaml.safe_load' -e 'yaml.load' -e 'TrainConfig(' -e 'Config(' -e 'restore' -e 'checkpoint' apax/config apax/train apax | head -260
printf '%s\n' '--- relevant tests and fixtures ---'
rg -n -F --glob '*.{py,yaml,yml}' -e 'radial_rank' -e 'radial_function' -e 'n_radial' -e 'config.yaml' -e 'GMNNConfig' tests apax 2>/dev/null | head -260 || test "$?" -eq 1Repository: apax-hub/apax Length of output: 41409 🏁 Script executed: set -eu
printf '%s\n' '--- config parsing ---'
nl -ba apax/config/common.py | sed -n '1,55p'
printf '%s\n' '--- checkpoint restoration ---'
nl -ba apax/train/checkpoints.py | sed -n '108,145p'
printf '%s\n' '--- builder radial path ---'
nl -ba apax/nn/builder.py | sed -n '80,140p'
printf '%s\n' '--- builder descriptor construction ---'
nl -ba apax/nn/builder.py | sed -n '315,350p'
printf '%s\n' '--- radial basis parameter declarations ---'
nl -ba apax/layers/descriptor/basis_functions.py | sed -n '110,285p'
printf '%s\n' '--- pre-change builder and basis declarations ---'
git show 8643a655c4b5aa1b1e00cd5ee1b83b0ed9ddc8f5:apax/nn/builder.py | nl -ba | sed -n '80,135p'
git show 8643a655c4b5aa1b1e00cd5ee1b83b0ed9ddc8f5:apax/layers/descriptor/basis_functions.py | nl -ba | sed -n '110,220p'Repository: apax-hub/apax Length of output: 19908 Preserve the dense radial architecture for legacy configurations. A legacy GMNN configuration does not contain When both new radial fields are absent, select the legacy dense function and retain the old 🐛 Suggested fix def _removed_fields(cls, values):
values = _drop_removed(
values, "radial_residual", False, "the per-pair radial residual did nothing"
)
values = _drop_removed(
values, "radial_factor_mode", "cp", "only the CP factorization is kept"
)
+ if (
+ isinstance(values, dict)
+ and "radial_rank" not in values
+ and "radial_function" not in values
+ ):
+ values = {**values, "radial_function": "dense"}
+ values.setdefault("n_radial", 5)
if (
isinstance(values, dict)
and "radial_rank" in values
and values["radial_rank"] is None🤖 Prompt for AI Agents |
||
| radial_emb_jitter: NonNegativeFloat = 0.1 | ||
|
|
||
| @model_validator(mode="before") | ||
| @classmethod | ||
| def _removed_fields(cls, values): | ||
| values = _drop_removed( | ||
| values, "radial_residual", False, "the per-pair radial residual did nothing" | ||
| ) | ||
| values = _drop_removed( | ||
| values, "radial_factor_mode", "cp", "only the CP factorization is kept" | ||
| ) | ||
| if ( | ||
| isinstance(values, dict) | ||
| and "radial_rank" in values | ||
| and values["radial_rank"] is None | ||
| ): | ||
| # saved before `radial_function` existed: no rank meant the dense table | ||
| values = {k: v for k, v in values.items() if k != "radial_rank"} | ||
| values.setdefault("radial_function", "dense") | ||
| elif isinstance(values, dict) and "radial_rank" in values: | ||
| values.setdefault("radial_function", "factorized") | ||
| return _drop_removed( | ||
| values, | ||
| "traceless_moments", | ||
| False, | ||
| "traceless moments were accuracy-neutral and slower", | ||
| ) | ||
|
|
||
| def get_builder(self): | ||
| from apax.nn.builder import GMNNBuilder | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
The new readout defaults change behavior for existing models and consumers. The new defaults are bias-free readouts with an ELU output. Old configs that omit these keys silently change their predictions, and code that expects bias parameters fails.
apax/config/model_config.py#L240-L241: set the defaults touse_bias=Trueandreadout_activation="identity". Enable the new options explicitly in new configs.apax/nn/builder.py#L172-L173: make the.getfallbacks match the legacy defaults.apax/layers/readout.py#L28-L28: make the module defaults match the legacy defaults. If bias-free layers stay supported, update the BAL(gb, gw)unpacking to handle them.📍 Affects 3 files
apax/config/model_config.py#L240-L241(this comment)apax/nn/builder.py#L172-L173apax/layers/readout.py#L28-L28🤖 Prompt for AI Agents