| BERTAttention |
Ran ran on a synthesized input |
AlibabaResearch/DAMO-ConvAI/dial2vec/modeling_bert.py code served (permissive licence) · get_code("fa58498fdf4cb81e") 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
import math
class BERTLayerNorm(nn.Module):
def __init__(self, config, variance_epsilon=1e-12):
"""Construct a layernorm module in the TF style (epsilon inside the square root).
"""
super(BERTLayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(config.hidden_size))
self.beta = nn.Parameter(torch.zeros(config.hidden_size))
self.variance_epsilon = variance_epsilon
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.gamma * x + self.beta
class BERTSelfAttention(nn.Module):
def __init__(self, config):
super(BERTSelfAttention, self).__init__()
if config.hidden_size % config.num_attention_heads != 0:
raise ValueError('The hidden size (%d) is not a multiple of the number of attention heads (%d)' % (config.hidden_size, config.num_attention_heads))
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(self, hidden_states, attention_mask):
mixed_query_layer = self.query(hidden_states)
mixed_key_layer = self.key(hidden_states)
mixed_value_layer = self.value(hidden_states)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
attention_scores = attention_scores + attention_mask
attention_probs = nn.Softmax(dim=-1)(attention_scores)
attention_probs = self.dropout(attention_probs)
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
return context_layer
class BERTSelfOutput(nn.Module):
def __init__(self, config):
super(BERTSelfOutput, self).__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.LayerNorm = BERTLayerNorm(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class BERTAttention(nn.Module):
def __init__(self, config):
super(BERTAttention, self).__init__()
self.self = BERTSelfAttention(config)
self.output = BERTSelfOutput(config)
def forward(self, input_tensor, attention_mask):
self_output = self.self(input_tensor, attention_mask)
attention_output = self.output(self_output, input_tensor)
return attention_output
class Config:
def __init__(self):
self.hidden_size = 8
self.num_attention_heads = 2
self.attention_probs_dropout_prob = 0.1
self.hidden_dropout_prob = 0.1
config = Config()
INIT_ARGS = {
'config': config
}
batch_size = 2
seq_length = 5
hidden_size = config.hidden_size
input_tensor = torch.randn(batch_size, seq_length, hidden_size)
attention_mask = torch.zeros(batch_size, 1, 1, seq_length)
ARGS = {
'input_tensor': input_tensor,
'attention_mask': attention_mask
}
- 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)
|
| BERTEmbeddings |
Ran ran on a synthesized input |
AlibabaResearch/DAMO-ConvAI/dial2vec/modeling_bert.py code served (permissive licence) · get_code("fb68baf229e1cf5a") 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
class BERTLayerNorm(nn.Module):
def __init__(self, config, variance_epsilon=1e-12):
"""Construct a layernorm module in the TF style (epsilon inside the square root).
"""
super(BERTLayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(config.hidden_size))
self.beta = nn.Parameter(torch.zeros(config.hidden_size))
self.variance_epsilon = variance_epsilon
def forward(self, x):
u = x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.gamma * x + self.beta
class BERTEmbeddings(nn.Module):
"""
提供BERT embeddings
"""
def __init__(self, config):
super(BERTEmbeddings, self).__init__()
'Construct the embedding module from word, position and token_type embeddings.\n '
self.config = config
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size)
self.turn_embeddings = nn.Embedding(100, self.config.hidden_size)
self.role_embeddings = nn.Embedding(10, self.config.hidden_size)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
self.LayerNorm = BERTLayerNorm(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, input_ids, turn_ids, role_ids, position_ids, token_type_ids):
"""
前向编码过程
"""
if token_type_ids is None:
token_type_ids = torch.zeros_like(input_ids)
words_embeddings = self.word_embeddings(input_ids)
position_embeddings = self.position_embeddings(position_ids)
token_type_embeddings = self.token_type_embeddings(token_type_ids)
embeddings = words_embeddings + position_embeddings + token_type_embeddings
if turn_ids is not None:
embeddings += self.turn_embeddings(turn_ids)
if role_ids is not None:
embeddings += self.role_embeddings(role_ids)
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
class Config:
def __init__(self):
self.vocab_size = 32
self.hidden_size = 4
self.max_position_embeddings = 16
self.type_vocab_size = 3
self.hidden_dropout_prob = 0.1
INIT_ARGS = {
'config': Config()
}
ARGS = {
'input_ids': torch.randint(0, 32, (2, 5)),
'turn_ids': torch.randint(0, 100, (2, 5)),
'role_ids': torch.randint(0, 10, (2, 5)),
'position_ids': torch.randint(0, 16, (2, 5)),
'token_type_ids': torch.randint(0, 3, (2, 5))
}
if __name__ == '__main__':
model = BERTEmbeddings(**INIT_ARGS)
output = model(**ARGS)
print(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 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)
|
| BERTIntermediate |
Ran ran on a synthesized input · constructed an object; no result was computed |
AlibabaResearch/DAMO-ConvAI/dial2vec/modeling_bert.py code served (permissive licence) · get_code("c45a021ae43f1086") How it ranRan in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, BERTIntermediate: the run constructed the object and did not call it, so no result was computed. 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
torch.manual_seed(0)
class Config:
def __init__(self, hidden_size, intermediate_size):
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
config = Config(hidden_size=4, intermediate_size=3)
ARGS = {
"config": config
}
- Setup block drafted by
- a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
- Imports
- torch — import names as written, not package names to install; a name the repository itself provides is not a package
- Returned
- type BERTIntermediate — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a BERTIntermediate output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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: none by the harness; any seed is in the setup block
|
| BERTPooler |
Ran ran on a synthesized input · constructed an object; no result was computed |
AlibabaResearch/DAMO-ConvAI/dial2vec/modeling_bert.py code served (permissive licence) · get_code("ddd04d6d8b2852c9") How it ranRan in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, BERTPooler: the run constructed the object and did not call it, so no result was computed. 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
torch.manual_seed(0)
class Config:
def __init__(self, hidden_size):
self.hidden_size = hidden_size
config = Config(hidden_size=4)
hidden_states = torch.randn(2, 5, 4)
ARGS = {
"config": config
}
- Setup block drafted by
- a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
- Imports
- torch — import names as written, not package names to install; a name the repository itself provides is not a package
- Returned
- type BERTPooler — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a BERTPooler output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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: none by the harness; any seed is in the setup block
|
| BERTSelfAttention |
Ran ran on a synthesized input |
AlibabaResearch/DAMO-ConvAI/dial2vec/modeling_bert.py code served (permissive licence) · get_code("a5e5c3ae263c81ac") 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
class Config:
def __init__(self):
self.hidden_size = 8
self.num_attention_heads = 2
self.attention_probs_dropout_prob = 0.1
config = Config()
INIT_ARGS = {
'config': config
}
batch_size = 2
seq_length = 5
hidden_size = config.hidden_size
hidden_states = torch.randn(batch_size, seq_length, hidden_size)
# attention_mask should be added to attention scores, typically with large negative values for masked positions
# Shape: (batch_size, 1, 1, seq_length) or (batch_size, num_heads, seq_length, seq_length)
# Using (batch_size, 1, 1, seq_length) for broadcasting
attention_mask = torch.zeros(batch_size, 1, 1, seq_length)
ARGS = {
'hidden_states': hidden_states,
'attention_mask': attention_mask
}
- 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)
|
| BERTavg |
Ran ran on a synthesized input |
AlibabaResearch/DAMO-ConvAI/dial2vec/modeling_bert.py code served (permissive licence) · get_code("6c50f0691f85142a") 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; 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
class BERTavg(nn.Module):
"""
对BERT输出的embedding求masked average
"""
def __init__(self):
super(BERTavg, self).__init__()
def forward(self, hidden_states, attention_mask):
mul_mask = lambda x, m: x * torch.unsqueeze(m, dim=-1)
reduce_mean = lambda x, m: torch.sum(mul_mask(x, m), dim=1) / (torch.sum(m, dim=1, keepdims=True) + 1e-10)
avg_output = reduce_mean(hidden_states, attention_mask)
return avg_output
INIT_ARGS = {}
ARGS = {
'hidden_states': torch.randn(2, 5, 4),
'attention_mask': torch.tensor([[1, 1, 1, 0, 0], [1, 1, 1, 1, 0]], dtype=torch.float32)
}
if __name__ == '__main__':
model = BERTavg(**INIT_ARGS)
output = model(**ARGS)
print("Output shape:", output.shape)
print("Output:", 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 2, 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)
|
| BertConfig |
Ran ran on a synthesized input · constructed an object; no result was computed |
AlibabaResearch/DAMO-ConvAI/dial2vec/modeling_bert.py code served (permissive licence) · get_code("e64c9e8361c93aaa") How it ranRan in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, BertConfig: the run constructed the object and did not call it, so no result was computed. 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 copy
import json
import six
# Call the function to construct a BertConfig
class BertConfig(object):
"""Configuration class to store the configuration of a `BertModel`.
"""
def __init__(self, vocab_size, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.8, attention_probs_dropout_prob=0.8, max_position_embeddings=512, type_vocab_size=16, initializer_range=0.02):
"""Constructs BertConfig.
Args:
vocab_size: Vocabulary size of `inputs_ids` in `BertModel`.
hidden_size: Size of the encoder layers and the pooler layer.
num_hidden_layers: Number of hidden layers in the Transformer encoder.
num_attention_heads: Number of attention heads for each attention layer in
the Transformer encoder.
intermediate_size: The size of the "intermediate" (i.e., feed-forward)
layer in the Transformer encoder.
hidden_act: The non-linear activation function (function or string) in the
encoder and pooler.
hidden_dropout_prob: The dropout probabilitiy for all fully connected
layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob: The dropout ratio for the attention
probabilities.
max_position_embeddings: The maximum sequence length that this model might
ever be used with. Typically set this to something large just in case
(e.g., 512 or 1024 or 2048).
type_vocab_size: The vocabulary size of the `token_type_ids` passed into
`BertModel`.
initializer_range: The sttdev of the truncated_normal_initializer for
initializing all weight matrices.
"""
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
@classmethod
def from_dict(cls, json_object):
"""Constructs a `BertConfig` from a Python dictionary of parameters."""
config = BertConfig(vocab_size=None)
for key, value in six.iteritems(json_object):
config.__dict__[key] = value
return config
@classmethod
def from_json_file(cls, json_file):
"""Constructs a `BertConfig` from a json file of parameters."""
with open(json_file, 'r') as reader:
text = reader.read()
return cls.from_dict(json.loads(text))
def to_dict(self):
"""Serializes this instance to a Python dictionary."""
output = copy.deepcopy(self.__dict__)
return output
def to_json_string(self):
"""Serializes this instance to a JSON string."""
return json.dumps(self.to_dict(), indent=2, sort_keys=True) + '\n'
ARGS = {
'vocab_size': 30522,
'hidden_size': 768,
'num_hidden_layers': 12,
'num_attention_heads': 12,
'intermediate_size': 3072,
'hidden_act': 'gelu',
'hidden_dropout_prob': 0.1,
'attention_probs_dropout_prob': 0.1,
'max_position_embeddings': 512,
'type_vocab_size': 2,
'initializer_range': 0.02
}
- Setup block drafted by
- a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
- Imports
- six — import names as written, not package names to install; a name the repository itself provides is not a package
- Returned
- type BertConfig — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a BertConfig output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not 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: none by the harness; any seed is in the setup block
|
| BERTEncoder |
Not yet run unverified (harvested, no recorded run) |
AlibabaResearch/DAMO-ConvAI/dial2vec/modeling_bert.py code served (permissive licence) · get_code("2297486f7089cbcd") How it ran |
| BERTLayer |
Not yet run unverified (harvested, no recorded run) |
AlibabaResearch/DAMO-ConvAI/dial2vec/modeling_bert.py code served (permissive licence) · get_code("f3faae060e87ee86") How it ran |
| BertModel |
Not yet run unverified (harvested, no recorded run) |
AlibabaResearch/DAMO-ConvAI/dial2vec/modeling_bert.py code served (permissive licence) · get_code("a7725d578d6fc49c") How it ran |
| Dial2vec |
Not yet run unverified (harvested, no recorded run) |
AlibabaResearch/DAMO-ConvAI/dial2vec/modeling_bert.py code served (permissive licence) · get_code("da1e6c7924893059") How it ran |