RSI-Anything / reaction_optimization /src /yield_predictor.py
dariuscty's picture
Restore RSI-Anything inference resources and LabHorizon dataset
672ecc3 verified
Raw History Blame Contribute Delete
3.55 kB
"""Predict yields from reaction SMILES."""
from rdkit import Chem
import torch
from .reactiont5_jepa import load_model
def canonicalize(smiles):
# Same normalization and dot-component ordering as prepare_data.py.
cleaned = smiles.replace('. ', '').replace(' .', '').replace(' ', ' ').strip()
if not cleaned:
return ' '
molecule = Chem.MolFromSmiles(cleaned)
if molecule is None:
raise ValueError(f'Invalid SMILES: {smiles!r}')
return '.'.join(sorted(Chem.MolToSmiles(molecule, canonical=True).split('.')))
def reaction_text(row):
for key in ('REACTANT', 'REAGENT', 'PRODUCT'):
if key not in row or not isinstance(row[key], str):
raise ValueError(f'Missing or non-string field: {key}')
if not row['REACTANT'].strip() or not row['PRODUCT'].strip():
raise ValueError('REACTANT and PRODUCT must be nonempty SMILES')
catalyst = row.get('CATALYST') or ''
if not isinstance(catalyst, str):
raise ValueError('CATALYST must be a SMILES string')
reagent = '.'.join(part for part in (catalyst, row['REAGENT']) if part.strip())
fields = {
'REACTANT': canonicalize(row['REACTANT']),
'REAGENT': canonicalize(reagent),
'PRODUCT': canonicalize(row['PRODUCT']),
}
return ''.join(f'{key}:{fields[key]}' for key in ('REACTANT', 'REAGENT', 'PRODUCT'))
class YieldPredictor:
def __init__(self, model_dir, device='cpu', precision='fp32', verify_checksum=True):
if precision not in ('bf16', 'fp32'):
raise ValueError('precision must be bf16 or fp32')
self.model, self.tokenizer, self.info = load_model(model_dir, device, verify_checksum)
self.device = torch.device(device)
self.precision = precision
if self.device.type == 'cuda' and precision == 'bf16' and not torch.cuda.is_bf16_supported():
raise RuntimeError('This GPU does not support BF16; use precision="fp32"')
@torch.inference_mode()
def predict(self, reactions, batch_size=32):
if batch_size < 1:
raise ValueError('batch_size must be positive')
reactions = list(reactions)
texts = [reaction_text(row) for row in reactions]
results = []
for start in range(0, len(texts), batch_size):
batch = texts[start:start + batch_size]
full_ids = self.tokenizer(batch, add_special_tokens=True, truncation=False)['input_ids']
encoded = self.tokenizer(
batch, add_special_tokens=True, padding='max_length', truncation=True,
max_length=self.info['max_input_length'], return_tensors='pt',
)
inputs = {key: encoded[key].to(self.device) for key in ('input_ids', 'attention_mask')}
values = self.model(inputs, self.precision).float().cpu().tolist()
for offset, value in enumerate(values):
if not (-float('inf') < value < float('inf')):
raise RuntimeError('The model produced a non-finite prediction')
results.append({
'index': start + offset,
'reaction_input': batch[offset],
'yield_fraction_raw': value,
'yield_percent_raw': value * 100.0,
'yield_percent_clipped': min(100.0, max(0.0, value * 100.0)),
'input_tokens': len(full_ids[offset]),
'input_truncated': len(full_ids[offset]) > self.info['max_input_length'],
})
return results