feat: replace sigmoid gating with stabilized FiLM affine modulation; train pimt_v2.pt
Browse files- scripts/hf_train_job.py +1 -1
- src/pino/embeddings.py +14 -3
- src/pino/pimt_model.py +41 -15
- src/pino/train.py +1 -1
scripts/hf_train_job.py
CHANGED
|
@@ -122,7 +122,7 @@ def hf_train_5epoch() -> None:
|
|
| 122 |
api = HfApi(token=token)
|
| 123 |
api.upload_file(
|
| 124 |
path_or_fileobj=str(checkpoint_path),
|
| 125 |
-
path_in_repo="
|
| 126 |
repo_id=repo_id,
|
| 127 |
repo_type="model",
|
| 128 |
)
|
|
|
|
| 122 |
api = HfApi(token=token)
|
| 123 |
api.upload_file(
|
| 124 |
path_or_fileobj=str(checkpoint_path),
|
| 125 |
+
path_in_repo="pimt_v2.pt",
|
| 126 |
repo_id=repo_id,
|
| 127 |
repo_type="model",
|
| 128 |
)
|
src/pino/embeddings.py
CHANGED
|
@@ -139,22 +139,33 @@ class OlfactoryEmbeddingEngine:
|
|
| 139 |
def get_embedding(self, smiles: str, cas: str | None = None) -> np.ndarray:
|
| 140 |
"""Main entry point. Returns a 151-dimensional float32 array."""
|
| 141 |
normalized_cas = self._normalized_cas(cas)
|
|
|
|
| 142 |
|
| 143 |
if normalized_cas:
|
| 144 |
try:
|
| 145 |
record = self.registry.get(normalized_cas)
|
| 146 |
if record:
|
| 147 |
structural = np.asarray(record.get("openpom_embedding") or [0.0] * STRUCTURAL_DIM, dtype=np.float32)
|
| 148 |
-
if structural.shape[0] != STRUCTURAL_DIM:
|
| 149 |
structural = self._compute_structural_embedding(smiles, cas)
|
| 150 |
shape = np.asarray(record.get("shape_3d_features") or [0.0] * SHAPE_DIM, dtype=np.float32)
|
| 151 |
-
if shape.shape[0] != SHAPE_DIM:
|
| 152 |
shape = self._compute_shape_features(smiles, cas)
|
| 153 |
physical = self._extract_physical_features(record)
|
| 154 |
functional = self._extract_functional_features(record)
|
| 155 |
combined = np.concatenate([structural, shape, physical, functional]).astype(np.float32)
|
| 156 |
norm = np.linalg.norm(combined)
|
| 157 |
return combined / norm if norm > 0 else combined
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
except Exception as exc:
|
| 159 |
logger.debug("Registry lookup failed for %s: %s", normalized_cas, exc)
|
| 160 |
|
|
@@ -182,7 +193,7 @@ class OlfactoryEmbeddingEngine:
|
|
| 182 |
logger.debug("Registry lookup failed for %s: %s", normalized_cas, exc)
|
| 183 |
|
| 184 |
# Natural oils may be resolvable from a constituent blend even if no SMILES.
|
| 185 |
-
if normalized_cas and (normalized_cas.startswith("8") or normalized_cas.startswith("6") or normalized_cas.startswith("9")):
|
| 186 |
try:
|
| 187 |
all_records = self.registry.all_records()
|
| 188 |
openpom, _ = resolve_natural_oil_vectors(normalized_cas, all_records)
|
|
|
|
| 139 |
def get_embedding(self, smiles: str, cas: str | None = None) -> np.ndarray:
|
| 140 |
"""Main entry point. Returns a 151-dimensional float32 array."""
|
| 141 |
normalized_cas = self._normalized_cas(cas)
|
| 142 |
+
is_natural = bool(cas and str(cas).startswith("NATURAL:"))
|
| 143 |
|
| 144 |
if normalized_cas:
|
| 145 |
try:
|
| 146 |
record = self.registry.get(normalized_cas)
|
| 147 |
if record:
|
| 148 |
structural = np.asarray(record.get("openpom_embedding") or [0.0] * STRUCTURAL_DIM, dtype=np.float32)
|
| 149 |
+
if structural.shape[0] != STRUCTURAL_DIM or (not is_natural and np.count_nonzero(structural) == 0):
|
| 150 |
structural = self._compute_structural_embedding(smiles, cas)
|
| 151 |
shape = np.asarray(record.get("shape_3d_features") or [0.0] * SHAPE_DIM, dtype=np.float32)
|
| 152 |
+
if shape.shape[0] != SHAPE_DIM or (not is_natural and np.count_nonzero(shape) == 0):
|
| 153 |
shape = self._compute_shape_features(smiles, cas)
|
| 154 |
physical = self._extract_physical_features(record)
|
| 155 |
functional = self._extract_functional_features(record)
|
| 156 |
combined = np.concatenate([structural, shape, physical, functional]).astype(np.float32)
|
| 157 |
norm = np.linalg.norm(combined)
|
| 158 |
return combined / norm if norm > 0 else combined
|
| 159 |
+
# If the registry has no record at all but this is a natural-oil token,
|
| 160 |
+
# still try to resolve from the natural-oil constituent profile.
|
| 161 |
+
if is_natural:
|
| 162 |
+
structural = self._compute_structural_embedding(smiles, cas)
|
| 163 |
+
shape = self._compute_shape_features(smiles, cas)
|
| 164 |
+
physical = np.array([0.5, self.global_median_logp / 5.0], dtype=np.float32)
|
| 165 |
+
functional = _functional_group_flags(None)
|
| 166 |
+
combined = np.concatenate([structural, shape, physical, functional]).astype(np.float32)
|
| 167 |
+
norm = np.linalg.norm(combined)
|
| 168 |
+
return combined / norm if norm > 0 else combined
|
| 169 |
except Exception as exc:
|
| 170 |
logger.debug("Registry lookup failed for %s: %s", normalized_cas, exc)
|
| 171 |
|
|
|
|
| 193 |
logger.debug("Registry lookup failed for %s: %s", normalized_cas, exc)
|
| 194 |
|
| 195 |
# Natural oils may be resolvable from a constituent blend even if no SMILES.
|
| 196 |
+
if normalized_cas and ((cas or "").startswith("NATURAL:") or normalized_cas.startswith("8") or normalized_cas.startswith("6") or normalized_cas.startswith("9")):
|
| 197 |
try:
|
| 198 |
all_records = self.registry.all_records()
|
| 199 |
openpom, _ = resolve_natural_oil_vectors(normalized_cas, all_records)
|
src/pino/pimt_model.py
CHANGED
|
@@ -148,26 +148,40 @@ class FragranceTrajectoryDataset(Dataset):
|
|
| 148 |
return ""
|
| 149 |
|
| 150 |
|
| 151 |
-
class
|
| 152 |
"""
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
"""
|
| 159 |
|
| 160 |
def __init__(self, embedding_dim: int, state_dim: int, hidden_dim: int = 64) -> None:
|
| 161 |
super().__init__()
|
| 162 |
self.embedding_dim = embedding_dim
|
| 163 |
self.state_dim = state_dim
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
torch.nn.ReLU(),
|
| 167 |
-
torch.nn.Linear(hidden_dim, embedding_dim),
|
| 168 |
-
torch.nn.Sigmoid(),
|
| 169 |
)
|
| 170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
def forward(self, tokens: torch.Tensor, states: torch.Tensor) -> torch.Tensor:
|
| 172 |
"""
|
| 173 |
tokens: (B, S, E)
|
|
@@ -176,10 +190,22 @@ class PhysicsInformedGatingBlock(torch.nn.Module):
|
|
| 176 |
"""
|
| 177 |
b, seq_len, e = tokens.shape
|
| 178 |
t_steps = states.size(1)
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
|
| 185 |
class PhysicsInformedMixtureTransformer(torch.nn.Module):
|
|
@@ -205,7 +231,7 @@ class PhysicsInformedMixtureTransformer(torch.nn.Module):
|
|
| 205 |
self.hidden_dim = hidden_dim
|
| 206 |
self.max_ingredients = max_ingredients
|
| 207 |
|
| 208 |
-
self.gating =
|
| 209 |
self.input_proj = torch.nn.Linear(embedding_dim, hidden_dim)
|
| 210 |
|
| 211 |
encoder_layer = torch.nn.TransformerEncoderLayer(
|
|
|
|
| 148 |
return ""
|
| 149 |
|
| 150 |
|
| 151 |
+
class PhysicsInformedFiLMBlock(torch.nn.Module):
|
| 152 |
"""
|
| 153 |
+
Feature-wise Linear Modulation (FiLM) of static token embeddings by a
|
| 154 |
+
time-varying physical state vector.
|
| 155 |
+
|
| 156 |
+
The physics engine predicts a per-token, per-timestep scale (gamma) and
|
| 157 |
+
shift (beta) that are applied to the static ingredient embeddings. The
|
| 158 |
+
``(1 + gamma) * tokens + beta`` form lets the block default to the identity
|
| 159 |
+
when weights are near zero, while still giving the network full dynamic
|
| 160 |
+
range as it learns. No positional encoding is added, so the model remains
|
| 161 |
+
permutation-invariant with respect to ingredient order.
|
| 162 |
"""
|
| 163 |
|
| 164 |
def __init__(self, embedding_dim: int, state_dim: int, hidden_dim: int = 64) -> None:
|
| 165 |
super().__init__()
|
| 166 |
self.embedding_dim = embedding_dim
|
| 167 |
self.state_dim = state_dim
|
| 168 |
+
|
| 169 |
+
# Stabilized per-channel affine transform for the raw physics states.
|
| 170 |
+
# This standardizes the physics channels without compressing them into a
|
| 171 |
+
# vector norm, preserving the genuine slope/curvature of the VLE trajectory.
|
| 172 |
+
self.physics_scaler = torch.nn.Parameter(torch.ones(state_dim)) # type: ignore[arg-type]
|
| 173 |
+
self.physics_bias = torch.nn.Parameter(torch.zeros(state_dim)) # type: ignore[arg-type]
|
| 174 |
+
|
| 175 |
+
self.state_proj = torch.nn.Sequential(
|
| 176 |
+
torch.nn.Linear(state_dim, hidden_dim),
|
| 177 |
torch.nn.ReLU(),
|
| 178 |
+
torch.nn.Linear(hidden_dim, embedding_dim * 2),
|
|
|
|
| 179 |
)
|
| 180 |
|
| 181 |
+
# Token normalization is applied BEFORE modulation (AdaLN style) so the
|
| 182 |
+
# time-varying beta/shift term is not dampened by static token statistics.
|
| 183 |
+
self.token_norm = torch.nn.LayerNorm(embedding_dim)
|
| 184 |
+
|
| 185 |
def forward(self, tokens: torch.Tensor, states: torch.Tensor) -> torch.Tensor:
|
| 186 |
"""
|
| 187 |
tokens: (B, S, E)
|
|
|
|
| 190 |
"""
|
| 191 |
b, seq_len, e = tokens.shape
|
| 192 |
t_steps = states.size(1)
|
| 193 |
+
|
| 194 |
+
# 1. Standardize physics channels independently.
|
| 195 |
+
normed_states = states * self.physics_scaler + self.physics_bias
|
| 196 |
+
|
| 197 |
+
# 2. Generate FiLM parameters and split into gamma (scale) and beta (shift).
|
| 198 |
+
film_params = self.state_proj(normed_states) # (B, T, S, 2*E)
|
| 199 |
+
gamma, beta = torch.chunk(film_params, 2, dim=-1)
|
| 200 |
+
|
| 201 |
+
# 3. Normalize tokens once, then broadcast across the time dimension.
|
| 202 |
+
normed_tokens = self.token_norm(tokens)
|
| 203 |
+
tokens_t = normed_tokens.unsqueeze(1).expand(b, t_steps, seq_len, e)
|
| 204 |
+
|
| 205 |
+
# 4. Affine modulation outside the token norm loop.
|
| 206 |
+
# Temporal variance from gamma and beta passes completely uninhibited.
|
| 207 |
+
modulated = (1.0 + gamma) * tokens_t + beta
|
| 208 |
+
return modulated
|
| 209 |
|
| 210 |
|
| 211 |
class PhysicsInformedMixtureTransformer(torch.nn.Module):
|
|
|
|
| 231 |
self.hidden_dim = hidden_dim
|
| 232 |
self.max_ingredients = max_ingredients
|
| 233 |
|
| 234 |
+
self.gating = PhysicsInformedFiLMBlock(embedding_dim, state_dim, hidden_dim=hidden_dim)
|
| 235 |
self.input_proj = torch.nn.Linear(embedding_dim, hidden_dim)
|
| 236 |
|
| 237 |
encoder_layer = torch.nn.TransformerEncoderLayer(
|
src/pino/train.py
CHANGED
|
@@ -266,7 +266,7 @@ def main():
|
|
| 266 |
"max_batches_per_epoch": None,
|
| 267 |
"lr": args.lr,
|
| 268 |
"weight_decay": 1e-2,
|
| 269 |
-
"checkpoint_name": "
|
| 270 |
}
|
| 271 |
logger.info("Configuration: %s", cfg)
|
| 272 |
|
|
|
|
| 266 |
"max_batches_per_epoch": None,
|
| 267 |
"lr": args.lr,
|
| 268 |
"weight_decay": 1e-2,
|
| 269 |
+
"checkpoint_name": "pimt_v2.pt",
|
| 270 |
}
|
| 271 |
logger.info("Configuration: %s", cfg)
|
| 272 |
|