| ClusterAssignmentEmbedder |
Ran ran on a synthesized input |
Q9gJYx/MixConfig/src/mixconfig/selector.py code served (permissive licence) · get_code("2aeaf67a16ac1228") 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
class ClusterAssignmentEmbedder(nn.Module):
"""
Embeds cluster assignments from each configuration into learnable vectors.
c_i = Embed_i(omega_i(x))
where omega_i(x) is the cluster assignment for sample x in configuration i.
Args:
n_configs: Number of configurations.
max_clusters: Maximum number of clusters per configuration.
embed_dim: Dimension of each cluster embedding.
"""
def __init__(self, n_configs: int, max_clusters: int, embed_dim: int=32):
super().__init__()
self.n_configs = n_configs
self.max_clusters = max_clusters
self.embed_dim = embed_dim
self.embeddings = nn.ModuleList([nn.Embedding(max_clusters, embed_dim) for _ in range(n_configs)])
for embed in self.embeddings:
nn.init.normal_(embed.weight, std=0.02)
def forward(self, cluster_assignments: torch.Tensor) -> torch.Tensor:
"""
Embed cluster assignments from all configurations.
Args:
cluster_assignments: Tensor of shape [batch_size, n_configs]
containing cluster indices for each sample and configuration.
Returns:
Embeddings of shape [batch_size, n_configs, embed_dim].
"""
batch_size = cluster_assignments.shape[0]
embeddings = []
for i, embed_layer in enumerate(self.embeddings):
indices = cluster_assignments[:, i].long()
emb = embed_layer(indices)
embeddings.append(emb)
return torch.stack(embeddings, dim=1)
def get_all_embeddings(self, config_idx: int) -> torch.Tensor:
"""
Get all cluster embeddings for a specific configuration.
Args:
config_idx: Index of the configuration.
Returns:
Embedding matrix of shape [max_clusters, embed_dim].
"""
return self.embeddings[config_idx].weight
INIT_ARGS = {
"n_configs": 3,
"max_clusters": 5,
"embed_dim": 4,
}
ARGS = {
"cluster_assignments": torch.randint(0, 5, (2, 3)),
}
if __name__ == "__main__":
model = ClusterAssignmentEmbedder(**INIT_ARGS)
output = model(**ARGS)
print("Output shape:", output.shape)
print("Output:", output)
all_emb = model.get_all_embeddings(0)
print("All embeddings shape:", all_emb.shape)
print("All embeddings:", all_emb)
- 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)
|
| EnergyStatistics |
Ran ran on a synthesized input |
Q9gJYx/MixConfig/src/mixconfig/selector.py code served (permissive licence) · get_code("de065fd64a18d5a3") 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
INIT_ARGS = {
'n_configs': 3,
'normalize': True,
}
ARGS = {
'features': torch.randn(2, 4),
'cluster_assignments': torch.tensor([[0, 1, 0], [1, 0, 1]]),
'n_clusters_per_config': torch.tensor([2, 2, 2]),
}
if __name__ == '__main__':
model = nn.Module()
from typing import Optional, Tuple
class EnergyStatistics(nn.Module):
"""
Computes energy statistics for each configuration.
For each configuration i, computes:
- H_i: Shannon entropy of cluster assignment distribution
- h_a^(i): Attractive energy (intra-cluster cohesion)
- h_r^(i): Repulsive energy (inter-cluster separation)
- delta_gamma_i: Energy gap (difference between min intra and max inter)
e_i = [H_i, h_a^(i), h_r^(i), delta_gamma_i]
Args:
n_configs: Number of configurations.
normalize: Whether to normalize energy statistics. Default: True.
"""
def __init__(self, n_configs: int, normalize: bool=True):
super().__init__()
self.n_configs = n_configs
self.normalize = normalize
self.energy_dim = 4
if normalize:
self.register_buffer('running_mean', torch.zeros(n_configs, self.energy_dim))
self.register_buffer('running_var', torch.ones(n_configs, self.energy_dim))
self.register_buffer('num_batches', torch.tensor(0))
def compute_entropy(self, cluster_assignments: torch.Tensor, n_clusters: int) -> torch.Tensor:
"""
Compute Shannon entropy of cluster distribution.
Args:
cluster_assignments: Cluster indices of shape [batch_size].
n_clusters: Number of possible clusters.
Returns:
Entropy value (scalar tensor).
"""
counts = torch.bincount(cluster_assignments.long(), minlength=n_clusters).float()
probs = counts / counts.sum()
probs = probs + 1e-10
entropy = -torch.sum(probs * torch.log(probs))
return entropy
def compute_energies(self, features: torch.Tensor, cluster_assignments: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""
Compute attractive and repulsive energies.
Args:
features: Sample features of shape [batch_size, feature_dim].
cluster_assignments: Cluster indices of shape [batch_size].
Returns:
Tuple of (attractive_energy, repulsive_energy, energy_gap).
"""
unique_clusters = torch.unique(cluster_assignments)
n_clusters = len(unique_clusters)
if n_clusters <= 1:
return (torch.tensor(0.0), torch.tensor(0.0), torch.tensor(0.0))
centroids = []
intra_distances = []
for c in unique_clusters:
mask = cluster_assignments == c
cluster_features = features[mask]
if len(cluster_features) > 0:
centroid = cluster_features.mean(dim=0)
centroids.append(centroid)
if len(cluster_features) > 1:
dists = torch.cdist(cluster_features.unsqueeze(0), centroid.unsqueeze(0).unsqueeze(0)).squeeze()
intra_distances.append(dists.mean())
centroids = torch.stack(centroids)
h_a = torch.stack(intra_distances).mean() if intra_distances else torch.tensor(0.0)
inter_dists = torch.cdist(centroids.unsqueeze(0), centroids.unsqueeze(0)).squeeze()
mask = torch.triu(torch.ones_like(inter_dists), diagonal=1).bool()
h_r = inter_dists[mask].mean() if mask.sum() > 0 else torch.tensor(0.0)
min_intra = torch.stack(intra_distances).min() if intra_distances else torch.tensor(0.0)
max_inter = inter_dists[mask].max() if mask.sum() > 0 else torch.tensor(0.0)
delta_gamma = max_inter - min_intra
return (h_a, h_r, delta_gamma)
def forward(self, features: torch.Tensor, cluster_assignments: torch.Tensor, n_clusters_per_config: Optional[torch.Tensor]=None) -> torch.Tensor:
"""
Compute energy statistics for all configurations.
Args:
features: Sample features of shape [batch_size, feature_dim].
cluster_assignments: Cluster assignments of shape [batch_size, n_configs].
n_clusters_per_config: Number of clusters per configuration.
Returns:
Energy statistics of shape [batch_size, n_configs, energy_dim].
"""
batch_size = features.shape[0]
device = features.device
energies = torch.zeros(batch_size, self.n_configs, self.energy_dim, device=device)
for i in range(self.n_configs):
config_assignments = cluster_assignments[:, i]
n_clusters = n_clusters_per_config[i] if n_clusters_per_config is not None else 100
H = self.compute_entropy(config_assignments, n_clusters)
h_a, h_r, delta_gamma = self.compute_energies(features, config_assignments)
energies[:, i, 0] = H
energies[:, i, 1] = h_a
energies[:, i, 2] = h_r
energies[:, i, 3] = delta_gamma
if self.normalize and self.training:
batch_mean = energies.mean(dim=0)
batch_var = energies.var(dim=0)
self.running_mean = self.running_mean * 0.99 + batch_mean * 0.01
self.running
- 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)
|
| SampleContextEncoder |
Ran ran on a synthesized input |
Q9gJYx/MixConfig/src/mixconfig/selector.py code served (permissive licence) · get_code("9dac6d849320c8a2") 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 2, dtype family float, shape (2, 3) 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
INIT_ARGS = {
'input_dim': 4,
'hidden_dims': [16, 8],
'output_dim': 3,
'activation': nn.ReLU,
'dropout': 0.1,
'norm_layer': nn.LayerNorm,
}
ARGS = {
'x': torch.randn(2, 4),
}
if __name__ == '__main__':
from typing import Optional, Tuple, List, Callable
class SampleContextEncoder(nn.Module):
"""
MLP encoder that maps raw sample features to a context embedding.
h = MLP_enc(x)
Args:
input_dim: Dimension of input features.
hidden_dims: List of hidden layer dimensions.
output_dim: Dimension of the context embedding.
activation: Activation function class. Default: nn.ReLU.
dropout: Dropout probability. Default: 0.1.
norm_layer: Optional normalization layer class.
"""
def __init__(self, input_dim: int, hidden_dims: List[int]=[256, 128], output_dim: int=64, activation: Callable[..., nn.Module]=nn.ReLU, dropout: float=0.1, norm_layer: Optional[Callable[..., nn.Module]]=nn.LayerNorm):
super().__init__()
layers = []
prev_dim = input_dim
for hidden_dim in hidden_dims:
layers.append(nn.Linear(prev_dim, hidden_dim))
if norm_layer is not None:
layers.append(norm_layer(hidden_dim))
layers.append(activation())
layers.append(nn.Dropout(dropout))
prev_dim = hidden_dim
layers.append(nn.Linear(prev_dim, output_dim))
self.encoder = nn.Sequential(*layers)
self.output_dim = output_dim
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Encode sample features to context embedding.
Args:
x: Input features of shape [batch_size, input_dim].
Returns:
Context embedding of shape [batch_size, output_dim].
"""
return self.encoder(x)
model = SampleContextEncoder(**INIT_ARGS)
output = model(**ARGS)
print(f"Output shape: {output.shape}")
print(f"Expected shape: (2, 3)")
assert output.shape == (2, 3), f"Shape mismatch: {output.shape} != (2, 3)"
print("Test passed!")
- 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 2, dtype family float, shape (2, 3) — shape (2, 3) 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)
|
| EnergyAwareSelector |
Not yet run unverified (harvested, no recorded run) |
Q9gJYx/MixConfig/src/mixconfig/selector.py code served (permissive licence) · get_code("a8a3fc5959367524") How it ran |
| MixConfigPredictor |
Not yet run unverified (harvested, no recorded run) |
Q9gJYx/MixConfig/src/mixconfig/selector.py code served (permissive licence) · get_code("619506395076bf2b") How it ran |