| DualHeadDecoder |
Ran ran on a synthesized input |
raviteja-bommireddy/PhaseNet/IS_Project/model/phasenet.py code served (permissive licence) · get_code("3630e69fa0426441") 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
import math
D_MODEL = 256
NUM_SENSORS = 51
N_FFT = 128
FREQ_BINS = N_FFT // 2 + 1
class DualHeadDecoder(nn.Module):
"""
Dual-head decoder: separate branches for magnitude and phase reconstruction.
• Magnitude head uses ReLU to enforce non-negativity.
• Phase head uses Tanh × π to bound output to [−π, π].
"""
def __init__(self, d_model: int=D_MODEL, num_sensors: int=NUM_SENSORS, freq_bins: int=FREQ_BINS):
super().__init__()
self.num_sensors = num_sensors
self.freq_bins = freq_bins
out_features = num_sensors * freq_bins
self.mag_decoder = nn.Sequential(nn.Linear(d_model, d_model), nn.GELU(), nn.Linear(d_model, out_features))
self.phase_decoder = nn.Sequential(nn.Linear(d_model, d_model), nn.GELU(), nn.Linear(d_model, out_features))
def forward(self, z: torch.Tensor) -> tuple:
"""
Args:
z: (B, d_model) latent representation
Returns:
mag_hat: (B, C, F) — reconstructed magnitudes (non-negative)
phase_hat: (B, C, F) — reconstructed phases in [−π, π]
"""
B = z.size(0)
mag_hat = self.mag_decoder(z)
mag_hat = mag_hat.view(B, self.num_sensors, self.freq_bins)
mag_hat = torch.relu(mag_hat)
phase_hat = self.phase_decoder(z)
phase_hat = phase_hat.view(B, self.num_sensors, self.freq_bins)
phase_hat = torch.tanh(phase_hat) * math.pi
return (mag_hat, phase_hat)
INIT_ARGS = {
'd_model': 4,
'num_sensors': 3,
'freq_bins': 5,
}
ARGS = {
'z': torch.randn(2, 4),
}
if __name__ == '__main__':
model = DualHeadDecoder(**INIT_ARGS)
mag_hat, phase_hat = model(**ARGS)
print(f"mag_hat shape: {mag_hat.shape}")
print(f"phase_hat shape: {phase_hat.shape}")
print(f"mag_hat min/max: {mag_hat.min():.4f} / {mag_hat.max():.4f}")
print(f"phase_hat min/max: {phase_hat.min():.4f} / {phase_hat.max():.4f}")
- 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)
|
| GATLayer |
Ran ran on a synthesized input |
raviteja-bommireddy/PhaseNet/IS_Project/model/phasenet.py code served (permissive licence) · get_code("3d62167cc1d927ed") 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, 16) 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
N_HEADS = 8
class GATLayer(nn.Module):
"""
Single Graph Attention layer with PCI-modulated attention.
For memory efficiency, attention is computed as:
1. Project nodes to queries/keys/values per head
2. Compute attention scores (QK^T / sqrt(d_k))
3. Modulate by PCI adjacency matrix
4. Softmax + aggregate values
"""
def __init__(self, in_dim: int, out_dim: int, n_heads: int=N_HEADS, dropout: float=0.1, concat: bool=True):
super().__init__()
self.n_heads = n_heads
self.concat = concat
if concat:
assert out_dim % n_heads == 0, 'out_dim must be divisible by n_heads when concatenating'
self.d_k = out_dim // n_heads
else:
self.d_k = out_dim
self.W_q = nn.Linear(in_dim, n_heads * self.d_k, bias=False)
self.W_k = nn.Linear(in_dim, n_heads * self.d_k, bias=False)
self.W_v = nn.Linear(in_dim, n_heads * self.d_k, bias=False)
self.attn_drop = nn.Dropout(dropout)
self.leaky_relu = nn.LeakyReLU(0.2)
if concat:
self.out_proj = nn.Linear(n_heads * self.d_k, out_dim)
else:
self.out_proj = nn.Linear(self.d_k, out_dim)
def forward(self, x: torch.Tensor, adj: torch.Tensor) -> torch.Tensor:
"""
Args:
x: (B, C, in_dim)
adj: (B, C, C) — PCI adjacency matrix
Returns:
out: (B, C, out_dim)
"""
B, C, _ = x.shape
H, D = (self.n_heads, self.d_k)
Q = self.W_q(x).view(B, C, H, D).permute(0, 2, 1, 3)
K = self.W_k(x).view(B, C, H, D).permute(0, 2, 1, 3)
V = self.W_v(x).view(B, C, H, D).permute(0, 2, 1, 3)
scores = torch.matmul(Q, K.transpose(-2, -1)) / D ** 0.5
scores = scores * adj.unsqueeze(1)
scores = self.leaky_relu(scores)
attn = torch.nn.functional.softmax(scores, dim=-1)
attn = self.attn_drop(attn)
out = torch.matmul(attn, V)
if self.concat:
out = out.permute(0, 2, 1, 3).reshape(B, C, H * D)
else:
out = out.mean(dim=1)
out = self.out_proj(out)
return out
INIT_ARGS = {
'in_dim': 4,
'out_dim': 16,
'n_heads': 8,
'dropout': 0.1,
'concat': True,
}
ARGS = {
'x': torch.randn(2, 3, 4),
'adj': torch.ones(2, 3, 3),
}
if __name__ == '__main__':
layer = GATLayer(**INIT_ARGS)
output = layer(**ARGS)
print(f"Output shape: {output.shape}")
print(f"Expected shape: (2, 3, 16)")
assert output.shape == (2, 3, 16), f"Shape mismatch: {output.shape}"
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 3, dtype family float, shape (2, 3, 16) — shape (2, 3, 16) 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)
|
| PhaseCoherenceGAT |
Ran ran on a synthesized input |
raviteja-bommireddy/PhaseNet/IS_Project/model/phasenet.py code served (permissive licence) · get_code("43a6ba7c159ef913") 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, 16) 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 torch.nn.functional as F
EMBED_DIM = 128
N_HEADS = 8
class GATLayer(nn.Module):
"""
Single Graph Attention layer with PCI-modulated attention.
For memory efficiency, attention is computed as:
1. Project nodes to queries/keys/values per head
2. Compute attention scores (QK^T / sqrt(d_k))
3. Modulate by PCI adjacency matrix
4. Softmax + aggregate values
"""
def __init__(self, in_dim: int, out_dim: int, n_heads: int=N_HEADS, dropout: float=0.1, concat: bool=True):
super().__init__()
self.n_heads = n_heads
self.concat = concat
if concat:
assert out_dim % n_heads == 0, 'out_dim must be divisible by n_heads when concatenating'
self.d_k = out_dim // n_heads
else:
self.d_k = out_dim
self.W_q = nn.Linear(in_dim, n_heads * self.d_k, bias=False)
self.W_k = nn.Linear(in_dim, n_heads * self.d_k, bias=False)
self.W_v = nn.Linear(in_dim, n_heads * self.d_k, bias=False)
self.attn_drop = nn.Dropout(dropout)
self.leaky_relu = nn.LeakyReLU(0.2)
if concat:
self.out_proj = nn.Linear(n_heads * self.d_k, out_dim)
else:
self.out_proj = nn.Linear(self.d_k, out_dim)
def forward(self, x: torch.Tensor, adj: torch.Tensor) -> torch.Tensor:
"""
Args:
x: (B, C, in_dim)
adj: (B, C, C) — PCI adjacency matrix
Returns:
out: (B, C, out_dim)
"""
B, C, _ = x.shape
H, D = (self.n_heads, self.d_k)
Q = self.W_q(x).view(B, C, H, D).permute(0, 2, 1, 3)
K = self.W_k(x).view(B, C, H, D).permute(0, 2, 1, 3)
V = self.W_v(x).view(B, C, H, D).permute(0, 2, 1, 3)
scores = torch.matmul(Q, K.transpose(-2, -1)) / D ** 0.5
scores = scores * adj.unsqueeze(1)
scores = self.leaky_relu(scores)
attn = F.softmax(scores, dim=-1)
attn = self.attn_drop(attn)
out = torch.matmul(attn, V)
if self.concat:
out = out.permute(0, 2, 1, 3).reshape(B, C, H * D)
else:
out = out.mean(dim=1)
out = self.out_proj(out)
return out
class PhaseCoherenceGAT(nn.Module):
"""
Two-layer GAT with PCI-modulated attention.
GAT Layer 1: Multi-head (8 heads), concat aggregation
GAT Layer 2: Multi-head (8 heads), concat aggregation + LeakyReLU
"""
def __init__(self, embed_dim: int=EMBED_DIM, n_heads: int=N_HEADS):
super().__init__()
self.gat1 = GATLayer(embed_dim, embed_dim, n_heads=n_heads, concat=True)
self.norm1 = nn.LayerNorm(embed_dim)
self.gat2 = GATLayer(embed_dim, embed_dim, n_heads=n_heads, concat=True)
self.norm2 = nn.LayerNorm(embed_dim)
self.act = nn.LeakyReLU(0.2)
def forward(self, x: torch.Tensor, adj: torch.Tensor) -> torch.Tensor:
"""
Args:
x: (B, C, D)
adj: (B, C, C)
Returns:
out: (B, C, D)
"""
residual = x
x = self.gat1(x, adj)
x = self.norm1(x + residual)
residual = x
x = self.gat2(x, adj)
x = self.act(x)
x = self.norm2(x + residual)
return x
INIT_ARGS = {
'embed_dim': 16,
'n_heads': 8,
}
ARGS = {
'x': torch.randn(2, 3, 16),
'adj': torch.ones(2, 3, 3),
}
if __name__ == '__main__':
model = PhaseCoherenceGAT(**INIT_ARGS)
output = model(**ARGS)
print(f"Output shape: {output.shape}")
print(f"Expected shape: (2, 3, 16)")
assert output.shape == (2, 3, 16), f"Shape mismatch: got {output.shape}"
print("Success!")
- 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, 16) — shape (2, 3, 16) 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)
|
| PositionalEncoding |
Ran ran on a synthesized input |
raviteja-bommireddy/PhaseNet/IS_Project/model/phasenet.py code served (permissive licence) · get_code("66dd29c51076ad1c") 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, 8, 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 math
class PositionalEncoding(nn.Module):
"""Standard sine/cosine positional encoding."""
def __init__(self, d_model: int, max_len: int=512):
super().__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float32).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2, dtype=torch.float32) * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""x: (B, S, d_model)"""
return x + self.pe[:, :x.size(1)]
INIT_ARGS = {
'd_model': 4,
'max_len': 16
}
ARGS = {
'x': torch.randn(2, 8, 4)
}
if __name__ == '__main__':
model = PositionalEncoding(**INIT_ARGS)
output = model(**ARGS)
print(f"Input shape: {ARGS['x'].shape}")
print(f"Output shape: {output.shape}")
print(f"Output:\n{output}")
- 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, 8, 4) — shape (2, 8, 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)
|
| TemporalTransformerEncoder |
Ran ran on a synthesized input |
raviteja-bommireddy/PhaseNet/IS_Project/model/phasenet.py code served (permissive licence) · get_code("98c9b99d5a2f057a") 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, 8) 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 math
DROPOUT = 0.2
D_MODEL = 256
EMBED_DIM = 128
FFN_EXPANSION = 4
NUM_SENSORS = 51
NUM_TRANSFORMER_LAYERS = 4
N_HEADS = 8
class PositionalEncoding(nn.Module):
"""Standard sine/cosine positional encoding."""
def __init__(self, d_model: int, max_len: int=512):
super().__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float32).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2, dtype=torch.float32) * (-math.log(10000.0) / d_model))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
pe = pe.unsqueeze(0)
self.register_buffer('pe', pe)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""x: (B, S, d_model)"""
return x + self.pe[:, :x.size(1)]
class TemporalTransformerEncoder(nn.Module):
"""
Processes the C sensor embeddings as a sequence (treating sensors as tokens).
Steps:
1. Linear projection: C*D → d_model (or D → d_model per sensor)
2. Positional Encoding
3. N Transformer Encoder layers
4. Mean pooling → (B, d_model)
"""
def __init__(self, num_sensors: int=NUM_SENSORS, embed_dim: int=EMBED_DIM, d_model: int=D_MODEL, n_heads: int=N_HEADS, num_layers: int=NUM_TRANSFORMER_LAYERS, ffn_expansion: int=FFN_EXPANSION, dropout: float=DROPOUT):
super().__init__()
self.num_sensors = num_sensors
self.d_model = d_model
self.input_proj = nn.Linear(embed_dim, d_model)
self.pos_enc = PositionalEncoding(d_model, max_len=num_sensors + 1)
encoder_layer = nn.TransformerEncoderLayer(d_model=d_model, nhead=n_heads, dim_feedforward=d_model * ffn_expansion, dropout=dropout, activation='gelu', batch_first=True, norm_first=True)
self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=num_layers)
self.norm = nn.LayerNorm(d_model)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Args:
x: (B, C, D) — graph-fused sensor embeddings
Returns:
latent: (B, d_model)
"""
x = self.input_proj(x)
x = self.pos_enc(x)
x = self.encoder(x)
x = self.norm(x)
x = x.mean(dim=1)
return x
INIT_ARGS = {
'num_sensors': 6,
'embed_dim': 4,
'd_model': 8,
'n_heads': 2,
'num_layers': 2,
'ffn_expansion': 4,
'dropout': 0.1,
}
ARGS = {
'x': torch.randn(2, 6, 4),
}
if __name__ == '__main__':
model = TemporalTransformerEncoder(**INIT_ARGS)
output = model(**ARGS)
print(f"Output shape: {output.shape}")
print(f"Expected shape: (2, 8)")
- 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, 8) — shape (2, 8) 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)
|
| TimeFrequencyEmbedding |
Ran ran on a synthesized input |
raviteja-bommireddy/PhaseNet/IS_Project/model/phasenet.py code served (permissive licence) · get_code("2ae555b550024d90") 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, 4, 128) 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 torch.nn.functional as F
EMBED_DIM = 128
N_FFT = 128
FREQ_BINS = N_FFT // 2 + 1
class TimeFrequencyEmbedding(nn.Module):
"""
CNN-based spectral feature extractor applied independently per sensor.
Architecture:
Conv1D(2→16, k=3, pad=1) → BN → GeLU
Conv1D(16→32, k=3, pad=1) → BN → GeLU
MaxPool1D(k=2)
Flatten + Linear → D
"""
def __init__(self, freq_bins: int=FREQ_BINS, embed_dim: int=EMBED_DIM):
super().__init__()
self.freq_bins = freq_bins
self.embed_dim = embed_dim
self.conv = nn.Sequential(nn.Conv1d(2, 16, kernel_size=3, padding=1), nn.BatchNorm1d(16), nn.GELU(), nn.Conv1d(16, 32, kernel_size=3, padding=1), nn.BatchNorm1d(32), nn.GELU(), nn.MaxPool1d(kernel_size=2))
pooled_F = freq_bins // 2
self.fc = nn.Linear(32 * pooled_F, embed_dim)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Args:
x: (B, C, 2, F)
Returns:
embeddings: (B, C, D)
"""
B, C, _, F = x.shape
x = x.reshape(B * C, 2, F)
x = self.conv(x)
x = x.reshape(B * C, -1)
x = self.fc(x)
return x.reshape(B, C, self.embed_dim)
INIT_ARGS = {
'freq_bins': 65,
'embed_dim': 128,
}
ARGS = {
'x': torch.randn(2, 4, 2, 65),
}
if __name__ == '__main__':
model = TimeFrequencyEmbedding(**INIT_ARGS)
output = model(**ARGS)
print(f"Output shape: {output.shape}")
print(f"Expected shape: (2, 4, 128)")
assert output.shape == (2, 4, 128), f"Shape mismatch: {output.shape}"
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 3, dtype family float, shape (2, 4, 128) — shape (2, 4, 128) 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)
|
| PhaseNetPP |
Not yet run unverified (harvested, no recorded run) |
raviteja-bommireddy/PhaseNet/IS_Project/model/phasenet.py code served (permissive licence) · get_code("3abcdbeda780c3e2") How it ran |