tree_lstm.py 5.74 KB
Newer Older
1
2
3
4
"""
Improved Semantic Representations From Tree-Structured Long Short-Term Memory Networks
https://arxiv.org/abs/1503.00075
"""
5
import time
6
7
import itertools
import networkx as nx
8
import numpy as np
9
10
11
12
import torch as th
import torch.nn as nn
import torch.nn.functional as F

13
import dgl
14
15
16
17
18
19
20
21
22
23
24

class ChildSumTreeLSTMCell(nn.Module):
    def __init__(self, x_size, h_size):
        super(ChildSumTreeLSTMCell, self).__init__()
        self.W_iou = nn.Linear(x_size, 3 * h_size)
        self.U_iou = nn.Linear(h_size, 3 * h_size)
        self.W_f = nn.Linear(x_size, h_size)
        self.U_f = nn.Linear(h_size, h_size)
        self.rt = 0.
        self.ut = 0.

25
26
    def message_func(self, edges):
        return {'h' : edges.src['h'], 'c' : edges.src['c']}
27

28
    def reduce_func(self, nodes):
29
        # equation (2)
30
        h_tild = th.sum(nodes.mailbox['h'], 1)
31
        # equation (4)
32
33
        wx = self.W_f(nodes.data['x']).unsqueeze(1)  # shape: (B, 1, H)
        uh = self.U_f(nodes.mailbox['h']) # shape: (B, deg, H)
34
35
        f = th.sigmoid(wx + uh)  # shape: (B, deg, H)
        # equation (7) second term
36
        c_tild = th.sum(f * nodes.mailbox['c'], 1)
37
        return {'h_tild' : h_tild, 'c_tild' : c_tild}
38
    
39
    def apply_func(self, nodes):
40
        # equation (3), (5), (6)
41
        iou = self.W_iou(nodes.data['x']) + self.U_iou(nodes.data['h_tild'])
42
43
        i, o, u = th.chunk(iou, 3, 1)
        i, o, u = th.sigmoid(i), th.sigmoid(o), th.tanh(u)
44
        # equation (7)
45
        c = i * u + nodes.data['c_tild']
46
        # equation (8)
47
48
49
        h = o * th.tanh(c)
        return {'h' : h, 'c' : c}

50
51
52
53
54
55
56
57
58
59
class TreeLSTM(nn.Module):
    def __init__(self,
                 num_vocabs,
                 x_size,
                 h_size,
                 num_classes,
                 dropout,
                 cell_type='childsum'):
        super(TreeLSTM, self).__init__()
        self.x_size = x_size
60
        self.h_size = h_size
61
62
63
64
65
66
        # TODO(minjie): pre-trained embedding like GLoVe
        self.embedding = nn.Embedding(num_vocabs, x_size)
        self.dropout = nn.Dropout(dropout)
        self.linear = nn.Linear(h_size, num_classes)
        if cell_type == 'childsum':
            self.cell = ChildSumTreeLSTMCell(x_size, h_size)
67
        else:
68
69
            raise RuntimeError('Unknown cell type:', cell_type)

70
    def forward(self, graph, zero_initializer, h=None, c=None, iterator=None, train=True):
71
        """Compute tree-lstm prediction given a batch.
72
73
74

        Parameters
        ----------
75
76
        graph : dgl.DGLGraph
            The batched trees.
77
78
79
        zero_initializer : callable
            Function to return zero value tensor.
        h : Tensor, optional
80
            Initial hidden state.
81
        c : Tensor, optional
82
            Initial cell state.
83
        iterator : graph iterator, optional
84
85
86
87
88
89
            External iterator on graph.

        Returns
        -------
        logits : Tensor
            The prediction of each node.
90
        """
91
        g = graph
92
        n = g.number_of_nodes()
Minjie Wang's avatar
Minjie Wang committed
93
94
95
        g.register_message_func(self.cell.message_func)
        g.register_reduce_func(self.cell.reduce_func)
        g.register_apply_node_func(self.cell.apply_func)
96
        # feed embedding
97
98
99
100
        wordid = g.pop_n_repr('x')
        mask = (wordid != dgl.data.SST.PAD_WORD)
        wordid = wordid * mask.long()
        embeds = self.embedding(wordid)
101
        g.ndata['x'] = embeds * th.unsqueeze(mask, 1).float()
102
103
        if h is None:
            h = zero_initializer((n, self.h_size))
104
105
        g.ndata['h'] = h
        g.ndata['h_tild'] = zero_initializer((n, self.h_size))
106
107
        if c is None:
            c = zero_initializer((n, self.h_size))
108
109
        g.ndata['c'] = c
        g.ndata['c_tild'] = zero_initializer((n, self.h_size))
110
111
        # TODO(minjie): potential bottleneck
        if iterator is None:
GaiYu0's avatar
GaiYu0 committed
112
            g.propagate('topo')
113
        else:
114
            for frontier in iterator:
115
                g.pull(frontier)
116
        # compute logits
117
        h = g.ndata.pop('h')
118
119
120
121
122
        h = self.dropout(h)
        logits = self.linear(h)
        return logits

'''
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
class NAryTreeLSTM(TreeLSTM):
    def __init__(self, n_embeddings, x_size, h_size, n_ary, n_classes):
        super().__init__(n_embeddings, x_size, h_size, n_classes)

        # TODO initializer
        self.iou_w = nn.Parameter(th.randn(x_size, 3 * h_size))
        self.iou_u = [nn.Parameter(th.randn(1, h_size, 3 * h_size)) for i in range(n_ary)]
        self.iou_b = nn.Parameter(th.zeros(1, 3 * h_size))

        # TODO initializer
        self.f_x = nn.Parameter(th.randn(x_size, h_size))
        self.f_h = [[nn.Parameter(th.randn(1, h_size, h_size))
                     for i in range(n_ary)] for i in range(n_ary)]
        self.f_b = nn.Parameter(th.zeros(1, h_size))

    def internal_update_func(self, node_reprs, edge_reprs):
        assert len(edge_reprs) > 0
        assert all(msg['h'] is not None and msg['c'] is not None for msg in edge_reprs)

        x = node_reprs['x']
        n_children = len(edge_reprs)

        iou_wx = th.mm(x, self.iou_w) if x is not None else 0
        iou_u = th.cat(self.iou_u[:n_children], 0)
        iou_h = th.cat([msg['h'] for msg in edge_reprs], 0).unsqueeze(1)
        iou_uh = th.sum(th.bmm(iou_h, iou_u), 0)
        i, o, u = th.chunk(iou_wx + iou_uh + self.iou_b, 3, 1)
        i, o, u = th.sigmoid(i), th.sigmoid(o), th.tanh(u)

        f_wx = th.mm(x, self.f_x).repeat(n_children, 1) if x is not None else 0
        f_h = iou_h.repeat(n_children, 1, 1)
        f_u = th.cat(sum([self.f_h[i][:n_children] for i in range(n_children)], []), 0)
        f_uh = th.sum(th.bmm(f_h, f_u).view(n_children, n_children, -1), 0)
        f = th.sigmoid(f_wx + f_uh + self.f_b)

        c = th.cat([msg['c'] for msg in edge_reprs], 0)
        c = i * u + th.sum(f * c, 0, keepdim=True)
        h = o * th.tanh(c)

        return {'h' : h, 'c' : c}
163
'''