| Block |
Ran ran on a synthesized input |
Giovanni-Sforza/MaskPoint-AMPT/models/MaskPoint.py code served (permissive licence) · get_code("4d94ec6274a40f2c") 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, 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
from timm.models.layers import DropPath
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** (-0.5)
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = (qkv[0], qkv[1], qkv[2])
attn = q @ k.transpose(-2, -1) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
def forward(self, x):
x = x + self.drop_path(self.attn(self.norm1(x)))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
INIT_ARGS = {
'dim': 8,
'num_heads': 2,
'mlp_ratio': 4.0,
'qkv_bias': False,
'qk_scale': None,
'drop': 0.0,
'attn_drop': 0.0,
'drop_path': 0.0,
'act_layer': nn.GELU,
'norm_layer': nn.LayerNorm,
}
ARGS = {
'x': torch.randn(2, 3, 8),
}
if __name__ == '__main__':
block = Block(**INIT_ARGS)
output = block(**ARGS)
print(f"Output shape: {output.shape}")
print(f"Expected shape: {ARGS['x'].shape}")
assert output.shape == ARGS['x'].shape, "Output shape mismatch"
print("Success!")
- Setup block drafted by
- a language model, class construct-then-call prompt, model not recorded
- Imports
- timm, 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, 8) — shape (2, 3, 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)
|
| Conv2d |
Ran ran on a synthesized input |
Giovanni-Sforza/MaskPoint-AMPT/models/MaskPoint.py code served (permissive licence) · get_code("64ccb0213c04a3a6") 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 4, dtype family float, shape (2, 4, 8, 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
from torch.nn import init
# Import the classes
import torch.nn as nn
from torch.nn import init
from typing import List, Tuple
class _BNBase(nn.Sequential):
def __init__(self, in_size, batch_norm=None, name=''):
super().__init__()
self.add_module(name + 'bn', batch_norm(in_size))
nn.init.constant_(self[0].weight, 1.0)
nn.init.constant_(self[0].bias, 0)
class _ConvBase(nn.Sequential):
def __init__(self, in_size, out_size, kernel_size, stride, padding, activation, bn, init, conv=None, batch_norm=None, bias=True, preact=False, name=''):
super().__init__()
bias = bias and (not bn)
conv_unit = conv(in_size, out_size, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)
init(conv_unit.weight)
if bias:
nn.init.constant_(conv_unit.bias, 0)
if bn:
if not preact:
bn_unit = batch_norm(out_size)
else:
bn_unit = batch_norm(in_size)
if preact:
if bn:
self.add_module(name + 'bn', bn_unit)
if activation is not None:
self.add_module(name + 'activation', activation)
self.add_module(name + 'conv', conv_unit)
if not preact:
if bn:
self.add_module(name + 'bn', bn_unit)
if activation is not None:
self.add_module(name + 'activation', activation)
class BatchNorm2d(_BNBase):
def __init__(self, in_size: int, name: str=''):
super().__init__(in_size, batch_norm=nn.BatchNorm2d, name=name)
class Conv2d(_ConvBase):
def __init__(self, in_size: int, out_size: int, *, kernel_size: Tuple[int, int]=(1, 1), stride: Tuple[int, int]=(1, 1), padding: Tuple[int, int]=(0, 0), activation=nn.ReLU(inplace=True), bn: bool=False, init=nn.init.kaiming_normal_, bias: bool=True, preact: bool=False, name: str=''):
super().__init__(in_size, out_size, kernel_size, stride, padding, activation, bn, init, conv=nn.Conv2d, batch_norm=BatchNorm2d, bias=bias, preact=preact, name=name)
INIT_ARGS = {
'in_size': 3,
'out_size': 4,
'kernel_size': (3, 3),
'stride': (1, 1),
'padding': (1, 1),
'activation': nn.ReLU(inplace=True),
'bn': False,
'init': nn.init.kaiming_normal_,
'bias': True,
'preact': False,
'name': ''
}
ARGS = {
'input': torch.randn(2, 3, 8, 8)
}
if __name__ == '__main__':
model = Conv2d(**INIT_ARGS)
output = model(**ARGS)
print(f"Input shape: {ARGS['input'].shape}")
print(f"Output shape: {output.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 Tensor, ndim 4, dtype family float, shape (2, 4, 8, 8) — shape (2, 4, 8, 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)
|
| CrossAttention |
Ran ran on a synthesized input |
Giovanni-Sforza/MaskPoint-AMPT/models/MaskPoint.py code served (permissive licence) · get_code("eecd5279cc0854b7") 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 = {
'dim': 4,
'num_heads': 2,
'qkv_bias': False,
'qk_scale': None,
'attn_drop': 0.1,
'proj_drop': 0.1,
}
ARGS = {
'x_q': torch.randn(2, 3, 4),
'x_k': torch.randn(2, 5, 4),
'x_v': torch.randn(2, 5, 4),
}
class CrossAttention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** (-0.5)
self.q_proj = nn.Linear(dim, dim, bias=qkv_bias)
self.k_proj = nn.Linear(dim, dim, bias=qkv_bias)
self.v_proj = nn.Linear(dim, dim, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x_q, x_k, x_v):
B, N, C = x_q.shape
q = self.q_proj(x_q).reshape(B, -1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
k = self.k_proj(x_k).reshape(B, -1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
v = self.v_proj(x_v).reshape(B, -1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
attn = q @ k.transpose(-2, -1) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, -1, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
if __name__ == '__main__':
model = CrossAttention(**INIT_ARGS)
output = model(**ARGS)
print(f"Output shape: {output.shape}")
print(f"Expected shape: (2, 3, 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, 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)
|
| CrossAttnBlock |
Ran ran on a synthesized input |
Giovanni-Sforza/MaskPoint-AMPT/models/MaskPoint.py code served (permissive licence) · get_code("62f5ed824cc9aaae") 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
from timm.models.layers import DropPath
class CrossAttention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** (-0.5)
self.q_proj = nn.Linear(dim, dim, bias=qkv_bias)
self.k_proj = nn.Linear(dim, dim, bias=qkv_bias)
self.v_proj = nn.Linear(dim, dim, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x_q, x_k, x_v):
B, N, C = x_q.shape
q = self.q_proj(x_q).reshape(B, -1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
k = self.k_proj(x_k).reshape(B, -1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
v = self.v_proj(x_v).reshape(B, -1, self.num_heads, C // self.num_heads).permute(0, 2, 1, 3)
attn = q @ k.transpose(-2, -1) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, -1, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class CrossAttnBlock(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.attn = CrossAttention(dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
def forward(self, x, pos, mem, mem_pos):
x = x + self.drop_path(self.attn(self.norm1(x) + pos, mem + mem_pos, mem))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
INIT_ARGS = {
'dim': 4,
'num_heads': 2,
'mlp_ratio': 4.0,
'qkv_bias': False,
'qk_scale': None,
'drop': 0.0,
'attn_drop': 0.0,
'drop_path': 0.0,
'act_layer': nn.GELU,
'norm_layer': nn.LayerNorm,
}
ARGS = {
'x': torch.randn(2, 3, 4),
'pos': torch.randn(2, 3, 4),
'mem': torch.randn(2, 5, 4),
'mem_pos': torch.randn(2, 5, 4),
}
if __name__ == '__main__':
model = CrossAttnBlock(**INIT_ARGS)
output = model(**ARGS)
print(f"Output shape: {output.shape}")
print(f"Expected shape: {ARGS['x'].shape}")
assert output.shape == ARGS['x'].shape, f"Shape mismatch: {output.shape} vs {ARGS['x'].shape}"
print("Test passed!")
- Setup block drafted by
- a language model, class construct-then-call prompt, model not recorded
- Imports
- timm, 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)
|
| SharedMLP |
Ran ran on a synthesized input |
Giovanni-Sforza/MaskPoint-AMPT/models/MaskPoint.py code served (permissive licence) · get_code("d15cfc72b540ff02") 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 4, dtype family float, shape (2, 16, 3, 5) 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
from typing import List, Tuple
# Import the classes from the provided code
import torch.nn as nn
from typing import List
from torch.nn import init
from typing import List, Tuple
class _BNBase(nn.Sequential):
def __init__(self, in_size, batch_norm=None, name=''):
super().__init__()
self.add_module(name + 'bn', batch_norm(in_size))
nn.init.constant_(self[0].weight, 1.0)
nn.init.constant_(self[0].bias, 0)
class _ConvBase(nn.Sequential):
def __init__(self, in_size, out_size, kernel_size, stride, padding, activation, bn, init, conv=None, batch_norm=None, bias=True, preact=False, name=''):
super().__init__()
bias = bias and (not bn)
conv_unit = conv(in_size, out_size, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)
init(conv_unit.weight)
if bias:
nn.init.constant_(conv_unit.bias, 0)
if bn:
if not preact:
bn_unit = batch_norm(out_size)
else:
bn_unit = batch_norm(in_size)
if preact:
if bn:
self.add_module(name + 'bn', bn_unit)
if activation is not None:
self.add_module(name + 'activation', activation)
self.add_module(name + 'conv', conv_unit)
if not preact:
if bn:
self.add_module(name + 'bn', bn_unit)
if activation is not None:
self.add_module(name + 'activation', activation)
class BatchNorm2d(_BNBase):
def __init__(self, in_size: int, name: str=''):
super().__init__(in_size, batch_norm=nn.BatchNorm2d, name=name)
class Conv2d(_ConvBase):
def __init__(self, in_size: int, out_size: int, *, kernel_size: Tuple[int, int]=(1, 1), stride: Tuple[int, int]=(1, 1), padding: Tuple[int, int]=(0, 0), activation=nn.ReLU(inplace=True), bn: bool=False, init=nn.init.kaiming_normal_, bias: bool=True, preact: bool=False, name: str=''):
super().__init__(in_size, out_size, kernel_size, stride, padding, activation, bn, init, conv=nn.Conv2d, batch_norm=BatchNorm2d, bias=bias, preact=preact, name=name)
class SharedMLP(nn.Sequential):
def __init__(self, args: List[int], *, bn: bool=False, activation=nn.ReLU(inplace=True), preact: bool=False, first: bool=False, name: str=''):
super().__init__()
for i in range(len(args) - 1):
self.add_module(name + 'layer{}'.format(i), Conv2d(args[i], args[i + 1], bn=(not first or not preact or i != 0) and bn, activation=activation if not first or not preact or i != 0 else None, preact=preact))
INIT_ARGS = {
'args': [4, 8, 16],
'bn': False,
'activation': nn.ReLU(inplace=True),
'preact': False,
'first': False,
'name': ''
}
ARGS = {
'input': torch.randn(2, 4, 3, 5)
}
if __name__ == '__main__':
model = SharedMLP(**INIT_ARGS)
output = model(**ARGS)
print(f"Input shape: {ARGS['input'].shape}")
print(f"Output shape: {output.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 Tensor, ndim 4, dtype family float, shape (2, 16, 3, 5) — shape (2, 16, 3, 5) 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)
|
| TransformerDecoder |
Ran ran on a synthesized input |
Giovanni-Sforza/MaskPoint-AMPT/models/MaskPoint.py code served (permissive licence) · get_code("63629fb929255f2a") 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; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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 numpy as np
from timm.models.layers import DropPath
INIT_ARGS = {
'embed_dim': 4,
'depth': 2,
'num_heads': 2,
'mlp_ratio': 2.0,
'qkv_bias': False,
'qk_scale': None,
'drop_rate': 0.0,
'attn_drop_rate': 0.0,
'drop_path_rate': 0.0
}
# Create input tensors
B, N_q, N_kv, C = 2, 3, 4, 4 # batch, query_len, key_value_len, embed_dim
x = torch.randn(B, N_q, C)
pos = torch.randn(B, N_q, C)
mem = torch.randn(B, N_kv, C)
mem_pos = torch.randn(B, N_kv, C)
ARGS = {
'x': x,
'pos': pos,
'mem': mem,
'mem_pos': mem_pos
}
- Setup block drafted by
- a language model, class construct-then-call prompt, model not recorded
- Imports
- numpy, timm, 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 — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
- 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)
|
| TransformerEncoder |
Ran ran on a synthesized input |
Giovanni-Sforza/MaskPoint-AMPT/models/MaskPoint.py code served (permissive licence) · get_code("9588659c897fcbf2") 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; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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
from timm.models.layers import DropPath
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class Attention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.0, proj_drop=0.0):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
self.scale = qk_scale or head_dim ** (-0.5)
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.attn_drop = nn.Dropout(attn_drop)
self.proj = nn.Linear(dim, dim)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x):
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
q, k, v = (qkv[0], qkv[1], qkv[2])
attn = q @ k.transpose(-2, -1) * self.scale
attn = attn.softmax(dim=-1)
attn = self.attn_drop(attn)
x = (attn @ v).transpose(1, 2).reshape(B, N, C)
x = self.proj(x)
x = self.proj_drop(x)
return x
class Block(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop=0.0, attn_drop=0.0, drop_path=0.0, act_layer=nn.GELU, norm_layer=nn.LayerNorm):
super().__init__()
self.norm1 = norm_layer(dim)
self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.attn = Attention(dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
def forward(self, x):
x = x + self.drop_path(self.attn(self.norm1(x)))
x = x + self.drop_path(self.mlp(self.norm2(x)))
return x
class TransformerEncoder(nn.Module):
def __init__(self, embed_dim=768, depth=4, num_heads=12, mlp_ratio=4.0, qkv_bias=False, qk_scale=None, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0):
super().__init__()
self.blocks = nn.ModuleList([Block(dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=drop_path_rate[i] if isinstance(drop_path_rate, list) else drop_path_rate) for i in range(depth)])
def forward(self, x, pos):
for _, block in enumerate(self.blocks):
x = block(x + pos)
return x
INIT_ARGS = {
'embed_dim': 4,
'depth': 2,
'num_heads': 2,
'mlp_ratio': 4.0,
'qkv_bias': False,
'qk_scale': None,
'drop_rate': 0.0,
'attn_drop_rate': 0.0,
'drop_path_rate': 0.0,
}
ARGS = {
'x': torch.randn(2, 3, 4),
'pos': torch.randn(2, 3, 4),
}
if __name__ == '__main__':
model = TransformerEncoder(**INIT_ARGS)
output = model(**ARGS)
print(f"Output shape: {output.shape}")
print(f"Expected shape: {ARGS['x'].shape}")
assert output.shape == ARGS['x'].shape, f"Shape mismatch: {output.shape} vs {ARGS['x'].shape}"
print("Success!")
- Setup block drafted by
- a language model, class construct-then-call prompt, model not recorded
- Imports
- timm, 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 — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
- 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)
|
| TransformerEncoderLayer |
Ran ran on a synthesized input |
Giovanni-Sforza/MaskPoint-AMPT/models/MaskPoint.py code served (permissive licence) · get_code("9d0fd8709fbd6207") 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; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim 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
from typing import Optional
from functools import partial
from torch import Tensor
ACTIVATION_DICT = {'relu': nn.ReLU, 'gelu': nn.GELU, 'leakyrelu': partial(nn.LeakyReLU, negative_slope=0.1)}
class BatchNormDim1Swap(nn.BatchNorm1d):
"""
Used for nn.Transformer that uses a HW x N x C rep
"""
def forward(self, x):
"""
x: HW x N x C
permute to N x C x HW
Apply BN on C
permute back
"""
hw, n, c = x.shape
x = x.permute(1, 2, 0)
x = super(BatchNormDim1Swap, self).forward(x)
x = x.permute(2, 0, 1)
return x
NORM_DICT = {'bn': BatchNormDim1Swap, 'bn1d': nn.BatchNorm1d, 'id': nn.Identity, 'ln': nn.LayerNorm}
class TransformerEncoderLayer(nn.Module):
def __init__(self, d_model, nhead=4, dim_feedforward=128, dropout=0.1, dropout_attn=None, activation='relu', normalize_before=True, norm_name='ln', use_ffn=True, ffn_use_bias=True):
super().__init__()
if dropout_attn is None:
dropout_attn = dropout
self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout_attn)
self.use_ffn = use_ffn
if self.use_ffn:
self.linear1 = nn.Linear(d_model, dim_feedforward, bias=ffn_use_bias)
self.dropout = nn.Dropout(dropout, inplace=True)
self.linear2 = nn.Linear(dim_feedforward, d_model, bias=ffn_use_bias)
self.norm2 = NORM_DICT[norm_name](d_model)
self.dropout2 = nn.Dropout(dropout, inplace=True)
self.norm1 = NORM_DICT[norm_name](d_model)
self.dropout1 = nn.Dropout(dropout, inplace=True)
self.activation = ACTIVATION_DICT[activation]()
self.normalize_before = normalize_before
self.nhead = nhead
self.use_norm_fn_on_input = False
def with_pos_embed(self, tensor, pos: Optional[Tensor]):
return tensor if pos is None else tensor + pos
def forward_post(self, src, src_mask: Optional[Tensor]=None, src_key_padding_mask: Optional[Tensor]=None, pos: Optional[Tensor]=None):
q = k = self.with_pos_embed(src, pos)
value = src
src2 = self.self_attn(q, k, value=value, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0]
src = src + self.dropout1(src2)
if self.use_norm_fn_on_input:
src = self.norm1(src)
if self.use_ffn:
src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
src = src + self.dropout2(src2)
src = self.norm2(src)
return src
def forward_pre(self, src, src_mask: Optional[Tensor]=None, src_key_padding_mask: Optional[Tensor]=None, pos: Optional[Tensor]=None, return_attn_weights: Optional[Tensor]=False):
src2 = self.norm1(src)
value = src2
q = k = self.with_pos_embed(src2, pos)
src2, attn_weights = self.self_attn(q, k, value=value, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)
src = src + self.dropout1(src2)
if self.use_ffn:
src2 = self.norm2(src)
src2 = self.linear2(self.dropout(self.activation(self.linear1(src2))))
src = src + self.dropout2(src2)
if return_attn_weights:
return (src, attn_weights)
return src
def forward(self, src, src_mask: Optional[Tensor]=None, src_key_padding_mask: Optional[Tensor]=None, pos: Optional[Tensor]=None, return_attn_weights: Optional[Tensor]=False):
if self.normalize_before:
return self.forward_pre(src, src_mask, src_key_padding_mask, pos, return_attn_weights)
return self.forward_post(src, src_mask, src_key_padding_mask, pos)
def extra_repr(self):
st = ''
if hasattr(self.self_attn, 'dropout'):
st += f'attn_dr={self.self_attn.dropout}'
return st
INIT_ARGS = {
'd_model': 4,
'nhead': 2,
'dim_feedforward': 8,
'dropout': 0.1,
'dropout_attn': None,
'activation': 'relu',
'normalize_before': True,
'norm_name': 'ln',
'use_ffn': True,
'ffn_use_bias': True,
}
ARGS = {
'src': torch.randn(3, 2, 4),
'src_mask': None,
'src_key_padding_mask': None,
'pos': None,
'return_attn_weights': False,
}
if __name__ == '__main__':
layer = TransformerEncoderLayer(**INIT_ARGS)
output = layer(**ARGS)
print("Output shape:", 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 — no output shape is stated: observe_signature.py observed this class with its constructor sizes canonicalised where it could, which the node does not record, so its shape is not stated as this setup block's
- 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)
|
| MaskPointTransformer |
Not yet run unverified (harvested, no recorded run) |
Giovanni-Sforza/MaskPoint-AMPT/models/MaskPoint.py code served (permissive licence) · get_code("f7949585b2bbd009") How it ran |
| PointnetSAModuleVotes |
Not yet run unverified (harvested, no recorded run) |
Giovanni-Sforza/MaskPoint-AMPT/models/MaskPoint.py code served (permissive licence) · get_code("23982f20d00ee0ae") How it ran |
| _ConvBase |
Not yet run unverified (harvested, no recorded run) |
Giovanni-Sforza/MaskPoint-AMPT/models/MaskPoint.py code served (permissive licence) · get_code("350b3898fc09eaa5") How it ran |