| CrossAttentionConditioner |
Ran ran on a synthesized input |
VIKI623/MS-GPT/src/ms_gpt/models/conditional_mlm.py code served (permissive licence) · get_code("bf9ce3393e79bf14") How it ranRan in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 3, dtype family float, shape (2, 3, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.
import torch
import torch.nn as nn
# Import the classes
from typing import Optional, Tuple, Union
class SplitQKVMultiheadAttention(nn.Module):
"""nn.MultiheadAttention with Q/K/V as separate Linear submodules."""
def __init__(self, embed_dim: int, num_heads: int, dropout: float=0.0, bias: bool=True):
super().__init__()
if embed_dim % num_heads != 0:
raise ValueError(f'embed_dim {embed_dim} not divisible by num_heads {num_heads}')
self.embed_dim = embed_dim
self.num_heads = num_heads
self.head_dim = embed_dim // num_heads
self.scale = self.head_dim ** (-0.5)
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.attn_dropout = nn.Dropout(dropout)
def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, key_padding_mask: Optional[torch.Tensor]=None, need_weights: bool=False) -> Tuple[torch.Tensor, None]:
B, Lq, _ = query.shape
Lk = key.shape[1]
q = self.q_proj(query).view(B, Lq, self.num_heads, self.head_dim).transpose(1, 2)
k = self.k_proj(key).view(B, Lk, self.num_heads, self.head_dim).transpose(1, 2)
v = self.v_proj(value).view(B, Lk, self.num_heads, self.head_dim).transpose(1, 2)
attn = torch.matmul(q * self.scale, k.transpose(-2, -1))
if key_padding_mask is not None:
attn = attn.masked_fill(key_padding_mask[:, None, None, :], float('-inf'))
attn = attn.softmax(dim=-1)
attn = self.attn_dropout(attn)
out = torch.matmul(attn, v).transpose(1, 2).reshape(B, Lq, self.embed_dim)
out = self.out_proj(out)
return (out, None)
class CrossAttentionConditioner(nn.Module):
"""Cross-attention layer injected into GPT-2 blocks for FP/formula conditioning."""
def __init__(self, d_model: int=768, num_heads: int=12, dropout: float=0.1):
super().__init__()
self.cross_attn = SplitQKVMultiheadAttention(embed_dim=d_model, num_heads=num_heads, dropout=dropout)
self.norm = nn.LayerNorm(d_model)
self.ffn = nn.Sequential(nn.Linear(d_model, d_model * 4), nn.GELU(), nn.Dropout(dropout), nn.Linear(d_model * 4, d_model), nn.Dropout(dropout))
self.norm2 = nn.LayerNorm(d_model)
def forward(self, x: torch.Tensor, context: torch.Tensor, context_mask: Optional[torch.Tensor]=None) -> torch.Tensor:
"""
Args:
x: (batch, seq_len, d_model) - MLM hidden states
context: (batch, ctx_len, d_model) - condition embeddings
context_mask: (batch, ctx_len) - True=valid, False=padding
"""
key_padding_mask = ~context_mask if context_mask is not None else None
residual = x
x = self.norm(x)
x, _ = self.cross_attn(x, context, context, key_padding_mask=key_padding_mask)
x = residual + x
x = x + self.ffn(self.norm2(x))
return x
# Setup code
INIT_ARGS = {
'd_model': 4,
'num_heads': 2,
'dropout': 0.1,
}
ARGS = {
'x': torch.randn(2, 3, 4),
'context': torch.randn(2, 5, 4),
'context_mask': torch.tensor([[True, True, True, True, False], [True, True, False, False, False]]),
}
# Construct and call
model = CrossAttentionConditioner(**INIT_ARGS)
output = model(**ARGS)
- Setup block drafted by
- a language model, class construct-then-call prompt, model not recorded
- Imports
- torch — import names as written, not package names to install; a name the repository itself provides is not a package
- Returned
- type Tensor, ndim 3, dtype family float, shape (2, 3, 4) — shape (2, 3, 4) as a later run recorded it
- dtype family
- int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
- Environment
- image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
|
| FingerprintEncoder |
Ran ran on a synthesized input |
VIKI623/MS-GPT/src/ms_gpt/models/conditional_mlm.py code served (permissive licence) · get_code("ed0edb0264d1759e") How it ranRan in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.
import torch
import torch.nn as nn
INIT_ARGS = {
'fp_bits': 64,
'd_model': 16,
'max_active_bits': 8,
'num_layers': 2,
'num_heads': 4,
'dropout': 0.1,
}
ARGS = {
'fingerprint': torch.randint(0, 2, (2, 64)).float(),
}
if __name__ == '__main__':
from typing import Optional, Tuple, Union
class FingerprintEncoder(nn.Module):
"""Encodes sparse Morgan fingerprint into dense sequence of embeddings."""
def __init__(self, fp_bits: int=4096, d_model: int=768, max_active_bits: int=256, num_layers: int=2, num_heads: int=8, dropout: float=0.1):
super().__init__()
self.fp_bits = fp_bits
self.max_active_bits = max_active_bits
self.d_model = d_model
self.bit_embedding = nn.Embedding(fp_bits, d_model)
self.value_proj = nn.Linear(1, d_model)
self.combine = nn.Linear(d_model * 2, d_model)
encoder_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=num_heads, dim_feedforward=d_model * 4, dropout=dropout, activation='gelu', batch_first=True, norm_first=True)
self.self_attn = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
self.norm = nn.LayerNorm(d_model)
def forward(self, fingerprint: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Args:
fingerprint: (batch, fp_bits) binary or soft fingerprint
Returns:
embeddings: (batch, seq_len, d_model) - active bit embeddings
mask: (batch, seq_len) - padding mask (True = valid)
"""
batch_size = fingerprint.shape[0]
device = fingerprint.device
embeddings_list = []
masks = []
for i in range(batch_size):
active_idx = fingerprint[i].nonzero(as_tuple=True)[0]
if len(active_idx) > self.max_active_bits:
active_idx = active_idx[:self.max_active_bits]
n_active = len(active_idx)
if n_active == 0:
active_idx = torch.zeros(1, dtype=torch.long, device=device)
n_active = 1
bit_emb = self.bit_embedding(active_idx)
val_emb = self.value_proj(fingerprint[i, active_idx].unsqueeze(-1))
combined = self.combine(torch.cat([bit_emb, val_emb], dim=-1))
pad_len = self.max_active_bits - n_active
if pad_len > 0:
padding = torch.zeros(pad_len, self.d_model, device=device)
combined = torch.cat([combined, padding], dim=0)
embeddings_list.append(combined)
mask = torch.cat([torch.ones(n_active, device=device, dtype=torch.bool), torch.zeros(pad_len, device=device, dtype=torch.bool)]) if pad_len > 0 else torch.ones(n_active, device=device, dtype=torch.bool)
masks.append(mask)
embeddings = torch.stack(embeddings_list)
mask = torch.stack(masks)
src_key_padding_mask = ~mask
embeddings = self.self_attn(embeddings, src_key_padding_mask=src_key_padding_mask)
embeddings = self.norm(embeddings)
return (embeddings, mask)
model = FingerprintEncoder(**INIT_ARGS)
output = model(**ARGS)
print(f"Output embeddings shape: {output[0].shape}")
print(f"Output mask shape: {output[1].shape}")
- Setup block drafted by
- a language model, class construct-then-call prompt, model not recorded
- Imports
- torch — import names as written, not package names to install; a name the repository itself provides is not a package
- Returned
- type tuple — a tuple output has no array shape of its own; none is stated
- Environment
- image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
|
| FormulaEncoder |
Ran ran on a synthesized input |
VIKI623/MS-GPT/src/ms_gpt/models/conditional_mlm.py code served (permissive licence) · get_code("52be847181a1ee5c") How it ranRan in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned Tensor, ndim 3, dtype family float, shape (2, 14, 4) as a later run recorded it. The image it ran in was not recorded. If your copy returns the same type, ndim and shape on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.
import torch
import torch.nn as nn
class FormulaEncoder(nn.Module):
"""Encodes molecular formula (element counts) into embeddings."""
ELEMENTS = ['C', 'H', 'N', 'O', 'S', 'P', 'F', 'Cl', 'Br', 'I', 'B', 'Si', 'Se', 'As']
def __init__(self, d_model: int=768, max_count: int=200):
super().__init__()
self.n_elements = len(self.ELEMENTS)
self.element_embedding = nn.Embedding(self.n_elements, d_model)
self.count_proj = nn.Sequential(nn.Linear(1, d_model), nn.GELU(), nn.Linear(d_model, d_model))
self.combine = nn.Linear(d_model * 2, d_model)
self.norm = nn.LayerNorm(d_model)
def forward(self, formula_vec: torch.Tensor) -> torch.Tensor:
"""
Args:
formula_vec: (batch, n_elements) element count vector
Returns:
(batch, n_elements, d_model) formula embeddings
"""
batch_size = formula_vec.shape[0]
device = formula_vec.device
elem_idx = torch.arange(self.n_elements, device=device).unsqueeze(0).expand(batch_size, -1)
elem_emb = self.element_embedding(elem_idx)
count_emb = self.count_proj(formula_vec.unsqueeze(-1))
combined = self.combine(torch.cat([elem_emb, count_emb], dim=-1))
return self.norm(combined)
INIT_ARGS = {
'd_model': 4,
'max_count': 200,
}
ARGS = {
'formula_vec': torch.randn(2, 14),
}
if __name__ == '__main__':
encoder = FormulaEncoder(**INIT_ARGS)
output = encoder(**ARGS)
print(f"Output shape: {output.shape}")
print(f"Expected shape: (2, 14, 4)")
- Setup block drafted by
- a language model, class construct-then-call prompt, model not recorded
- Imports
- torch — import names as written, not package names to install; a name the repository itself provides is not a package
- Returned
- type Tensor, ndim 3, dtype family float, shape (2, 14, 4) — shape (2, 14, 4) as a later run recorded it
- dtype family
- int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
- Environment
- image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
|
| SplitQKVMultiheadAttention |
Ran ran on a synthesized input |
VIKI623/MS-GPT/src/ms_gpt/models/conditional_mlm.py code served (permissive licence) · get_code("40c0bf0afe9be616") How it ranRan in Syntology's sandbox on this synthesized input (drafted by a language model, class construct-then-call prompt, model not recorded) and returned tuple. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.
import torch
import torch.nn as nn
INIT_ARGS = {
'embed_dim': 8,
'num_heads': 2,
'dropout': 0.1,
'bias': True,
}
ARGS = {
'query': torch.randn(2, 3, 8),
'key': torch.randn(2, 4, 8),
'value': torch.randn(2, 4, 8),
'key_padding_mask': None,
'need_weights': False,
}
if __name__ == '__main__':
from typing import Optional, Tuple, Union
class SplitQKVMultiheadAttention(nn.Module):
"""nn.MultiheadAttention with Q/K/V as separate Linear submodules.
Math is bit-identical to ``nn.MultiheadAttention(batch_first=True)`` so
that released checkpoints can transfer through ``normalize_mlm_checkpoint_state_dict``
without retraining. We expose q_proj / k_proj / v_proj as standalone
nn.Linear modules so peft LoRA can target them directly (the original
nn.MultiheadAttention bundles them in a single ``in_proj_weight``
parameter, which peft cannot target).
"""
def __init__(self, embed_dim: int, num_heads: int, dropout: float=0.0, bias: bool=True):
super().__init__()
if embed_dim % num_heads != 0:
raise ValueError(f'embed_dim {embed_dim} not divisible by num_heads {num_heads}')
self.embed_dim = embed_dim
self.num_heads = num_heads
self.head_dim = embed_dim // num_heads
self.scale = self.head_dim ** (-0.5)
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.attn_dropout = nn.Dropout(dropout)
def forward(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, key_padding_mask: Optional[torch.Tensor]=None, need_weights: bool=False) -> Tuple[torch.Tensor, None]:
B, Lq, _ = query.shape
Lk = key.shape[1]
q = self.q_proj(query).view(B, Lq, self.num_heads, self.head_dim).transpose(1, 2)
k = self.k_proj(key).view(B, Lk, self.num_heads, self.head_dim).transpose(1, 2)
v = self.v_proj(value).view(B, Lk, self.num_heads, self.head_dim).transpose(1, 2)
attn = torch.matmul(q * self.scale, k.transpose(-2, -1))
if key_padding_mask is not None:
attn = attn.masked_fill(key_padding_mask[:, None, None, :], float('-inf'))
attn = attn.softmax(dim=-1)
attn = self.attn_dropout(attn)
out = torch.matmul(attn, v).transpose(1, 2).reshape(B, Lq, self.embed_dim)
out = self.out_proj(out)
return (out, None)
model = SplitQKVMultiheadAttention(**INIT_ARGS)
output = model(**ARGS)
print(f"Output shape: {output[0].shape}")
print(f"Output weights: {output[1]}")
- Setup block drafted by
- a language model, class construct-then-call prompt, model not recorded
- Imports
- torch — import names as written, not package names to install; a name the repository itself provides is not a package
- Returned
- type tuple — a tuple output has no array shape of its own; none is stated
- Environment
- image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: torch and numpy seeded to 0 by the harness immediately before the class was constructed from INIT_ARGS (fixture_check.py)
|
| ConditionalMoleculeLanguageModel |
Not yet run unverified (harvested, no recorded run) |
VIKI623/MS-GPT/src/ms_gpt/models/conditional_mlm.py code served (permissive licence) · get_code("47b68d47b6b345db") How it ran |