File: sched.py

package info (click to toggle)
theano 1.0.5%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 30,016 kB
  • sloc: python: 142,361; ansic: 9,767; javascript: 2,413; sh: 175; makefile: 147; pascal: 81
file content (276 lines) | stat: -rw-r--r-- 7,931 bytes parent folder | download | duplicates (2)
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
from __future__ import absolute_import, print_function, division
from collections import defaultdict
from six import iteritems
from theano.gof.graph import list_of_nodes
from theano.compat import cmp

# {{{ http://code.activestate.com/recipes/578231/ (r1)
# Copyright (c) Oren Tirosh 2012
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


def memodict(f):
    """
    Memoization decorator for a function taking a single argument.

    """
    class memodict(defaultdict):
        def __missing__(self, key):
            ret = self[key] = f(key)
            return ret
    return memodict().__getitem__

# end of http://code.activestate.com/recipes/578231/ }}}


def make_depends():
    @memodict
    def depends(pair):
        """
        Returns True if a depends on b.

        """
        a, b = pair
        return (any(bout in a.inputs for bout in b.outputs) or
                any(depends((ainp.owner, b)) for ainp in a.inputs
                    if ainp.owner))
    return depends


def make_dependence_cmp():
    """
    Create a comparator to represent the dependence of nodes in a graph.

    """
    depends = make_depends()

    def dependence(a, b):
        """
        A cmp function for nodes in a graph - does a depend on b?

        Returns
        -------
        int
            Positive number if a depends on b, negative number
            if b depends on a, 0 otherwise.

        """
        if depends((a, b)):
            return 1
        if depends((b, a)):
            return -1
        return 0

    return dependence


def reverse_dict(d):
    """
    Reverses direction of dependence dict.

    Notes
    -----
    dict order is not deterministic. As we iterate on the
    input dict, it makes the output of this function depend on the
    dict order. So this function output order should be considered
    as undeterministic.

    Examples
    --------
    >>> d = {'a': (1, 2), 'b': (2, 3), 'c':()}
    >>> reverse_dict(d)
    {1: ('a',), 2: ('a', 'b'), 3: ('b',)}

    """
    result = {}
    for key in d:
        for val in d[key]:
            result[val] = result.get(val, tuple()) + (key, )
    return result


def _toposort(edges):
    """
    Topological sort algorithm by Kahn [1] - O(nodes + vertices).

    Parameters
    ----------
    edges
        A dict of the form {a: {b, c}} where b and c depend on a.

    Returns
    -------
    L : list
        An ordered list of nodes that satisfy the dependencies of edges.

    Closely follows the wikipedia page [2]

    References
    ----------
    [1] Kahn, Arthur B. (1962), "Topological sorting of large networks",
    Communications of the ACM
    [2] http://en.wikipedia.org/wiki/Toposort#Algorithms

    Examples
    --------
    >>> _toposort({1: {2, 3}, 2: (3, )})
    [1, 2, 3]

    """
    incoming_edges = reverse_dict(edges)
    incoming_edges = dict((k, set(val))
                          for k, val in iteritems(incoming_edges))
    S = set((v for v in edges if v not in incoming_edges))
    L = []

    while S:
        n = S.pop()
        L.append(n)
        for m in edges.get(n, ()):
            assert n in incoming_edges[m]
            incoming_edges[m].remove(n)
            if not incoming_edges[m]:
                S.add(m)
    if any(incoming_edges.get(v, None) for v in edges):
        raise ValueError("Input has cycles")
    return L


def posort(l, *cmps):
    """
    Partially ordered sort with multiple comparators.

    Given a list of comparators, orders the elements in l so that the
    comparators are satisfied as much as possible giving precedence to
    earlier comparators.

    Parameters
    ----------
    l
        An iterable of nodes in a graph.
    cmps
        A sequence of comparator functions that describe which nodes should
        come before which others.

    Returns
    -------
    list
        A list of nodes which satisfy the comparators as much as possible.

    Notes
    -----
    Implemented with _toposort.

    Examples
    --------
    >>> lower_tens = lambda a, b: a/10 - b/10 # prefer lower numbers div 10
    >>> prefer evens = lambda a, b: a%2 - b%2 # prefer even numbers
    >>> posort(list(range(20)), lower_tens, prefer_evens)
    [0, 8, 2, 4, 6, 1, 3, 5, 7, 9, 16, 18, 10, 12, 14, 17, 19, 11, 13, 15]

    """
    comes_before = dict((a, set()) for a in l)
    comes_after = dict((a, set()) for a in l)

    def add_links(a, b):  # b depends on a
        comes_after[a].add(b)
        comes_after[a].update(comes_after[b])
        for c in comes_before[a]:
            comes_after[c].update(comes_after[a])
        comes_before[b].add(a)
        comes_before[b].update(comes_before[a])
        for c in comes_after[b]:
            comes_before[c].update(comes_before[b])

    def check():
        """
        Tests for cycles in manufactured edges.

        """
        for a in l:
            for b in l:
                assert not(b in comes_after[a] and a in comes_after[b])

    for cmp_fn in cmps:
        for a in l:
            for b in l:
                if cmp_fn(a, b) < 0:  # a wants to come before b
                    # if this wouldn't cause a cycle and isn't already known
                    if b not in comes_before[a] and b not in comes_after[a]:
                        add_links(a, b)
    # check() # debug code

    return _toposort(comes_after)


def sort_apply_nodes(inputs, outputs, cmps):
    """
    Order a graph of apply nodes according to a list of comparators.

    The following example sorts first by dependence of nodes (this is a
    topological sort) and then by lexicographical ordering (nodes that start
    with 'E' come before nodes that start with 'I' if there is no dependence.

    Examples
    --------
    >>> from theano.gof.graph import sort_apply_nodes, dependence
    >>> from theano.tensor import matrix, dot
    >>> x = matrix('x')
    >>> y = dot(x*2, x+1)
    >>> str_cmp = lambda a, b: cmp(str(a), str(b)) # lexicographical sort
    >>> sort_apply_nodes([x], [y], cmps=[dependence, str_cmp])
    [Elemwise{add,no_inplace}(x, InplaceDimShuffle{x,x}.0),
     InplaceDimShuffle{x,x}(TensorConstant{2}),
     Elemwise{mul,no_inplace}(x, InplaceDimShuffle{x,x}.0),
     InplaceDimShuffle{x,x}(TensorConstant{1}),
     dot(Elemwise{mul,no_inplace}.0, Elemwise{add,no_inplace}.0)]

    """
    return posort(list_of_nodes(inputs, outputs), *cmps)


def sort_schedule_fn(*cmps):
    """
    Make a schedule function from comparators.

    See Also
    --------
    sort_apply_nodes

    """
    dependence = make_dependence_cmp()
    cmps = (dependence,) + cmps

    def schedule(fgraph):
        """
        Order nodes in a FunctionGraph.

        """
        return sort_apply_nodes(fgraph.inputs, fgraph.outputs, cmps)
    return schedule


def key_to_cmp(key):
    """
    comparator function based on "key" function
    """
    def key_cmp(a, b):
        return cmp(key(a), key(b))
    return key_cmp