File size: 8,503 Bytes
49812da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import torch
from torch_geometric.nn import MessagePassing
from torch_geometric.nn import global_mean_pool, global_max_pool
import torch.nn.functional as F
from torch_geometric.utils import add_self_loops, degree

allowable_synthesis_features = {
    'synth_type' : [0,1,2,3,4,5,6]
}

def get_synth_feature_dims():
    return list(map(len, [
        allowable_synthesis_features['synth_type']
]))

full_synthesis_feature_dims = get_synth_feature_dims()


allowable_features = {
    'node_type' : [0,1,2],
    'gate_type' : [0,1,2]
}

def get_node_feature_dims():
    return list(map(len, [
        allowable_features['node_type']
    ]))


full_node_feature_dims = get_node_feature_dims()


class NodeEncoder(torch.nn.Module):

    def __init__(self, emb_dim):
        super(NodeEncoder, self).__init__()

        self.node_type_embedding = torch.nn.Embedding(full_node_feature_dims[0], emb_dim)
        torch.nn.init.xavier_uniform_(self.node_type_embedding.weight.data)

    def forward(self, x):
        # First feature is node type, second feature is inverted predecessor
        x_embedding = self.node_type_embedding(x[:, 0])
        #for i in range(1, x.shape[1]):
        #print(x_embedding,x_embedding.shape)
        x_embedding = torch.cat((x_embedding, x[:,1].reshape(-1,1)), dim=1)
        return x_embedding

class GCNConv(MessagePassing):
    def __init__(self, in_emb_dim, out_emb_dim):
        super(GCNConv, self).__init__(aggr='add')
        self.linear = torch.nn.Linear(in_emb_dim, out_emb_dim)

    def forward(self, x, edge_index):
        edge_index, _ = add_self_loops(edge_index, num_nodes=x.size(0))

        x = self.linear(x)
        row, col = edge_index

        # edge_weight = torch.ones((edge_index.size(1), ), device=edge_index.device)
        deg = degree(row, x.size(0), dtype=x.dtype) + 1
        deg_inv_sqrt = deg.pow(-0.5)
        deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0

        norm = deg_inv_sqrt[row] * deg_inv_sqrt[col]

        return self.propagate(edge_index, x=x, norm=norm)

    def message(self, x_j, norm):
        return norm.view(-1, 1) * x_j

    def update(self, aggr_out):
        return aggr_out

class GNN(torch.nn.Module):
    """
    Output:
        node representations
    """

    def __init__(self, node_encoder, input_dim, emb_dim=64, gnn_type='gcn'):
        '''
            emb_dim (int): node embedding dimensionality
            num_layer (int): number of GNN message passing layers
        '''
        super(GNN, self).__init__()
        self.node_emb_size = input_dim
        self.node_encoder = node_encoder

        self.conv1 = GCNConv(input_dim, emb_dim)
        self.conv2 = GCNConv(emb_dim, emb_dim)
        #self.conv3 = GCNConv(emb_dim, emb_dim)

        self.batch_norm1 = torch.nn.BatchNorm1d(emb_dim)
        self.batch_norm2 = torch.nn.BatchNorm1d(emb_dim)
        #self.batch_norm3 = torch.nn.BatchNorm1d(emb_dim)


    def forward(self, batched_data):
        edge_index, batch = batched_data.edge_index, batched_data.batch
        x = torch.cat([batched_data.node_type.reshape(-1, 1), batched_data.num_inverted_predecessors.reshape(-1, 1)],
                      dim=1)
        h = self.node_encoder(x)
        h = F.relu(self.batch_norm1(self.conv1(h, edge_index)))
        #h = F.relu(self.batch_norm2(self.conv2(h, edge_index)))
        h = self.batch_norm2(self.conv2(h, edge_index))

        xF = torch.cat([global_max_pool(h, batch), global_mean_pool(h, batch)], dim=1)

        return xF


class SynthFlowEncoder(torch.nn.Module):
    def __init__(self, emb_dim):
        super(SynthFlowEncoder, self).__init__()
        self.synth_emb = torch.nn.Embedding(full_synthesis_feature_dims[0], emb_dim)
        torch.nn.init.xavier_uniform_(self.synth_emb.weight.data)


    def forward(self, x):
        x_embedding = self.synth_emb(x[:, 0])
        for i in range(1, x.shape[1]):
            x_embedding = torch.cat((x_embedding, self.synth_emb(x[:, i])), dim=1)
        return x_embedding

class SynthConv(torch.nn.Module):
    def __init__(self, inp_channel=1,out_channel=3,ksize=6,stride_len=1):
        super(SynthConv, self).__init__()
        self.conv1d = torch.nn.Conv1d(inp_channel,out_channel,kernel_size=(ksize,),stride=(stride_len,))

    def forward(self, x):
        x = x.reshape(-1,1,x.size(1)) # Convert [4,60] to [4,1,60]
        x = self.conv1d(x)
        return x.reshape(x.size(0),-1) # Convert [4,3,55] to [4,165]


class SynthNet(torch.nn.Module):

    def __init__(self, node_encoder, synth_encoder, n_classes, synth_input_dim, node_input_dim, gnn_embed_dim = 128,num_fc_layer=4, hidden_dim = 512,drop_ratio=0.2):
        super(SynthNet,self).__init__()
        self.num_layers = num_fc_layer
        self.hidden_dim = hidden_dim
        self.node_encoder = node_encoder
        self.synth_encoder = synth_encoder
        self.node_enc_outdim = node_input_dim
        self.synth_enc_outdim = synth_input_dim
        self.gnn_emb_dim = gnn_embed_dim
        self.n_classes = n_classes
        self.drop_ratio = drop_ratio


        # Synthesis Convolution parameters
        # output_dim = {(input_dim - kernel_size + 2* padding) / stride} + 1
        self.synconv_in_channel = 1
        self.synconv_out_channel = 1
        self.synconv_stride_len = 3

        # Synth Conv1 output
        self.synconv1_ks = 21
        self.synconv1_out_dim_flatten = 1 + (self.synth_enc_outdim - self.synconv1_ks)/self.synconv_stride_len

        # Synth Conv2 output
        self.synconv2_ks = 24
        self.synconv2_out_dim_flatten = 1 + (self.synth_enc_outdim - self.synconv2_ks) / self.synconv_stride_len

        # Synth Conv3 output
        self.synconv3_ks = 27
        self.synconv3_out_dim_flatten = 1 + (self.synth_enc_outdim - self.synconv3_ks) / self.synconv_stride_len

        # Synth Conv4 output
        self.synconv4_ks = 30
        self.synconv4_out_dim_flatten = 1 + (self.synth_enc_outdim - self.synconv4_ks) / self.synconv_stride_len

        # Multiplier by 2 since each gate and node type has same encoding out dimension
        # self.gnn = GNN(self.node_encoder,self.node_enc_outdim*2)
        # Node encoding has dimension 3 and number of incoming inverted edges has dimension 1
        self.gnn = GNN(self.node_encoder, self.node_enc_outdim + 1)
        self.synth_conv1 = SynthConv(self.synconv_in_channel,self.synconv_out_channel,ksize=self.synconv1_ks,stride_len=self.synconv_stride_len)
        self.synth_conv2 = SynthConv(self.synconv_in_channel,self.synconv_out_channel,ksize=self.synconv2_ks,stride_len=self.synconv_stride_len)
        self.synth_conv3 = SynthConv(self.synconv_in_channel,self.synconv_out_channel,ksize=self.synconv3_ks,stride_len=self.synconv_stride_len)
        self.synth_conv4 = SynthConv(self.synconv_in_channel,self.synconv_out_channel,ksize=self.synconv4_ks,stride_len=self.synconv_stride_len)

        self.fcs = torch.nn.ModuleList()
        self.batch_norms = torch.nn.ModuleList()

        # GNN + (synthesis flow encoding + synthesis convolution)
        self.in_dim_to_fcs = int(self.gnn_emb_dim + self.synconv1_out_dim_flatten + self.synconv3_out_dim_flatten + self.synconv2_out_dim_flatten + self.synconv4_out_dim_flatten)
        self.fcs.append(torch.nn.Linear(self.in_dim_to_fcs,self.hidden_dim))
        #self.batch_norms.append(torch.nn.BatchNorm1d(self.hidden_dim))

        for layer in range(1, self.num_layers-1):
            self.fcs.append(torch.nn.Linear(self.hidden_dim,self.hidden_dim))
            #self.batch_norms.append(torch.nn.BatchNorm1d(emb_dim))

        self.fcs.append(torch.nn.Linear(self.hidden_dim, self.n_classes))

    def forward(self,batch_data):
        graphEmbed = self.gnn(batch_data)
        synthFlow = batch_data.synVec

        # Synthesis flow length = 20
        h_syn = self.synth_encoder(synthFlow.reshape(-1,20))
        synconv1_out = self.synth_conv1(h_syn)
        synconv2_out = self.synth_conv2(h_syn)
        synconv3_out = self.synth_conv3(h_syn)
        synconv4_out = self.synth_conv4(h_syn)
        concatenatedInput = torch.cat([graphEmbed, synconv1_out, synconv2_out, synconv3_out,synconv4_out], dim=1)
        #print(concatenatedInput.shape)
        x = F.relu(self.fcs[0](concatenatedInput))
        x = F.dropout(x, p=self.drop_ratio,training=self.training)
        for layer in range(1, self.num_layers-1):
            x = F.relu(self.fcs[layer](x))
            x = F.dropout(x, p=self.drop_ratio,training=self.training)
        x = self.fcs[-1](x)
        return x