Initial commit
Browse files- adjacency_matrix/graph_dataset_comments.pkl +3 -0
- config.json +41 -0
- configuration_vgcn.py +33 -0
- modeling_vcgn.py +341 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +7 -0
- tokenizer.json +0 -0
- tokenizer_config.json +15 -0
- vocab.txt +0 -0
adjacency_matrix/graph_dataset_comments.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8c118066ba0ab7c65b4dced7681f41b41e3526789f343f932027945a1fc83626
|
| 3 |
+
size 111026916
|
config.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_probs_dropout_prob": 0.1,
|
| 3 |
+
"classifier_dropout": null,
|
| 4 |
+
"do_lower_case": 1,
|
| 5 |
+
"do_remove_accents": 0,
|
| 6 |
+
"gcn_adj_matrix": "adjacency_matrix/graph_dataset_comments.pkl",
|
| 7 |
+
"gcn_embedding_dim": 32,
|
| 8 |
+
"gradient_checkpointing": false,
|
| 9 |
+
"hidden_act": "gelu",
|
| 10 |
+
"hidden_dropout_prob": 0.1,
|
| 11 |
+
"hidden_size": 768,
|
| 12 |
+
"id2label": {
|
| 13 |
+
"0": "OTHER",
|
| 14 |
+
"1": "PROFANITY",
|
| 15 |
+
"2": "INSULT",
|
| 16 |
+
"3": "ABUSE"
|
| 17 |
+
},
|
| 18 |
+
"initializer_range": 0.02,
|
| 19 |
+
"intermediate_size": 3072,
|
| 20 |
+
"label2id": {
|
| 21 |
+
"ABUSE": 3,
|
| 22 |
+
"INSULT": 2,
|
| 23 |
+
"OTHER": 0,
|
| 24 |
+
"PROFANITY": 1
|
| 25 |
+
},
|
| 26 |
+
"layer_norm_eps": 1e-12,
|
| 27 |
+
"max_position_embeddings": 512,
|
| 28 |
+
"max_seq_len": 256,
|
| 29 |
+
"model_type": "vgcn",
|
| 30 |
+
"npmi_threshold": 0.2,
|
| 31 |
+
"num_attention_heads": 12,
|
| 32 |
+
"num_hidden_layers": 12,
|
| 33 |
+
"pad_token_id": 0,
|
| 34 |
+
"position_embedding_type": "absolute",
|
| 35 |
+
"tf_threshold": 0.0,
|
| 36 |
+
"transformers_version": "4.30.2",
|
| 37 |
+
"type_vocab_size": 2,
|
| 38 |
+
"use_cache": true,
|
| 39 |
+
"vocab_size": 37788,
|
| 40 |
+
"vocab_type": "pmi"
|
| 41 |
+
}
|
configuration_vgcn.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig, BertConfig
|
| 2 |
+
from typing import List
|
| 3 |
+
|
| 4 |
+
class VGCNConfig(BertConfig):
|
| 5 |
+
model_type = "vgcn"
|
| 6 |
+
|
| 7 |
+
def __init__(
|
| 8 |
+
self,
|
| 9 |
+
gcn_adj_matrix: str ='',
|
| 10 |
+
max_seq_len: int = 256,
|
| 11 |
+
npmi_threshold: float = 0.2,
|
| 12 |
+
tf_threshold: float = 0.0,
|
| 13 |
+
vocab_type: str = "all",
|
| 14 |
+
gcn_embedding_dim: int = 32,
|
| 15 |
+
**kwargs,
|
| 16 |
+
):
|
| 17 |
+
if vocab_type not in ["all", "pmi", "tf"]:
|
| 18 |
+
raise ValueError(f"`vocab_type` must be 'all', 'pmi' or 'tf', got {vocab_type}.")
|
| 19 |
+
if max_seq_len < 1 or max_seq_len > 512:
|
| 20 |
+
raise ValueError(f"`max_seq_len` must be between 1 and 512, got {max_seq_len}.")
|
| 21 |
+
if npmi_threshold < 0.0 or npmi_threshold > 1.0:
|
| 22 |
+
raise ValueError(f"`npmi_threshold` must be between 0.0 and 1.0, got {npmi_threshold}.")
|
| 23 |
+
if tf_threshold < 0.0 or tf_threshold > 1.0:
|
| 24 |
+
raise ValueError(f"`tf_threshold` must be between 0.0 and 1.0, got {tf_threshold}.")
|
| 25 |
+
|
| 26 |
+
self.gcn_adj_matrix = gcn_adj_matrix
|
| 27 |
+
self.max_seq_len = max_seq_len
|
| 28 |
+
self.npmi_threshold = npmi_threshold
|
| 29 |
+
self.tf_threshold = tf_threshold
|
| 30 |
+
self.vocab_type = vocab_type
|
| 31 |
+
self.gcn_embedding_dim = gcn_embedding_dim
|
| 32 |
+
|
| 33 |
+
super().__init__(**kwargs)
|
modeling_vcgn.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import PreTrainedModel, BertTokenizer
|
| 3 |
+
from transformers.utils import is_remote_url, download_url
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from configuration_vgcn import VGCNConfig
|
| 6 |
+
import pickle as pkl
|
| 7 |
+
import numpy as np
|
| 8 |
+
import scipy.sparse as sp
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def get_torch_gcn(gcn_vocab_adj_tf, gcn_vocab_adj,gcn_config:VGCNConfig):
|
| 14 |
+
|
| 15 |
+
def sparse_scipy2torch(coo_sparse):
|
| 16 |
+
# coo_sparse=coo_sparse.tocoo()
|
| 17 |
+
i = torch.LongTensor(np.vstack((coo_sparse.row, coo_sparse.col)))
|
| 18 |
+
v = torch.from_numpy(coo_sparse.data)
|
| 19 |
+
return torch.sparse.FloatTensor(i, v, torch.Size(coo_sparse.shape))
|
| 20 |
+
|
| 21 |
+
def normalize_adj(adj):
|
| 22 |
+
"""
|
| 23 |
+
Symmetrically normalize adjacency matrix.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
D_matrix = np.array(adj.sum(axis=1)) # D-degree matrix as array (Diagonal, rest is 0.)
|
| 27 |
+
D_inv_sqrt = np.power(D_matrix, -0.5).flatten()
|
| 28 |
+
D_inv_sqrt[np.isinf(D_inv_sqrt)] = 0.
|
| 29 |
+
d_mat_inv_sqrt = sp.diags(D_inv_sqrt) # array to matrix
|
| 30 |
+
return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt) # D^(-1/2) . A . D^(-1/2)
|
| 31 |
+
|
| 32 |
+
gcn_vocab_adj_tf.data *= (gcn_vocab_adj_tf.data > gcn_config.tf_threshold)
|
| 33 |
+
gcn_vocab_adj_tf.eliminate_zeros()
|
| 34 |
+
|
| 35 |
+
gcn_vocab_adj.data *= (gcn_vocab_adj.data > gcn_config.npmi_threshold)
|
| 36 |
+
gcn_vocab_adj.eliminate_zeros()
|
| 37 |
+
|
| 38 |
+
if gcn_config.vocab_type == 'pmi':
|
| 39 |
+
gcn_vocab_adj_list = [gcn_vocab_adj]
|
| 40 |
+
elif gcn_config.vocab_type == 'tf':
|
| 41 |
+
gcn_vocab_adj_list = [gcn_vocab_adj_tf]
|
| 42 |
+
elif gcn_config.vocab_type == 'all':
|
| 43 |
+
gcn_vocab_adj_list = [gcn_vocab_adj_tf, gcn_vocab_adj]
|
| 44 |
+
else:
|
| 45 |
+
raise ValueError(f"vocab_type must be 'pmi', 'tf' or 'all', got {gcn_config.vocab_type}")
|
| 46 |
+
|
| 47 |
+
norm_gcn_vocab_adj_list = []
|
| 48 |
+
for i in range(len(gcn_vocab_adj_list)):
|
| 49 |
+
adj = gcn_vocab_adj_list[i]
|
| 50 |
+
adj = normalize_adj(adj)
|
| 51 |
+
norm_gcn_vocab_adj_list.append(sparse_scipy2torch(adj.tocoo()))
|
| 52 |
+
|
| 53 |
+
del gcn_vocab_adj_list
|
| 54 |
+
|
| 55 |
+
return norm_gcn_vocab_adj_list
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class VCGNModelForTextClassification(PreTrainedModel):
|
| 60 |
+
config_class = VGCNConfig
|
| 61 |
+
|
| 62 |
+
def __init__(self, config):
|
| 63 |
+
super().__init__(config)
|
| 64 |
+
|
| 65 |
+
self.pre_trained_model_name = ''
|
| 66 |
+
self.remove_stop_words = False
|
| 67 |
+
self.tokenizer = None
|
| 68 |
+
self.norm_gcn_vocab_adj_list = None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
self.load_adj_matrix(config.gcn_adj_matrix)
|
| 72 |
+
|
| 73 |
+
self.model = VGCN_Bert(
|
| 74 |
+
config,
|
| 75 |
+
gcn_adj_matrix=self.norm_gcn_vocab_adj_list,
|
| 76 |
+
gcn_adj_dim=config.vocab_size,
|
| 77 |
+
gcn_adj_num=len(self.norm_gcn_vocab_adj_list),
|
| 78 |
+
gcn_embedding_dim=config.gcn_embedding_dim,
|
| 79 |
+
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
def load_adj_matrix(self, adj_matrix):
|
| 83 |
+
if Path(adj_matrix).is_file():
|
| 84 |
+
#load file
|
| 85 |
+
gcn_vocab_adj_tf, gcn_vocab_adj, adj_config = pkl.load(open(adj_matrix, 'rb'))
|
| 86 |
+
if is_remote_url(adj_matrix):
|
| 87 |
+
resolved_archive_file = download_url(adj_matrix)
|
| 88 |
+
|
| 89 |
+
self.pre_trained_model_name = adj_config['bert_model']
|
| 90 |
+
self.remove_stop_words = adj_config['remove_stop_words']
|
| 91 |
+
self.tokenizer = BertTokenizer.from_pretrained(self.pre_trained_model_name)
|
| 92 |
+
self.norm_gcn_vocab_adj_list = get_torch_gcn(gcn_vocab_adj_tf, gcn_vocab_adj, self.config)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def forward(self, tensor, labels=None):
|
| 96 |
+
logits = self.model(tensor)
|
| 97 |
+
if labels is not None:
|
| 98 |
+
loss = torch.nn.cross_entropy(logits, labels)
|
| 99 |
+
return {"loss": loss, "logits": logits}
|
| 100 |
+
return {"logits": logits}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
import torch
|
| 105 |
+
import torch.nn as nn
|
| 106 |
+
import torch.nn.init as init
|
| 107 |
+
import math
|
| 108 |
+
|
| 109 |
+
from transformers import BertModel
|
| 110 |
+
from transformers.models.bert.modeling_bert import BertEmbeddings, BertPooler,BertEncoder
|
| 111 |
+
|
| 112 |
+
class VocabGraphConvolution(nn.Module):
|
| 113 |
+
"""Vocabulary GCN module.
|
| 114 |
+
|
| 115 |
+
Params:
|
| 116 |
+
`voc_dim`: The size of vocabulary graph
|
| 117 |
+
`num_adj`: The number of the adjacency matrix of Vocabulary graph
|
| 118 |
+
`hid_dim`: The hidden dimension after XAW
|
| 119 |
+
`out_dim`: The output dimension after Relu(XAW)W
|
| 120 |
+
`dropout_rate`: The dropout probabilitiy for all fully connected
|
| 121 |
+
layers in the embeddings, encoder, and pooler.
|
| 122 |
+
|
| 123 |
+
Inputs:
|
| 124 |
+
`vocab_adj_list`: The list of the adjacency matrix
|
| 125 |
+
`X_dv`: the feature of mini batch document, can be TF-IDF (batch, vocab), or word embedding (batch, word_embedding_dim, vocab)
|
| 126 |
+
|
| 127 |
+
Outputs:
|
| 128 |
+
The graph embedding representation, dimension (batch, `out_dim`) or (batch, word_embedding_dim, `out_dim`)
|
| 129 |
+
|
| 130 |
+
"""
|
| 131 |
+
def __init__(self,adj_matrix,voc_dim, num_adj, hid_dim, out_dim, dropout_rate=0.2):
|
| 132 |
+
super(VocabGraphConvolution, self).__init__()
|
| 133 |
+
self.adj_matrix=adj_matrix
|
| 134 |
+
self.voc_dim=voc_dim
|
| 135 |
+
self.num_adj=num_adj
|
| 136 |
+
self.hid_dim=hid_dim
|
| 137 |
+
self.out_dim=out_dim
|
| 138 |
+
|
| 139 |
+
for i in range(self.num_adj):
|
| 140 |
+
setattr(self, 'W%d_vh'%i, nn.Parameter(torch.randn(voc_dim, hid_dim)))
|
| 141 |
+
|
| 142 |
+
self.fc_hc=nn.Linear(hid_dim,out_dim)
|
| 143 |
+
self.act_func = nn.ReLU()
|
| 144 |
+
self.dropout = nn.Dropout(dropout_rate)
|
| 145 |
+
|
| 146 |
+
self.reset_parameters()
|
| 147 |
+
|
| 148 |
+
def reset_parameters(self):
|
| 149 |
+
for n,p in self.named_parameters():
|
| 150 |
+
if n.startswith('W') or n.startswith('a') or n in ('W','a','dense'):
|
| 151 |
+
init.kaiming_uniform_(p, a=math.sqrt(5))
|
| 152 |
+
|
| 153 |
+
def forward(self, X_dv, add_linear_mapping_term=False):
|
| 154 |
+
for i in range(self.num_adj):
|
| 155 |
+
H_vh=self.adj_matrix[i].mm(getattr(self, 'W%d_vh'%i))
|
| 156 |
+
# H_vh=self.dropout(F.elu(H_vh))
|
| 157 |
+
H_vh=self.dropout(H_vh)
|
| 158 |
+
H_dh=X_dv.matmul(H_vh)
|
| 159 |
+
|
| 160 |
+
if add_linear_mapping_term:
|
| 161 |
+
H_linear=X_dv.matmul(getattr(self, 'W%d_vh'%i))
|
| 162 |
+
H_linear=self.dropout(H_linear)
|
| 163 |
+
H_dh+=H_linear
|
| 164 |
+
|
| 165 |
+
if i == 0:
|
| 166 |
+
fused_H = H_dh
|
| 167 |
+
else:
|
| 168 |
+
fused_H += H_dh
|
| 169 |
+
|
| 170 |
+
out=self.fc_hc(fused_H)
|
| 171 |
+
return out
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class VGCNBertEmbeddings(BertEmbeddings):
|
| 175 |
+
"""Construct the embeddings from word, VGCN graph, position and token_type embeddings.
|
| 176 |
+
|
| 177 |
+
Params:
|
| 178 |
+
`config`: a BertConfig class instance with the configuration to build a new model
|
| 179 |
+
`gcn_adj_dim`: The size of vocabulary graph
|
| 180 |
+
`gcn_adj_num`: The number of the adjacency matrix of Vocabulary graph
|
| 181 |
+
`gcn_embedding_dim`: The output dimension after VGCN
|
| 182 |
+
|
| 183 |
+
Inputs:
|
| 184 |
+
`vocab_adj_list`: The list of the adjacency matrix
|
| 185 |
+
`gcn_swop_eye`: The transform matrix for transform the token sequence (sentence) to the Vocabulary order (BoW order)
|
| 186 |
+
`input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
|
| 187 |
+
with the word token indices in the vocabulary. Items in the batch should begin with the special "CLS" token. (see the tokens preprocessing logic in the scripts
|
| 188 |
+
`extract_features.py`, `run_classifier.py` and `run_squad.py`)
|
| 189 |
+
`token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
|
| 190 |
+
types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
|
| 191 |
+
a `sentence B` token (see BERT paper for more details).
|
| 192 |
+
`attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
|
| 193 |
+
selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
|
| 194 |
+
input sequence length in the current batch. It's the mask that we typically use for attention when
|
| 195 |
+
a batch has varying length sentences.
|
| 196 |
+
|
| 197 |
+
Outputs:
|
| 198 |
+
the word embeddings fused by VGCN embedding, position embedding and token_type embeddings.
|
| 199 |
+
|
| 200 |
+
"""
|
| 201 |
+
def __init__(self, config, gcn_adj_matrix, gcn_adj_dim, gcn_adj_num, gcn_embedding_dim):
|
| 202 |
+
super(VGCNBertEmbeddings, self).__init__(config)
|
| 203 |
+
assert gcn_embedding_dim>=0
|
| 204 |
+
self.gcn_adj_matrix=gcn_adj_matrix
|
| 205 |
+
self.gcn_embedding_dim=gcn_embedding_dim
|
| 206 |
+
self.vocab_gcn=VocabGraphConvolution(gcn_adj_matrix,gcn_adj_dim, gcn_adj_num, 128, gcn_embedding_dim) #192/256
|
| 207 |
+
|
| 208 |
+
def forward(self, gcn_swop_eye, input_ids, token_type_ids=None, attention_mask=None):
|
| 209 |
+
words_embeddings = self.word_embeddings(input_ids)
|
| 210 |
+
vocab_input=gcn_swop_eye.matmul(words_embeddings).transpose(1,2)
|
| 211 |
+
|
| 212 |
+
if self.gcn_embedding_dim>0:
|
| 213 |
+
gcn_vocab_out = self.vocab_gcn(vocab_input)
|
| 214 |
+
|
| 215 |
+
gcn_words_embeddings=words_embeddings.clone()
|
| 216 |
+
for i in range(self.gcn_embedding_dim):
|
| 217 |
+
tmp_pos=(attention_mask.sum(-1)-2-self.gcn_embedding_dim+1+i)+torch.arange(0,input_ids.shape[0]).to(input_ids.device)*input_ids.shape[1]
|
| 218 |
+
gcn_words_embeddings.flatten(start_dim=0, end_dim=1)[tmp_pos,:]=gcn_vocab_out[:,:,i]
|
| 219 |
+
|
| 220 |
+
seq_length = input_ids.size(1)
|
| 221 |
+
position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device)
|
| 222 |
+
position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
|
| 223 |
+
if token_type_ids is None:
|
| 224 |
+
token_type_ids = torch.zeros_like(input_ids)
|
| 225 |
+
|
| 226 |
+
position_embeddings = self.position_embeddings(position_ids)
|
| 227 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
| 228 |
+
|
| 229 |
+
if self.gcn_embedding_dim>0:
|
| 230 |
+
embeddings = gcn_words_embeddings + position_embeddings + token_type_embeddings
|
| 231 |
+
else:
|
| 232 |
+
embeddings = words_embeddings + position_embeddings + token_type_embeddings
|
| 233 |
+
|
| 234 |
+
embeddings = self.LayerNorm(embeddings)
|
| 235 |
+
embeddings = self.dropout(embeddings)
|
| 236 |
+
return embeddings
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
class VGCN_Bert(BertModel):
|
| 240 |
+
"""VGCN-BERT model for text classification. It inherits from Huggingface's BertModel.
|
| 241 |
+
|
| 242 |
+
Params:
|
| 243 |
+
`config`: a BertConfig class instance with the configuration to build a new model
|
| 244 |
+
`gcn_adj_dim`: The size of vocabulary graph
|
| 245 |
+
`gcn_adj_num`: The number of the adjacency matrix of Vocabulary graph
|
| 246 |
+
`gcn_embedding_dim`: The output dimension after VGCN
|
| 247 |
+
`num_labels`: the number of classes for the classifier. Default = 2.
|
| 248 |
+
`output_attentions`: If True, also output attentions weights computed by the model at each layer. Default: False
|
| 249 |
+
`keep_multihead_output`: If True, saves output of the multi-head attention module with its gradient.
|
| 250 |
+
This can be used to compute head importance metrics. Default: False
|
| 251 |
+
|
| 252 |
+
Inputs:
|
| 253 |
+
`vocab_adj_list`: The list of the adjacency matrix
|
| 254 |
+
`gcn_swop_eye`: The transform matrix for transform the token sequence (sentence) to the Vocabulary order (BoW order)
|
| 255 |
+
`input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]
|
| 256 |
+
with the word token indices in the vocabulary. Items in the batch should begin with the special "CLS" token. (see the tokens preprocessing logic in the scripts
|
| 257 |
+
`extract_features.py`, `run_classifier.py` and `run_squad.py`)
|
| 258 |
+
`token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token
|
| 259 |
+
types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to
|
| 260 |
+
a `sentence B` token (see BERT paper for more details).
|
| 261 |
+
`attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices
|
| 262 |
+
selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max
|
| 263 |
+
input sequence length in the current batch. It's the mask that we typically use for attention when
|
| 264 |
+
a batch has varying length sentences.
|
| 265 |
+
`labels`: labels for the classification output: torch.LongTensor of shape [batch_size]
|
| 266 |
+
with indices selected in [0, ..., num_labels].
|
| 267 |
+
`head_mask`: an optional torch.Tensor of shape [num_heads] or [num_layers, num_heads] with indices between 0 and 1.
|
| 268 |
+
It's a mask to be used to nullify some heads of the transformer. 1.0 => head is fully masked, 0.0 => head is not masked.
|
| 269 |
+
|
| 270 |
+
Outputs:
|
| 271 |
+
Outputs the classification logits of shape [batch_size, num_labels].
|
| 272 |
+
|
| 273 |
+
"""
|
| 274 |
+
def __init__(self, config, gcn_adj_matrix, gcn_adj_dim, gcn_adj_num, gcn_embedding_dim):
|
| 275 |
+
super(VGCN_Bert, self).__init__(config)
|
| 276 |
+
self.embeddings = VGCNBertEmbeddings(config,gcn_adj_matrix,gcn_adj_dim,gcn_adj_num, gcn_embedding_dim)
|
| 277 |
+
self.encoder = BertEncoder(config)
|
| 278 |
+
self.pooler = BertPooler(config)
|
| 279 |
+
self.gcn_adj_matrix=gcn_adj_matrix
|
| 280 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 281 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 282 |
+
self.will_collect_cls_states=False
|
| 283 |
+
self.all_cls_states=[]
|
| 284 |
+
self.output_attentions=config.output_attentions
|
| 285 |
+
|
| 286 |
+
# self.apply(self.init_bert_weights)
|
| 287 |
+
|
| 288 |
+
def forward(self, gcn_swop_eye, input_ids, token_type_ids=None, attention_mask=None, output_hidden_states=False, head_mask=None):
|
| 289 |
+
if token_type_ids is None:
|
| 290 |
+
token_type_ids = torch.zeros_like(input_ids)
|
| 291 |
+
if attention_mask is None:
|
| 292 |
+
attention_mask = torch.ones_like(input_ids)
|
| 293 |
+
embedding_output = self.embeddings(gcn_swop_eye, input_ids, token_type_ids,attention_mask)
|
| 294 |
+
|
| 295 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
| 296 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
| 297 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
| 298 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
| 299 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
| 300 |
+
extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 301 |
+
|
| 302 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
| 303 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
| 304 |
+
# positions we want to attend and -10000.0 for masked positions.
|
| 305 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
| 306 |
+
# effectively the same as removing these entirely.
|
| 307 |
+
extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility
|
| 308 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
|
| 309 |
+
|
| 310 |
+
# Prepare head mask if needed
|
| 311 |
+
# 1.0 in head_mask indicate we keep the head
|
| 312 |
+
# attention_probs has shape bsz x n_heads x N x N
|
| 313 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
| 314 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
| 315 |
+
if head_mask is not None:
|
| 316 |
+
if head_mask.dim() == 1:
|
| 317 |
+
head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
|
| 318 |
+
head_mask = head_mask.expand_as(self.config.num_hidden_layers, -1, -1, -1, -1)
|
| 319 |
+
elif head_mask.dim() == 2:
|
| 320 |
+
head_mask = head_mask.unsqueeze(1).unsqueeze(-1).unsqueeze(-1) # We can specify head_mask for each layer
|
| 321 |
+
head_mask = head_mask.to(dtype=next(self.parameters()).dtype) # switch to fload if need + fp16 compatibility
|
| 322 |
+
else:
|
| 323 |
+
head_mask = [None] * self.config.num_hidden_layers
|
| 324 |
+
|
| 325 |
+
if self.output_attentions:
|
| 326 |
+
output_all_encoded_layers=True
|
| 327 |
+
encoded_layers = self.encoder(embedding_output,
|
| 328 |
+
extended_attention_mask,
|
| 329 |
+
output_hidden_states=output_hidden_states,
|
| 330 |
+
head_mask=head_mask)
|
| 331 |
+
if self.output_attentions:
|
| 332 |
+
all_attentions, encoded_layers = encoded_layers
|
| 333 |
+
|
| 334 |
+
pooled_output = self.pooler(encoded_layers[-1])
|
| 335 |
+
pooled_output = self.dropout(pooled_output)
|
| 336 |
+
logits = self.classifier(pooled_output)
|
| 337 |
+
|
| 338 |
+
if self.output_attentions:
|
| 339 |
+
return all_attentions, logits
|
| 340 |
+
|
| 341 |
+
return logits
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5b23581bedc6271217c0910a5676cfbb76a36b8b707a8f8f4171986cc6e5d8dd
|
| 3 |
+
size 479695719
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cls_token": "[CLS]",
|
| 3 |
+
"mask_token": "[MASK]",
|
| 4 |
+
"pad_token": "[PAD]",
|
| 5 |
+
"sep_token": "[SEP]",
|
| 6 |
+
"unk_token": "[UNK]"
|
| 7 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"clean_up_tokenization_spaces": true,
|
| 3 |
+
"cls_token": "[CLS]",
|
| 4 |
+
"do_basic_tokenize": true,
|
| 5 |
+
"do_lower_case": true,
|
| 6 |
+
"mask_token": "[MASK]",
|
| 7 |
+
"model_max_length": 512,
|
| 8 |
+
"never_split": null,
|
| 9 |
+
"pad_token": "[PAD]",
|
| 10 |
+
"sep_token": "[SEP]",
|
| 11 |
+
"strip_accents": false,
|
| 12 |
+
"tokenize_chinese_chars": true,
|
| 13 |
+
"tokenizer_class": "BertTokenizer",
|
| 14 |
+
"unk_token": "[UNK]"
|
| 15 |
+
}
|
vocab.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|