mattbitzesty commited on
Commit
96f3ac5
·
1 Parent(s): cfa3391

perf(optimizer): cache PIMT model locally instead of hitting Space every candidate

Browse files

Why: each CMA-ES evaluation was downloading/running the model from the Space
fallback, which is too slow for hundreds of candidates and broke when the Space
was sleeping or rebuilding. Now FormulationOptimizer loads the critic once and
uses _predict_local directly.

Also fixes IFRA projection with iterative water-filling so re-normalisation never
re-inflates a capped ingredient above its IFRA limit, and filters the palette to
exclude solvents and restricted materials.

Files changed (3) hide show
  1. .gitignore +2 -1
  2. src/pino/inference_cloud.py +10 -5
  3. src/pino/optimizer.py +83 -15
.gitignore CHANGED
@@ -10,6 +10,7 @@ build/
10
  *.json
11
  !.gitkeep
12
  !data/design_brief.json
 
 
13
  *.jsonl
14
  *.parquet
15
- src/pino/registry.db
 
10
  *.json
11
  !.gitkeep
12
  !data/design_brief.json
13
+ *.db
14
+ !src/pino/registry.db
15
  *.jsonl
16
  *.parquet
 
src/pino/inference_cloud.py CHANGED
@@ -72,11 +72,14 @@ def _smiles_for_cas(cas: str) -> str:
72
  def predict_cloud(
73
  formula: dict[str, Any],
74
  token: str | None = None,
 
 
75
  ) -> dict[str, Any]:
76
  """
77
  POST a processed formula to the HF Space inference endpoint and return predictions.
78
 
79
- Falls back to a local model if the Space endpoint is not yet available.
 
80
  """
81
  url = _resolve_space_url(token)
82
  payload = encode_formula(formula)
@@ -94,14 +97,16 @@ def predict_cloud(
94
  return result
95
  except Exception as e:
96
  logger.warning("Cloud inference failed (%s); falling back to local model", e)
97
- return _predict_local(formula)
98
 
99
 
100
- def _predict_local(formula: dict[str, Any]) -> dict[str, Any]:
101
- """Local CPU fallback for development/testing."""
102
  import torch
103
 
104
- model = PhysicsInformedMixtureTransformer.from_pretrained("mattbitzesty/pino-pimt")
 
 
105
  model.eval()
106
 
107
  payload = encode_formula(formula)
 
72
  def predict_cloud(
73
  formula: dict[str, Any],
74
  token: str | None = None,
75
+ *,
76
+ _cached_model: Any = None,
77
  ) -> dict[str, Any]:
78
  """
79
  POST a processed formula to the HF Space inference endpoint and return predictions.
80
 
81
+ Falls back to a local model if the Space endpoint is not yet available. A
82
+ cached model can be supplied to avoid repeated Hub downloads.
83
  """
84
  url = _resolve_space_url(token)
85
  payload = encode_formula(formula)
 
97
  return result
98
  except Exception as e:
99
  logger.warning("Cloud inference failed (%s); falling back to local model", e)
100
+ return _predict_local(formula, cached_model=_cached_model)
101
 
102
 
103
+ def _predict_local(formula: dict[str, Any], *, cached_model: Any = None) -> dict[str, Any]:
104
+ """Local CPU fallback for development/testing, with optional cached model."""
105
  import torch
106
 
107
+ model = cached_model
108
+ if model is None:
109
+ model = PhysicsInformedMixtureTransformer.from_pretrained("mattbitzesty/pino-pimt")
110
  model.eval()
111
 
112
  payload = encode_formula(formula)
src/pino/optimizer.py CHANGED
@@ -266,6 +266,9 @@ class FormulationOptimizer:
266
  surface_area_m2=1e-4,
267
  mass_transfer_coefficient=1e-4,
268
  )
 
 
 
269
  self.palette: list[Ingredient] = []
270
  self.palette_cas: list[str] = []
271
  self._rng = np.random.default_rng(self.config.seed)
@@ -273,6 +276,14 @@ class FormulationOptimizer:
273
  random.seed(self.config.seed)
274
  torch.manual_seed(self.config.seed)
275
 
 
 
 
 
 
 
 
 
276
  def _build_palette(self, count: int = 20) -> None:
277
  """
278
  Select a diverse palette from the SQLite registry.
@@ -284,36 +295,43 @@ class FormulationOptimizer:
284
  """
285
  import sqlite3
286
 
287
- path = Path(self.config.registry_path) if self.config.registry_path else Path(__file__).with_suffix(".db")
288
  conn = sqlite3.connect(path)
289
  conn.row_factory = sqlite3.Row
290
 
291
  # Pull candidates with reasonable volatility and a canonical SMILES.
 
 
 
 
292
  rows = conn.execute(
293
  """
294
  SELECT cas, name, smiles, molecular_weight, boiling_point_k, vapor_pressure_pa, logp
295
  FROM aroma_chemicals
296
- WHERE molecular_weight BETWEEN 50 AND 300
297
  AND vapor_pressure_pa IS NOT NULL
298
  AND vapor_pressure_pa > 0
299
  ORDER BY molecular_weight ASC
300
  LIMIT ?
301
  """,
302
- (count * 4,),
303
  ).fetchall()
304
  conn.close()
305
 
306
  candidates: list[Ingredient] = []
307
  for row in rows:
 
 
 
308
  try:
309
  ing = self.resolver.resolve(
310
- str(row["cas"]),
311
  weight_fraction=0.0,
312
  name=row["name"],
313
  )
314
  candidates.append(ing)
315
  except Exception as exc:
316
- logger.debug("Skipping palette candidate %s: %s", row["cas"], exc)
317
  continue
318
 
319
  # Shuffle and downsample to the requested count for variety.
@@ -350,28 +368,48 @@ class FormulationOptimizer:
350
  Steps:
351
  1. Clip to [0, 1] and zero out negligible components (promotes sparsity).
352
  2. Enforce IFRA Category 4 limits by capping each ingredient at its
353
- maximum allowed concentration.
 
 
354
  3. Re-normalize so the vector sums to exactly 1.0.
355
 
356
  This projection is cheap and keeps the search inside the safe region.
357
- CMA-ES therefore only ever evaluates physically meaningful recipes.
358
  """
359
  x = np.clip(x, 0.0, 1.0)
360
  x[x < self.config.min_weight_fraction] = 0.0
361
 
362
- # IFRA limit projection: each component cannot exceed its Category 4 limit.
 
 
 
363
  for i, ing in enumerate(self.palette):
364
  restriction = IFRA_RESTRICTIONS.get(ing.cas)
365
  if restriction:
366
- limit_fraction = restriction["category_4_pct"] / 100.0
367
- x[i] = min(x[i], limit_fraction)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
 
369
  total = x.sum()
370
  if total > 0:
371
  x = x / total
372
  else:
373
- # Fallback: uniform distribution if the projection collapses.
374
- x = np.ones_like(x) / len(x)
 
 
375
  return x
376
 
377
  def _evaluate(self, x: np.ndarray, target: CompositionTarget) -> Candidate:
@@ -418,9 +456,11 @@ class FormulationOptimizer:
418
  message=result["message"],
419
  )
420
 
421
- # Encode for the PIMT critic.
 
 
422
  try:
423
- prediction = self._predict(formula_records, result["trajectory"])
424
  except Exception as exc:
425
  logger.warning("Prediction failed for candidate: %s", exc)
426
  return Candidate(
@@ -465,7 +505,35 @@ class FormulationOptimizer:
465
  "trajectory": trajectory,
466
  "metadata": {"generation_strategy": "wildcard"},
467
  }
468
- return predict_cloud(formula_payload, token=self.config.token)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
469
 
470
  def _mse(self, prediction: dict[str, Any], target: CompositionTarget) -> float:
471
  """
 
266
  surface_area_m2=1e-4,
267
  mass_transfer_coefficient=1e-4,
268
  )
269
+ # Cache the PIMT model locally so the composer does not download it for
270
+ # every candidate evaluation. This dramatically speeds up the local fallback.
271
+ self._cached_model = self._load_cached_model()
272
  self.palette: list[Ingredient] = []
273
  self.palette_cas: list[str] = []
274
  self._rng = np.random.default_rng(self.config.seed)
 
276
  random.seed(self.config.seed)
277
  torch.manual_seed(self.config.seed)
278
 
279
+ def _load_cached_model(self) -> "PhysicsInformedMixtureTransformer":
280
+ """Load the critic model once; used for every candidate evaluation."""
281
+ from .pimt_model_hf import PhysicsInformedMixtureTransformer
282
+ logger.info("Loading PIMT critic model from mattbitzesty/pino-pimt")
283
+ model = PhysicsInformedMixtureTransformer.from_pretrained("mattbitzesty/pino-pimt")
284
+ model.eval()
285
+ return model
286
+
287
  def _build_palette(self, count: int = 20) -> None:
288
  """
289
  Select a diverse palette from the SQLite registry.
 
295
  """
296
  import sqlite3
297
 
298
+ path = Path(self.config.registry_path) if self.config.registry_path else Path(__file__).with_name("registry.db")
299
  conn = sqlite3.connect(path)
300
  conn.row_factory = sqlite3.Row
301
 
302
  # Pull candidates with reasonable volatility and a canonical SMILES.
303
+ non_formula_solvents = {"64-17-5", "67-63-0", "25265-71-8"} # ethanol, IPA, DPG
304
+ restricted_or_problematic = {
305
+ "80-54-6", "83-66-9", "81-15-2", "89-68-9", "92-48-8", "143-50-0"
306
+ }
307
  rows = conn.execute(
308
  """
309
  SELECT cas, name, smiles, molecular_weight, boiling_point_k, vapor_pressure_pa, logp
310
  FROM aroma_chemicals
311
+ WHERE molecular_weight BETWEEN 80 AND 300
312
  AND vapor_pressure_pa IS NOT NULL
313
  AND vapor_pressure_pa > 0
314
  ORDER BY molecular_weight ASC
315
  LIMIT ?
316
  """,
317
+ (count * 8,),
318
  ).fetchall()
319
  conn.close()
320
 
321
  candidates: list[Ingredient] = []
322
  for row in rows:
323
+ cas = str(row["cas"])
324
+ if cas in non_formula_solvents or cas in restricted_or_problematic:
325
+ continue
326
  try:
327
  ing = self.resolver.resolve(
328
+ cas,
329
  weight_fraction=0.0,
330
  name=row["name"],
331
  )
332
  candidates.append(ing)
333
  except Exception as exc:
334
+ logger.debug("Skipping palette candidate %s: %s", cas, exc)
335
  continue
336
 
337
  # Shuffle and downsample to the requested count for variety.
 
368
  Steps:
369
  1. Clip to [0, 1] and zero out negligible components (promotes sparsity).
370
  2. Enforce IFRA Category 4 limits by capping each ingredient at its
371
+ maximum allowed concentration. Because re-normalisation can push a
372
+ capped ingredient back above its limit, we iterate the cap-and-rescale
373
+ step until the simplex is stable (water-filling on the simplex).
374
  3. Re-normalize so the vector sums to exactly 1.0.
375
 
376
  This projection is cheap and keeps the search inside the safe region.
 
377
  """
378
  x = np.clip(x, 0.0, 1.0)
379
  x[x < self.config.min_weight_fraction] = 0.0
380
 
381
+ # Build the limit vector. If an ingredient has no IFRA entry, its limit
382
+ # is 1.0 (i.e., it can be the entire formula). Prohibited materials have
383
+ # limit 0.0 and are therefore removed by this step.
384
+ limits = np.ones(len(self.palette), dtype=float)
385
  for i, ing in enumerate(self.palette):
386
  restriction = IFRA_RESTRICTIONS.get(ing.cas)
387
  if restriction:
388
+ limits[i] = restriction["category_4_pct"] / 100.0
389
+
390
+ # Iterative water-filling on the simplex. Any component above its limit
391
+ # is clamped to the limit; the excess mass is redistributed among the
392
+ # components that are still below their limits. This terminates quickly
393
+ # because at least one component is capped each iteration.
394
+ for _ in range(50):
395
+ x = np.minimum(x, limits)
396
+ total = x.sum()
397
+ if total <= 0:
398
+ break
399
+ scale = 1.0 / total
400
+ x = x * scale
401
+ # If all components are now within limits after rescaling, we are done.
402
+ if np.all(x <= limits + 1e-12):
403
+ break
404
 
405
  total = x.sum()
406
  if total > 0:
407
  x = x / total
408
  else:
409
+ # Fallback: uniform distribution over ingredients with a non-zero limit.
410
+ allowed = limits > 0
411
+ x = np.zeros_like(x)
412
+ x[allowed] = 1.0 / allowed.sum()
413
  return x
414
 
415
  def _evaluate(self, x: np.ndarray, target: CompositionTarget) -> Candidate:
 
456
  message=result["message"],
457
  )
458
 
459
+ # Encode for the PIMT critic. We use the cached local model directly to
460
+ # avoid the per-request HTTP round-trip to the Space endpoint, which is
461
+ # especially slow when the Space is sleeping or rebuilding.
462
  try:
463
+ prediction = self._predict_local(formula_records, result["trajectory"])
464
  except Exception as exc:
465
  logger.warning("Prediction failed for candidate: %s", exc)
466
  return Candidate(
 
505
  "trajectory": trajectory,
506
  "metadata": {"generation_strategy": "wildcard"},
507
  }
508
+ return predict_cloud(formula_payload, token=self.config.token, _cached_model=self._cached_model)
509
+
510
+ def _predict_local(
511
+ self,
512
+ formula_records: list[dict[str, Any]],
513
+ trajectory: list[dict[str, Any]],
514
+ ) -> dict[str, Any]:
515
+ """Run the cached PIMT critic directly without any HTTP round-trip."""
516
+ import torch
517
+ from .inference_cloud import encode_formula
518
+
519
+ formula_payload = {
520
+ "formula": formula_records,
521
+ "trajectory": trajectory,
522
+ "metadata": {"generation_strategy": "wildcard"},
523
+ }
524
+ payload = encode_formula(formula_payload)
525
+ tokens = torch.tensor(payload["tokens"], dtype=torch.float32).unsqueeze(0)
526
+ physics = torch.tensor(payload["physics"], dtype=torch.float32).unsqueeze(0)
527
+ mask = torch.tensor(payload["src_key_padding_mask"], dtype=torch.bool).unsqueeze(0)
528
+
529
+ with torch.no_grad():
530
+ output = self._cached_model(tokens, physics, src_key_padding_mask=mask)
531
+
532
+ return {
533
+ "status": "success (local cached)",
534
+ "objective": output.logits.cpu().numpy().tolist(),
535
+ "subjective": output.subjective.cpu().numpy().tolist(),
536
+ }
537
 
538
  def _mse(self, prediction: dict[str, Any], target: CompositionTarget) -> float:
539
  """