|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import jax |
| 4 | +import jax.numpy as jnp |
| 5 | +import numpy as np |
| 6 | +from jax import tree_util as jtu |
| 7 | +from mace_jax.data.utils import AtomicNumberTable as JaxAtomicNumberTable |
| 8 | + |
| 9 | +from equitrain.argparser import check_args_complete |
| 10 | +from equitrain.data.backend_jax import atoms_to_graphs, build_loader, make_apply_fn |
| 11 | + |
| 12 | + |
| 13 | +def _is_multi_device() -> bool: |
| 14 | + return jax.local_device_count() > 1 |
| 15 | + |
| 16 | + |
| 17 | +def _prepare_single_batch(graph): |
| 18 | + def _to_device_array(x): |
| 19 | + if x is None: |
| 20 | + return None |
| 21 | + return jnp.asarray(x) |
| 22 | + |
| 23 | + return jtu.tree_map(_to_device_array, graph, is_leaf=lambda leaf: leaf is None) |
| 24 | + |
| 25 | + |
| 26 | +def _stack_or_none(chunks): |
| 27 | + if not chunks: |
| 28 | + return None |
| 29 | + return np.concatenate(chunks, axis=0) |
| 30 | + |
| 31 | + |
| 32 | +def predict(args): |
| 33 | + check_args_complete(args, 'predict') |
| 34 | + backend = getattr(args, 'backend', 'torch') or 'torch' |
| 35 | + if backend != 'jax': |
| 36 | + raise NotImplementedError( |
| 37 | + f'JAX predict backend invoked with unsupported backend="{backend}".' |
| 38 | + ) |
| 39 | + |
| 40 | + if getattr(args, 'predict_file', None) is None: |
| 41 | + raise ValueError('--predict-file is a required argument for JAX prediction.') |
| 42 | + if getattr(args, 'model', None) is None: |
| 43 | + raise ValueError('--model is a required argument for JAX prediction.') |
| 44 | + |
| 45 | + if _is_multi_device(): |
| 46 | + raise NotImplementedError( |
| 47 | + 'JAX prediction currently supports single-device runs only. ' |
| 48 | + 'Set XLA flags to limit execution to one device.' |
| 49 | + ) |
| 50 | + |
| 51 | + bundle = _load_bundle(args.model, dtype=args.dtype) |
| 52 | + |
| 53 | + atomic_numbers = bundle.config.get('atomic_numbers') |
| 54 | + if not atomic_numbers: |
| 55 | + raise RuntimeError('Model configuration is missing `atomic_numbers`.') |
| 56 | + z_table = JaxAtomicNumberTable(atomic_numbers) |
| 57 | + |
| 58 | + r_max = ( |
| 59 | + float(args.r_max) |
| 60 | + if getattr(args, 'r_max', None) |
| 61 | + else float(bundle.config.get('r_max', 0.0)) |
| 62 | + ) |
| 63 | + if r_max <= 0.0: |
| 64 | + raise RuntimeError( |
| 65 | + 'Model configuration must define a positive `r_max`, or override via --r-max.' |
| 66 | + ) |
| 67 | + |
| 68 | + graphs = atoms_to_graphs( |
| 69 | + args.predict_file, |
| 70 | + r_max, |
| 71 | + z_table, |
| 72 | + niggli_reduce=getattr(args, 'niggli_reduce', False), |
| 73 | + ) |
| 74 | + loader = build_loader( |
| 75 | + graphs, |
| 76 | + batch_size=args.batch_size, |
| 77 | + shuffle=False, |
| 78 | + max_nodes=args.batch_max_nodes, |
| 79 | + max_edges=args.batch_max_edges, |
| 80 | + drop=getattr(args, 'batch_drop', False), |
| 81 | + ) |
| 82 | + if loader is None: |
| 83 | + raise RuntimeError('Prediction dataset is empty.') |
| 84 | + |
| 85 | + wrapper = _create_wrapper( |
| 86 | + bundle, |
| 87 | + compute_force=getattr(args, 'forces_weight', 0.0) > 0.0, |
| 88 | + compute_stress=getattr(args, 'stress_weight', 0.0) > 0.0, |
| 89 | + ) |
| 90 | + apply_fn = make_apply_fn(wrapper, num_species=len(z_table)) |
| 91 | + apply_fn = jax.jit(apply_fn) |
| 92 | + |
| 93 | + energies: list[np.ndarray] = [] |
| 94 | + forces: list[np.ndarray] = [] |
| 95 | + stresses: list[np.ndarray] = [] |
| 96 | + |
| 97 | + for batch in loader: |
| 98 | + micro_batches = batch if isinstance(batch, list) else [batch] |
| 99 | + for micro in micro_batches: |
| 100 | + prepared = _prepare_single_batch(micro) |
| 101 | + outputs = jax.device_get(apply_fn(bundle.params, prepared)) |
| 102 | + energy_pred = np.asarray(outputs['energy']) |
| 103 | + energies.append(energy_pred.reshape(-1)) |
| 104 | + |
| 105 | + if outputs.get('forces') is not None: |
| 106 | + forces.append(np.asarray(outputs['forces'])) |
| 107 | + if outputs.get('stress') is not None: |
| 108 | + stresses.append(np.asarray(outputs['stress'])) |
| 109 | + |
| 110 | + return _stack_or_none(energies), _stack_or_none(forces), _stack_or_none(stresses) |
| 111 | + |
| 112 | + |
| 113 | +def _load_bundle(model_path: str, dtype: str): |
| 114 | + from equitrain.backends.jax_utils import load_model_bundle as _load_model_bundle |
| 115 | + |
| 116 | + return _load_model_bundle(model_path, dtype=dtype) |
| 117 | + |
| 118 | + |
| 119 | +def _create_wrapper(bundle, *, compute_force: bool, compute_stress: bool): |
| 120 | + from equitrain.backends.jax_wrappers import MaceWrapper as JaxMaceWrapper |
| 121 | + |
| 122 | + return JaxMaceWrapper( |
| 123 | + module=bundle.module, |
| 124 | + config=bundle.config, |
| 125 | + compute_force=compute_force, |
| 126 | + compute_stress=compute_stress, |
| 127 | + ) |
| 128 | + |
| 129 | + |
| 130 | +__all__ = ['predict'] |
0 commit comments