""" Grammar-Constrained Decoding (GCD) for Spectra-Reason-GCD inference. Ensures generated SMILES are syntactically valid using an EBNF grammar. """ from __future__ import annotations from pathlib import Path from typing import Any, List, Optional import torch def get_smiles_constraint(tokenizer, grammar_path: Optional[Path] = None): """ Return a logits processor for SMILES grammar if transformers_cfg is available. Otherwise return None (unconstrained). """ try: from transformers_cfg.grammar_utils import IncrementalGrammarConstraint except ImportError: return None if grammar_path is None: grammar_path = Path(__file__).resolve().parents[1] / "grammars" / "smiles.ebnf" if not grammar_path.exists(): return None grammar_str = grammar_path.read_text() try: return IncrementalGrammarConstraint(grammar_str, "root", tokenizer) except Exception: return None def generate_with_gcd( model, tokenizer, inputs_embeds: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, max_new_tokens: int = 200, grammar_path: Optional[Path] = None, **generate_kwargs: Any, ) -> List[str]: """ Generate from model with optional SMILES grammar constraint. inputs_embeds: (B, 64 + prefix_len, dim) or (B, total_len, dim) including soft tokens. """ logits_processor = [] constraint = get_smiles_constraint(tokenizer, grammar_path) if constraint is not None: logits_processor.append(constraint) gen_kw = { "max_new_tokens": max_new_tokens, "do_sample": False, "pad_token_id": tokenizer.pad_token_id or tokenizer.eos_token_id, **generate_kwargs, } if logits_processor: gen_kw["logits_processor"] = logits_processor with torch.no_grad(): out = model.generate( inputs_embeds=inputs_embeds, attention_mask=attention_mask, position_ids=position_ids, **gen_kw, ) # Decode only the generated part (skip input length) input_len = inputs_embeds.shape[1] generated = out[:, input_len:] return tokenizer.batch_decode(generated, skip_special_tokens=True) def predict_smiles_from_spectrum( encoder, model, tokenizer, peaks: torch.Tensor, device: torch.device, max_new_tokens: int = 200, use_gcd: bool = True, grammar_path: Optional[Path] = None, ) -> str: """ Single spectrum -> SMILES. Encoder produces 64 soft tokens; we build prompt (user message), prepend soft tokens, then generate with optional GCD. """ encoder.eval() model.eval() meta = {"peaks": peaks.to(device)} if peaks.dim() == 2: peaks = peaks.unsqueeze(0) meta["peaks"] = peaks.to(device) with torch.no_grad(): soft = encoder(peaks=peaks.to(device), meta=meta) B = soft.shape[0] llm_dim = soft.shape[2] embed_layer = model.get_input_embeddings() messages = [ {"role": "system", "content": "You are an expert mass spectrometrist. Analyze the input spectrum, deduce the substructures, and generate the valid SMILES string."}, {"role": "user", "content": "Analyze the spectrum and predict the molecule structure."}, ] prompt = tokenizer.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_tensors="pt", ) prompt = prompt.to(device) if prompt.dim() == 1: prompt = prompt.unsqueeze(0).expand(B, -1) text_emb = embed_layer(prompt) soft = soft.to(dtype=text_emb.dtype) # Ensure dtype match inputs_embeds = torch.cat([soft, text_emb], dim=1) attention_mask = torch.ones(inputs_embeds.shape[0], inputs_embeds.shape[1], dtype=torch.long, device=device) position_ids = torch.arange(inputs_embeds.shape[1], device=device).unsqueeze(0).expand(B, -1) constraint = get_smiles_constraint(tokenizer, grammar_path) if use_gcd else None logits_processor = [constraint] if constraint is not None else [] with torch.no_grad(): out = model.generate( inputs_embeds=inputs_embeds, attention_mask=attention_mask, position_ids=position_ids, max_new_tokens=max_new_tokens, do_sample=False, pad_token_id=tokenizer.pad_token_id or tokenizer.eos_token_id, logits_processor=logits_processor, ) # When using inputs_embeds without input_ids, generate returns ONLY new tokens. generated = out decoded = tokenizer.batch_decode(generated, skip_special_tokens=True) return decoded[0].strip() if decoded else ""