InvDesTool 0.1.0a12__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.
Files changed (37) hide show
  1. invdestool/__init__.py +11 -0
  2. invdestool/__main__.py +3 -0
  3. invdestool/_io.py +49 -0
  4. invdestool/_match.py +87 -0
  5. invdestool/_vendor/__init__.py +1 -0
  6. invdestool/_vendor/benchmark_generation_v2.py +194 -0
  7. invdestool/_vendor/crystaldit.py +43 -0
  8. invdestool/_vendor/csp_classic_adapters_v1.py +146 -0
  9. invdestool/_vendor/csp_conditional_adapters_v1.py +125 -0
  10. invdestool/_vendor/csp_crystallm_inference_v2.py +18 -0
  11. invdestool/_vendor/csp_crystallm_postprocess_v2.py +30 -0
  12. invdestool/_vendor/csp_extension_adapters_v1.py +331 -0
  13. invdestool/_vendor/csp_extension_uni3dar.py +146 -0
  14. invdestool/_vendor/dao_guided.py +63 -0
  15. invdestool/_vendor/dng_multimodel_generate_v3_2026_10_21.py +191 -0
  16. invdestool/_vendor/mat2seq_recovered_v1.py +149 -0
  17. invdestool/_worker.py +279 -0
  18. invdestool/catalog.py +102 -0
  19. invdestool/cli.py +233 -0
  20. invdestool/client.py +353 -0
  21. invdestool/data/environments.json +277 -0
  22. invdestool/data/invdestool-demo.json +165 -0
  23. invdestool/data/model_guides.json +750 -0
  24. invdestool/data/models.json +5004 -0
  25. invdestool/datasets.py +90 -0
  26. invdestool/download.py +290 -0
  27. invdestool/environments.py +51 -0
  28. invdestool/errors.py +16 -0
  29. invdestool/experiment.py +166 -0
  30. invdestool/inputs.py +133 -0
  31. invdestool-0.1.0a12.dist-info/METADATA +214 -0
  32. invdestool-0.1.0a12.dist-info/RECORD +37 -0
  33. invdestool-0.1.0a12.dist-info/WHEEL +5 -0
  34. invdestool-0.1.0a12.dist-info/entry_points.txt +2 -0
  35. invdestool-0.1.0a12.dist-info/licenses/LICENSE +21 -0
  36. invdestool-0.1.0a12.dist-info/licenses/NOTICE +12 -0
  37. invdestool-0.1.0a12.dist-info/top_level.txt +1 -0
invdestool/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """Lightweight model discovery and isolated crystal generation. No import-time I/O."""
2
+ from .catalog import get_model, list_models
3
+ from .client import GenerationResult, Model, configure, configure_models_dir, generate, load_model, model_info
4
+ from .environments import configure_runtime
5
+ from .errors import InvDesToolError, DownloadError, ConfigurationError, InferenceError
6
+ from .experiment import ExperimentResult, run
7
+
8
+ __version__ = "0.1.0a12"
9
+ __all__ = ["ExperimentResult", "GenerationResult", "Model", "run", "configure", "configure_models_dir", "configure_runtime", "generate", "load_model",
10
+ "get_model", "list_models", "model_info", "InvDesToolError",
11
+ "DownloadError", "ConfigurationError", "InferenceError"]
invdestool/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
invdestool/_io.py ADDED
@@ -0,0 +1,49 @@
1
+ import hashlib
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ import tempfile
6
+
7
+
8
+ def sha256(path):
9
+ digest = hashlib.sha256()
10
+ with Path(path).open("rb") as stream:
11
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
12
+ digest.update(block)
13
+ return digest.hexdigest()
14
+
15
+
16
+ def write_json(path, value):
17
+ """Atomic JSON commit; no global or caller-directory changes."""
18
+ path = Path(path)
19
+ path.parent.mkdir(parents=True, exist_ok=True)
20
+ fd, temporary = tempfile.mkstemp(prefix="." + path.name, dir=path.parent)
21
+ try:
22
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
23
+ json.dump(value, stream, ensure_ascii=False, indent=2, allow_nan=False)
24
+ stream.write("\n")
25
+ stream.flush()
26
+ os.fsync(stream.fileno())
27
+ os.replace(temporary, path)
28
+ finally:
29
+ Path(temporary).unlink(missing_ok=True)
30
+
31
+
32
+ def cache_root(path=None):
33
+ if path is not None:
34
+ return Path(path).expanduser().absolute()
35
+ configured = os.environ.get("INVDESTOOL_CACHE")
36
+ if configured:
37
+ return Path(configured).expanduser().absolute()
38
+ return Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))).expanduser().absolute() / "invdestool"
39
+
40
+
41
+ def inside(root, relative):
42
+ root = Path(root).resolve()
43
+ relative = Path(relative)
44
+ if relative.is_absolute() or ".." in relative.parts:
45
+ raise ValueError(f"Expected a relative path inside {root}: {relative}")
46
+ path = root / relative
47
+ if not path.resolve().is_relative_to(root):
48
+ raise ValueError(f"Path escapes {root}: {relative}")
49
+ return path
invdestool/_match.py ADDED
@@ -0,0 +1,87 @@
1
+ """Evaluate CSP geometry in the selected interpreter with CUDA hidden."""
2
+ from collections import Counter
3
+ from contextlib import contextmanager
4
+ import json
5
+ import math
6
+ from pathlib import Path
7
+ import signal
8
+ import sys
9
+
10
+
11
+ MATCHER_SETTINGS = dict(ltol=0.3, stol=0.5, angle_tol=10, primitive_cell=True,
12
+ scale=True, attempt_supercell=False)
13
+ MATCH_TIMEOUT_SECONDS = 2
14
+
15
+
16
+ @contextmanager
17
+ def _deadline():
18
+ def expired(*args):
19
+ raise TimeoutError('Structure matching exceeded 2 seconds')
20
+
21
+ previous = signal.signal(signal.SIGALRM, expired)
22
+ signal.setitimer(signal.ITIMER_REAL, MATCH_TIMEOUT_SECONDS)
23
+ try:
24
+ yield
25
+ finally:
26
+ signal.setitimer(signal.ITIMER_REAL, 0)
27
+ signal.signal(signal.SIGALRM, previous)
28
+
29
+
30
+ def _geometry(value, structure_type):
31
+ return structure_type(value['lattice'], value['atomic_numbers'], value['frac_coords'])
32
+
33
+
34
+ def _reference(case, structure_type):
35
+ value = case['reference']
36
+ if 'cif' not in value:
37
+ return _geometry(value, structure_type)
38
+ structure = structure_type.from_str(value['cif'], fmt='cif', primitive=False)
39
+ if not structure.is_ordered:
40
+ raise ValueError('Reference CIF must describe an ordered crystal')
41
+ counts = {str(number): count for number, count in Counter(structure.atomic_numbers).items()}
42
+ if counts != case['composition']:
43
+ raise ValueError('Reference CIF cell composition does not match the input')
44
+ return structure_type(structure.lattice, structure.atomic_numbers, structure.frac_coords)
45
+
46
+
47
+ def compare(cases, attempts):
48
+ from pymatgen.analysis.structure_matcher import StructureMatcher
49
+ from pymatgen.core import Structure
50
+
51
+ matcher = StructureMatcher(**MATCHER_SETTINGS)
52
+ reference_cases = {case['id']: case for case in cases if 'reference' in case}
53
+ references = {}
54
+ errors = {}
55
+ results = {}
56
+ for attempt in attempts:
57
+ sample_id = attempt['sample_id']
58
+ if attempt['status'] != 'generated' or sample_id not in reference_cases:
59
+ continue
60
+ try:
61
+ if sample_id not in references and sample_id not in errors:
62
+ try:
63
+ references[sample_id] = _reference(reference_cases[sample_id], Structure)
64
+ except Exception as exc:
65
+ errors[sample_id] = str(exc)
66
+ if sample_id in errors:
67
+ raise ValueError(errors[sample_id])
68
+ with _deadline():
69
+ distance = matcher.get_rms_dist(references[sample_id], _geometry(attempt, Structure))
70
+ rmsd = float(distance[0]) if distance is not None else None
71
+ if rmsd is not None and not math.isfinite(rmsd):
72
+ raise ValueError('Structure matcher returned a nonfinite distance')
73
+ value = {'matched': rmsd is not None, 'normalized_rmsd': rmsd}
74
+ except Exception as exc:
75
+ value = {'matched': None, 'normalized_rmsd': None, 'error': str(exc)}
76
+ results[attempt['attempt_id']] = value
77
+ return results
78
+
79
+
80
+ def main(output):
81
+ dataset = json.loads((output/'dataset.json').read_text(encoding='utf-8'))
82
+ attempts = json.loads((output/'attempts.json').read_text(encoding='utf-8'))
83
+ print(json.dumps(compare(dataset['cases'], attempts), allow_nan=False))
84
+
85
+
86
+ if __name__ == '__main__':
87
+ main(Path(sys.argv[1]))
@@ -0,0 +1 @@
1
+ """Internal inference snapshots; imported only in isolated model processes."""
@@ -0,0 +1,194 @@
1
+ """Versioned raw generation for corrected CSP conditions and queued DNG.
2
+
3
+ Legacy numerical implementations are imported read-only. Every requested
4
+ attempt is retained; failures are never replaced by extra samples.
5
+ """
6
+ import argparse
7
+ from collections import Counter
8
+ import hashlib
9
+ import json
10
+ import math
11
+ import os
12
+ from pathlib import Path
13
+ import time
14
+
15
+ ROOT = Path(".") # Explicit paths are supplied by the private worker.
16
+ BASE = None # Supplied by the private worker.
17
+
18
+
19
+ def save(path,value):
20
+ def clean(x):
21
+ if isinstance(x,float) and not math.isfinite(x):return None
22
+ if isinstance(x,dict):return {str(k):clean(v) for k,v in x.items()}
23
+ if isinstance(x,(list,tuple)):return [clean(v) for v in x]
24
+ return x
25
+ tmp=path.with_name(path.name+f".{os.getpid()}.tmp");tmp.write_text(json.dumps(clean(value),allow_nan=False));tmp.replace(path)
26
+
27
+
28
+ def con_sample(model,runtime,jobs,params,seed,dng=False):
29
+ """Native conditional prior plus native decoder; no reference encoder."""
30
+ import random,types
31
+ import numpy as np
32
+ import torch
33
+ from types import SimpleNamespace
34
+ from pymatgen.core import Lattice
35
+ random.seed(seed);np.random.seed(seed);torch.manual_seed(seed)
36
+ ld=SimpleNamespace(n_step_each=params['n_step_each'],step_lr=params['step_lr'],min_sigma=params['min_sigma'],save_traj=False,disable_bar=True,use_one=True)
37
+ device=model.device;n=len(jobs);prior=runtime['prior'];strategy=params['strategy']
38
+ needed=[e.condition_name for e in prior.conditon_need]
39
+ values={};rng=np.random.default_rng(seed)
40
+ for key in needed:
41
+ supplied=[j.get('conditions',{}).get(key) for j in jobs]
42
+ if all(v is not None for v in supplied):values[key]=np.asarray(supplied,dtype=float)
43
+ elif strategy=='less' and key!='formation_energy_per_atom':
44
+ # This is the native less strategy: optional omitted properties
45
+ # come from the frozen author TRAIN prior, never target geometry.
46
+ index=rng.integers(0,len(runtime['reference']),size=n)
47
+ values[key]=runtime['reference'].iloc[index][key].to_numpy().copy()
48
+ else:raise ValueError(f"Missing required condition {key}")
49
+ context={k:torch.tensor(v,dtype=torch.float32,device=device) for k,v in values.items()}
50
+ original=prior.condition_emb_box
51
+ prior.condition_emb_box=types.MethodType(lambda self,inputs,randan_z,ld_kwargs=None:self.condition_model(inputs),prior)
52
+ try:z=prior.gen(context,torch.randn(n,model.hparams.latent_dim,device=device),ld)
53
+ finally:prior.condition_emb_box=original
54
+ energy=torch.tensor([[j['conditions']['formation_energy_per_atom']] for j in jobs],device=device,dtype=torch.float32).reshape(n)
55
+ embedding=model.condition_model({'formation_energy_per_atom':energy})
56
+ latent=model.z_condition(torch.cat((z,embedding),dim=1))
57
+ num_atoms=torch.tensor([j['num_atoms_input'] for j in jobs],device=device)
58
+ if dng:atom_types=None
59
+ else:atom_types=torch.tensor([int(z) for j in jobs for z,count in sorted(j['counts'].items(),key=lambda x:int(x[0])) for _ in range(int(count))],device=device)
60
+ result=model.langevin_dynamics(latent,ld,gt_num_atoms=num_atoms,gt_atom_types=atom_types)
61
+ rows=[];offset=0
62
+ for i,natoms in enumerate(result['num_atoms'].tolist()):
63
+ lengths=result['lengths'][i].detach().cpu().tolist();angles=result['angles'][i].detach().cpu().tolist()
64
+ row={'atomic_numbers':result['atom_types'][offset:offset+natoms].detach().cpu().tolist(),
65
+ 'frac_coords':result['frac_coords'][offset:offset+natoms].detach().cpu().tolist(),
66
+ 'lattice':Lattice.from_parameters(*lengths,*angles).matrix.tolist(),
67
+ 'provided_conditions':jobs[i]['conditions'],
68
+ 'effective_prior_conditions':{k:float(v[i]) for k,v in values.items()}}
69
+ offset+=natoms;rows.append(row)
70
+ return rows
71
+
72
+
73
+ def build(spec):
74
+ backend=spec['backend']
75
+ if backend=='mattergen':
76
+ import sys
77
+ from hydra.utils import instantiate
78
+ sys.path.insert(0,str(ROOT/spec['source']))
79
+ from mattergen.generator import CrystalGenerator
80
+ from mattergen.common.utils.data_classes import MatterGenCheckpointInfo
81
+ overrides=["++lightning_module.diffusion_module.model.element_mask_func={_target_:'mattergen.denoiser.mask_disallowed_elements',_partial_:True}"]
82
+ info=MatterGenCheckpointInfo(model_path=(ROOT/spec['checkpoint']).parents[1],load_epoch='last',config_overrides=overrides,strict_checkpoint_loading=True)
83
+ generator=CrystalGenerator(checkpoint_info=info,batch_size=spec['batch_size'],num_batches=1,
84
+ properties_to_condition_on={},diffusion_guidance_factor=0.,record_trajectories=False)
85
+ model=generator.model;model.eval()
86
+ cfg=generator.load_sampling_config(batch_size=spec['batch_size'],num_batches=1)
87
+ sampler=instantiate(cfg.sampler_partial)(pl_module=model)
88
+ return model,{'generator':generator,'sampler':sampler,'mode':'native empty-property unconditional generation'}
89
+ if backend in ['crystalflow','diffcsp','chemeleon','omatg']:
90
+ from dng_multimodel_generate_2026_10_20 import build as native_build
91
+ return native_build(backend,spec)
92
+ if backend=='diffcsp_carbon':
93
+ import torch,hydra
94
+ from omegaconf import OmegaConf
95
+ import sys
96
+ source=ROOT/spec['source'];sys.path.insert(0,str(source));os.environ['PROJECT_ROOT']=str(source)
97
+ cfg=OmegaConf.load(ROOT/spec['config'])
98
+ model=hydra.utils.instantiate(cfg.model,optim=cfg.optim,data=cfg.data,logging=cfg.logging,_recursive_=False)
99
+ ck=torch.load(ROOT/spec['checkpoint'],map_location='cpu',weights_only=False)
100
+ model.load_state_dict(ck['state_dict'],strict=True);model.eval().to('cuda:0')
101
+ assert not model.keep_coords and not model.keep_lattice
102
+ return model,{'strict_state':True,'fixed_element':'C','architecture':cfg.model._target_}
103
+ if backend in ['con_conditions','cond_pressure']:
104
+ from csp_conditional_adapters_v1 import build as native_build
105
+ model,runtime=native_build(spec['native_model'],'cuda:0')
106
+ model.encode=lambda *a,**k:(_ for _ in ()).throw(RuntimeError('Reference encoder forbidden'))
107
+ return model,runtime
108
+ if backend=='mat2seq_recovered':
109
+ from mat2seq_recovered_v1 import load
110
+ model,tok,details=load('cuda:0');return model,{'tokenizer':tok,'details':details}
111
+ if backend=='chemeleon_csp_alex':
112
+ import csp_extension_adapters_v1 as native
113
+ original=native.settings
114
+ override=original('chemeleon');override['checkpoint']=ROOT/spec['checkpoint']
115
+ native.settings=lambda name:override if name=='chemeleon' else original(name)
116
+ return native.build('chemeleon')
117
+ raise ValueError(f"Unimplemented backend: {backend}")
118
+
119
+
120
+ def sample(spec,model,runtime,jobs,seed):
121
+ import torch
122
+ backend=spec['backend']
123
+ if backend=='mattergen':
124
+ import numpy as np
125
+ from mattergen.common.data.dataset import NumAtomsCrystalDataset
126
+ from mattergen.common.data.collate import collate
127
+ dataset=NumAtomsCrystalDataset(num_atoms=np.asarray([j['num_atoms_input'] for j in jobs]))
128
+ conditioning=collate([dataset[i] for i in range(len(jobs))]).to('cuda:0')
129
+ assert (conditioning.atomic_numbers==-1).all() and torch.isnan(conditioning.pos).all() and torch.isnan(conditioning.cell).all()
130
+ _,mean=runtime['sampler'].sample(conditioning,mask=None)
131
+ rows=[]
132
+ for g in mean.to_data_list():
133
+ cell=g.cell.detach().cpu().reshape(3,3)
134
+ rows.append({'atomic_numbers':g.atomic_numbers.detach().cpu().reshape(-1).tolist(),
135
+ 'frac_coords':g.pos.detach().cpu().reshape(-1,3).tolist(),'lattice':cell.tolist(),
136
+ 'property_condition_mode':'unconditional via native empty-property interface'})
137
+ return rows
138
+ if backend in ['crystalflow','diffcsp','chemeleon','omatg']:
139
+ from dng_multimodel_generate_2026_10_20 import sample as native_sample
140
+ return native_sample(backend,model,[j['num_atoms_input'] for j in jobs],spec['sampling_parameters'])
141
+ if backend=='diffcsp_carbon':
142
+ from torch_geometric.data import Batch,Data
143
+ from dng_multimodel_generate_2026_10_20 import unpack
144
+ batch=Batch.from_data_list([Data(num_atoms=torch.tensor([j['num_atoms_input']]),num_nodes=j['num_atoms_input'],atom_types=torch.full((j['num_atoms_input'],),6,dtype=torch.long)) for j in jobs]).to('cuda:0')
145
+ generated,trajectory=model.sample(batch,**spec['sampling_parameters'])
146
+ rows=unpack(generated['atom_types'].detach().cpu(),generated['frac_coords'].detach().cpu(),generated['lattices'].detach().cpu(),generated['num_atoms'].detach().cpu());del trajectory
147
+ return rows
148
+ if backend=='con_conditions':return con_sample(model,runtime,jobs,spec['sampling_parameters'],seed,dng=spec['task']=='DNG')
149
+ if backend=='cond_pressure':
150
+ from types import SimpleNamespace
151
+ from pymatgen.core import Lattice
152
+ cfg=runtime['cfg'];scaler=dict(zip(cfg.data.prop,model.prop_scalers))['pressure']
153
+ numbers=[int(z) for j in jobs for z,n in sorted(j['counts'].items(),key=lambda x:int(x[0])) for _ in range(int(n))]
154
+ atom_types=torch.tensor(numbers,device=model.device);counts=torch.tensor([j['num_atoms_input'] for j in jobs],device=model.device)
155
+ physical=torch.tensor([[j['conditions']['pressure_GPa']] for j in jobs],dtype=torch.float32,device=model.device)
156
+ pressure=(physical-float(scaler.means.item()))/float(scaler.stds.item())
157
+ conditions={'composition':(atom_types,counts),'pressure':pressure}
158
+ z=torch.randn(len(jobs),model.hparams.latent_dim,device=model.device)
159
+ latent=model.zgivenc(z,model.multiemb(conditions));ld=SimpleNamespace(n_step_each=spec['sampling_parameters']['n_step_each'],step_lr=spec['sampling_parameters']['step_lr'],min_sigma=spec['sampling_parameters']['min_sigma'],save_traj=False,disable_bar=True,use_one=True)
160
+ result=model.langevin_dynamics(latent,ld,counts,atom_types);rows=[];offset=0
161
+ for i,n in enumerate(counts.tolist()):
162
+ rows.append({'atomic_numbers':result['atom_types'][offset:offset+n].detach().cpu().tolist(),'frac_coords':result['frac_coords'][offset:offset+n].detach().cpu().tolist(),'lattice':Lattice.from_parameters(*result['lengths'][i].detach().cpu().tolist(),*result['angles'][i].detach().cpu().tolist()).matrix.tolist(),'provided_conditions':jobs[i]['conditions'],'normalized_pressure':float(pressure[i].item())});offset+=n
163
+ return rows
164
+ if backend=='mat2seq_recovered':
165
+ from mat2seq_recovered_v1 import prompt_for,decode
166
+ tok=runtime['tokenizer'];rows=[]
167
+ start=0
168
+ while start<len(jobs):
169
+ end_group=start+1
170
+ while end_group<len(jobs) and jobs[end_group]['counts']==jobs[start]['counts']:end_group+=1
171
+ group=jobs[start:end_group];ids,prefix,_=prompt_for(group[0]['counts'],tok)
172
+ x=torch.tensor([ids],device='cuda:0').repeat(len(group),1)
173
+ with torch.autocast('cuda',dtype=torch.bfloat16):y,ends=model.generate(x,spec['sampling_parameters']['max_new_tokens'],temperature=spec['sampling_parameters']['temperature'],top_k=spec['sampling_parameters']['top_k'],num_gens=len(group))
174
+ for slot,job in enumerate(group):
175
+ end=int(ends[slot]);tokens=y[slot,:end if end>0 else y.size(1)].tolist();text=tok.decode(tokens)
176
+ row={'native_text':text,'native_token_ids':tokens,'terminated':end>0}
177
+ try:
178
+ _,info=decode(text,job['counts'],prefix);row.update(info)
179
+ if end<=0:row.update(status='conversion_failed',error='No normal termination')
180
+ elif not info['composition_preserved']:row.update(status='conversion_failed',error='Stoichiometry changed')
181
+ except Exception as e:row.update(status='conversion_failed',error_type=type(e).__name__,error=str(e))
182
+ rows.append(row)
183
+ start=end_group
184
+ return rows
185
+ if backend=='chemeleon_csp_alex':
186
+ from csp_extension_adapters_v1 import sample as native_sample
187
+ selected=[]
188
+ for j in jobs:
189
+ z=[int(z) for z,n in sorted(j['counts'].items(),key=lambda x:int(x[0])) for _ in range(int(n))]
190
+ selected.append(dict(j,atomic_numbers_input=z))
191
+ return native_sample('chemeleon',model,runtime,selected,seed)[0]
192
+ raise ValueError(backend)
193
+
194
+
@@ -0,0 +1,43 @@
1
+ """CrystalDiT MP20 adapter. The worker owns RNG, CUDA, and run bookkeeping."""
2
+ from pathlib import Path
3
+ import sys
4
+
5
+
6
+ def build(request):
7
+ import torch
8
+
9
+ card = request['model']
10
+ checkpoint = Path(request['model_path']) / card['checkpoint']
11
+ sys.path.insert(0, request['source_path'])
12
+ import generate_crystals as author
13
+
14
+ fixed = card['fixed_parameters']
15
+ model, _ = author.load_model(str(checkpoint), fixed['max_atoms'], torch.device('cuda:0'),
16
+ fixed['hidden_size'], fixed['depth'], fixed['num_heads'])
17
+ return model, author, ['Native CrystalDiT MP20 generation and per-slot decoding']
18
+
19
+
20
+ def sample(model, author, count, fixed):
21
+ import torch
22
+
23
+ diffusion = author.CrystalGaussianDiffusion(timesteps=fixed['timesteps'], beta_schedule=fixed['beta_schedule'])
24
+ lattice, atoms = diffusion.p_sample_loop(model, batch_size=count, max_atoms=fixed['max_atoms'],
25
+ device=torch.device('cuda:0'), progress=False)
26
+ lattice, atoms = lattice.detach().cpu(), atoms.detach().cpu()
27
+ if tuple(lattice.shape) != (count, 3, 3) or tuple(atoms.shape) != (count, fixed['max_atoms'], 5):
28
+ raise RuntimeError('Unexpected native CrystalDiT batch shape')
29
+ rows = []
30
+ for slot in range(count):
31
+ try:
32
+ structures = author.convert_to_structure(lattice[slot:slot+1], atoms[slot:slot+1],
33
+ max_length=fixed['max_length'],
34
+ filter_rare_gases=fixed['filter_rare_gases'])
35
+ if len(structures) != 1:
36
+ raise ValueError('Native decoder did not return a structure for this slot')
37
+ structure = structures[0]
38
+ rows.append(dict(atomic_numbers=[int(site.specie.Z) for site in structure],
39
+ frac_coords=structure.frac_coords.tolist(), lattice=structure.lattice.matrix.tolist(),
40
+ num_atoms=len(structure)))
41
+ except Exception as exc:
42
+ rows.append(dict(status='conversion_failed', error_type=type(exc).__name__, error=str(exc)))
43
+ return rows, {'native_lattice_vectors': lattice, 'native_atom_features': atoms}
@@ -0,0 +1,146 @@
1
+ """Composition-only author samplers; checkpoint schedules are authoritative."""
2
+ import ast
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ ROOT = Path(".") # Explicit paths are supplied by the private worker.
8
+
9
+
10
+ def paths(name):
11
+ raise RuntimeError("Explicit model paths must be configured by the private worker")
12
+
13
+
14
+ def build(name, checkpoint_path, weights):
15
+ import torch
16
+ source, _, _, _ = paths(name)
17
+ os.environ['PROJECT_ROOT'] = str(source)
18
+ sys.path.insert(0, str(source))
19
+ checkpoint = torch.load(checkpoint_path, map_location='cpu', weights_only=False)
20
+ notes = []
21
+ if name.startswith('crystalite'):
22
+ from src.crystalite import CrystaliteModel
23
+ from src.models.type_encoding_state import resolve_type_encoding
24
+ # Use the exact author's constructor without importing its DNG/MLIP eval stack.
25
+ tree = ast.parse((source / 'src/eval_crystalite_ckpt.py').read_text())
26
+ fn = next(n for n in tree.body if isinstance(n, ast.FunctionDef)
27
+ and n.name == '_build_model_from_ckpt')
28
+ ns = dict(CrystaliteModel=CrystaliteModel, torch=torch, VZ=94, Any=object)
29
+ exec(compile(ast.Module(body=[fn], type_ignores=[]), str(source / 'src/eval_crystalite_ckpt.py'), 'exec'), ns)
30
+ model, cfg = ns['_build_model_from_ckpt'](ckpt=checkpoint, device=torch.device('cuda:0'))
31
+ ema = checkpoint['ema_state_dict']
32
+ names = {n for n, _ in model.named_parameters()}
33
+ assert names == set(ema), 'Incomplete EMA parameters'
34
+ with torch.no_grad():
35
+ for n, p in model.named_parameters():
36
+ assert p.shape == ema[n].shape
37
+ p.copy_(ema[n].to(device=p.device, dtype=p.dtype))
38
+ enc = resolve_type_encoding(checkpoint, vz=94)
39
+ assert enc.name == 'atomic_number'
40
+ notes.append('Exact author model constructor; complete EMA; no DNG or MLIP evaluator imported')
41
+ return model, dict(cfg=cfg, encoding=enc), notes
42
+ import hydra
43
+ from omegaconf import OmegaConf
44
+ cfg = OmegaConf.load(weights / 'hparams.yaml')
45
+ if name.startswith('crysbfn'):
46
+ import types
47
+ # Author data_utils also contains an unrelated DNG evaluator with heavy
48
+ # matminer/SMACT imports. Load its unchanged geometry utilities without
49
+ # that isolated evaluator block; none of those names is used by sampling.
50
+ module_name = 'crysbfn.common.data_utils'
51
+ util_path = source / 'crysbfn/common/data_utils.py'
52
+ util_tree = ast.parse(util_path.read_text())
53
+ def unused_evaluator(node):
54
+ if isinstance(node, ast.ImportFrom):
55
+ return (node.module or '').startswith(('matminer.', 'crysbfn.evaluate.eval_utils'))
56
+ if isinstance(node, ast.Assign):
57
+ return any(isinstance(t, ast.Name) and t.id in ['CrystalNNFP', 'CompFP'] for t in node.targets)
58
+ return isinstance(node, (ast.ClassDef, ast.FunctionDef)) and node.name in ['Crystal', 'vis_crystal']
59
+ util_tree.body = [node for node in util_tree.body if not unused_evaluator(node)]
60
+ util_module = types.ModuleType(module_name)
61
+ util_module.__file__ = str(util_path)
62
+ util_module.__package__ = 'crysbfn.common'
63
+ sys.modules[module_name] = util_module
64
+ exec(compile(util_tree, str(util_path), 'exec'), util_module.__dict__)
65
+ cfg.model._target_ = 'crysbfn.pl_modules.crysbfn_csp_plmodel.CrysBFN_CSP_PL_Model'
66
+ cfg.model.BFN._target_ = 'crysbfn.pl_modules.crysbfn_csp.CrysBFN_CSP'
67
+ cfg.model.decoder._target_ = 'crysbfn.pl_modules.egnn.cspnet.CSPNet'
68
+ notes.append('Author renamed cdvae/VM_BFN namespaces mapped to crysbfn/CrysBFN; original EMA state restored strictly; official ten-step entropy schedule')
69
+ notes.append('Skipped isolated, unused DNG evaluator block in data_utils; unchanged geometry and sampler functions')
70
+ elif name.startswith('dao'):
71
+ # This is initialization from stage 2 for TRAINING, not inference conditioning.
72
+ # The fine-tuned checkpoint below contains and strictly restores the whole model.
73
+ cfg.model.pretrain_repr = None
74
+ notes.append('Disabled training-only pretrain_repr path; strict complete fine-tuned state loaded')
75
+ elif name.startswith('equicsp'):
76
+ import equicsp.pl_modules.diff_utils as du
77
+ buffers = {k.split('.', 1)[1]: v for k, v in checkpoint['state_dict'].items()
78
+ if k.startswith('sigma_scheduler.')}
79
+ class CheckpointSigma(torch.nn.Module):
80
+ def __init__(self, timesteps, sigma_begin, sigma_end):
81
+ super().__init__()
82
+ self.timesteps, self.sigma_begin, self.sigma_end = timesteps, sigma_begin, sigma_end
83
+ for key, value in buffers.items():
84
+ self.register_buffer(key, value.clone())
85
+ du.SigmaScheduler = CheckpointSigma
86
+ notes.append('Restored all saved SigmaScheduler buffers, including legacy normalization buffers, directly from author checkpoint; no normalization recomputation')
87
+ model = hydra.utils.instantiate(cfg.model, optim=cfg.optim, data=cfg.data,
88
+ logging=cfg.logging, _recursive_=False)
89
+ keys = model.load_state_dict(checkpoint if name.startswith('crysbfn') else checkpoint['state_dict'], strict=True)
90
+ assert not keys.missing_keys and not keys.unexpected_keys
91
+ assert not getattr(model, 'keep_coords', False) and not getattr(model, 'keep_lattice', False)
92
+ model.eval().to('cuda:0')
93
+ return model, {}, notes
94
+
95
+
96
+ def sample(name, model, runtime, batch, params, seed):
97
+ if name.startswith('crysbfn'):
98
+ import torch
99
+ from crysbfn.common.data_utils import lattice_params_to_matrix_torch
100
+ # Full connectivity is determined solely by atom count.
101
+ edges = []
102
+ offset = 0
103
+ for n in batch.num_atoms.tolist():
104
+ indices = torch.arange(n, device='cuda:0') + offset
105
+ edges.append(torch.stack([indices.repeat_interleave(n), indices.repeat(n)]))
106
+ offset += n
107
+ batch.edge_index = torch.cat(edges, dim=1)
108
+ output = model.sample(batch, **params)
109
+ generated = dict(atom_types=output['atom_types'], num_atoms=output['num_atoms'],
110
+ frac_coords=output['frac_coords'],
111
+ lattices=lattice_params_to_matrix_torch(output['lengths'], output['angles']))
112
+ return generated, output
113
+ if not name.startswith('crystalite'):
114
+ return model.sample(batch, **params)
115
+ import torch
116
+ from src.crystalite import mod1
117
+ from src.crystalite.sampler import edm_sampler, clamp_lattice_latent
118
+ from src.models.lattice_repr import lattice_latent_to_y1
119
+ from pymatgen.core import Lattice
120
+ cfg, enc = runtime['cfg'], runtime['encoding']
121
+ nmax = max(int(cfg['nmax']), int(batch.num_atoms.max()))
122
+ a0 = torch.zeros((batch.num_graphs, nmax), device='cuda:0', dtype=torch.long)
123
+ mask = torch.arange(nmax, device='cuda:0')[None, :] >= batch.num_atoms[:, None]
124
+ offset = 0
125
+ for i, count in enumerate(batch.num_atoms.tolist()):
126
+ a0[i, :count] = batch.atom_types[offset:offset+count]
127
+ offset += count
128
+ fixed = enc.encode_from_A0(a0=a0, pad_mask=mask)
129
+ gen = torch.Generator(device='cuda:0').manual_seed(seed)
130
+ lattice_repr = cfg.get('lattice_repr', 'ltri')
131
+ samples = edm_sampler(model=model, pad_mask=mask, type_dim=enc.type_dim,
132
+ sigma_min=float(cfg.get('sigma_min', .002)), sigma_max=float(cfg.get('sigma_max', 80)),
133
+ sigma_data_type=float(cfg.get('sigma_data_type', 1)),
134
+ sigma_data_coord=float(cfg.get('sigma_data_coord', .3)),
135
+ sigma_data_lat=float(cfg.get('sigma_data_lattice', .3)),
136
+ generator=gen, autocast_dtype=torch.bfloat16 if cfg.get('bf16', False) else None,
137
+ fixed_atom_types=fixed, skip_type_scaling=True, lattice_repr=lattice_repr, **params)
138
+ frac = mod1(samples['frac'] + .5).clamp(0., 1.)[~mask]
139
+ latent = clamp_lattice_latent(samples['lat'].detach().cpu(), lattice_repr)
140
+ y1 = clamp_lattice_latent(lattice_latent_to_y1(latent, lattice_repr=lattice_repr), 'y1')
141
+ lengths = torch.exp(y1[:, :3]).numpy()
142
+ angles = torch.rad2deg(torch.acos(y1[:, 3:].clamp(-1., 1.))).numpy()
143
+ matrices = [Lattice.from_parameters(*lengths[i], *angles[i]).matrix for i in range(len(lengths))]
144
+ import numpy as np
145
+ return dict(atom_types=batch.atom_types, num_atoms=batch.num_atoms, frac_coords=frac,
146
+ lattices=torch.as_tensor(np.asarray(matrices))), samples