chunk_codegen.py 87.4 KB
Newer Older
oahzxl's avatar
init  
oahzxl committed
1
2
import colossalai
import torch
oahzxl's avatar
oahzxl committed
3
import copy
oahzxl's avatar
init  
oahzxl committed
4
5
from typing import List, Callable, Any, Tuple, Dict, Iterable

oahzxl's avatar
oahzxl committed
6
from torch.fx.node import Node, Argument, map_arg, _type_repr, _get_qualified_name
oahzxl's avatar
oahzxl committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from torch.fx.graph import (
    _Namespace,
    PythonCode,
    _custom_builtins,
    _is_from_torch,
    _format_target,
    magic_methods,
    CodeGen,
    _origin_type_map,
    inplace_methods,
    _CustomBuiltin,
)
from colossalai.fx.profiler import (
    calculate_fwd_out,
    calculate_fwd_tmp,
    parameter_size,
    activation_size,
)

oahzxl's avatar
oahzxl committed
26
CODEGEN_AVAILABLE = True
oahzxl's avatar
oahzxl committed
27
__all__ = ["ChunkCodeGen"]
oahzxl's avatar
init  
oahzxl committed
28
29


oahzxl's avatar
oahzxl committed
30
31
32
def _delete_free_var_from_last_use(user_to_last_uses):
    for key, value in user_to_last_uses.items():
        for n in value:
oahzxl's avatar
oahzxl committed
33
            if n.op == "placeholder":
oahzxl's avatar
oahzxl committed
34
35
                user_to_last_uses[key].remove(n)

oahzxl's avatar
oahzxl committed
36

37
def _get_node_shape(node):
oahzxl's avatar
oahzxl committed
38
39
    if hasattr(node.meta["tensor_meta"], "shape"):
        return node.meta["tensor_meta"].shape
40
41
    return None

oahzxl's avatar
oahzxl committed
42

oahzxl's avatar
oahzxl committed
43
def _is_non_compute_node(node):
oahzxl's avatar
oahzxl committed
44
45
46
    if any(i in node.op for i in ["placeholder", "get_attr", "output"]) or any(
        i in node.name for i in ["getitem", "getattr"]
    ):
oahzxl's avatar
oahzxl committed
47
48
        return True
    return False
oahzxl's avatar
oahzxl committed
49
50


oahzxl's avatar
oahzxl committed
51
def _is_non_compute_node_except_placeholder(node):
oahzxl's avatar
oahzxl committed
52
53
54
    if any(i in node.op for i in ["get_attr", "output"]) or any(
        i in node.name for i in ["getitem", "getattr"]
    ):
oahzxl's avatar
oahzxl committed
55
56
57
58
        return True
    return False


oahzxl's avatar
oahzxl committed
59
60
61
62
63
64
65
66
def _is_non_compute_node_except_placeholder_output(node):
    if any(i in node.op for i in ["get_attr"]) or any(
        i in node.name for i in ["getitem", "getattr"]
    ):
        return True
    return False


oahzxl's avatar
oahzxl committed
67
class IndexTracer(object):
oahzxl's avatar
oahzxl committed
68
69
    def __init__(self, node_list) -> None:
        self.node_list = node_list
70
        self.idx_trace_list = self._init_idx_trace_list()
oahzxl's avatar
oahzxl committed
71
        self.idx_trace_equal = []
oahzxl's avatar
oahzxl committed
72
        self.idx_view_list = {}
oahzxl's avatar
oahzxl committed
73
        self.idx_count = -1
oahzxl's avatar
oahzxl committed
74
        self.all_reorder_map = {i: i for i in range(len(self.idx_trace_list))}
oahzxl's avatar
oahzxl committed
75

76
77
    def _init_idx_trace_list(self):
        idx_trace_list = []
oahzxl's avatar
oahzxl committed
78
        for n in self.node_list:
oahzxl's avatar
oahzxl committed
79
            if _get_node_shape(n) != None:
80
                cur_trace = {
oahzxl's avatar
oahzxl committed
81
82
83
                    "idx": [None for _ in range(len(_get_node_shape(n)))],
                    "compute": [[] for _ in range(len(_get_node_shape(n)))],
                    "source": [{} for _ in range(len(_get_node_shape(n)))],
84
85
                }
            else:
oahzxl's avatar
oahzxl committed
86
                cur_trace = {"idx": [], "compute": [], "source": []}
87
88
            idx_trace_list.append(cur_trace)
        return idx_trace_list
oahzxl's avatar
oahzxl committed
89

oahzxl's avatar
oahzxl committed
90
    def _add_index(self):
oahzxl's avatar
oahzxl committed
91
92
        """
        Update the count and return it. To record the idx number.
oahzxl's avatar
oahzxl committed
93

oahzxl's avatar
oahzxl committed
94
95
        Returns:
            idx_count: int
oahzxl's avatar
oahzxl committed
96
        """
oahzxl's avatar
oahzxl committed
97
        self.idx_count += 1
oahzxl's avatar
oahzxl committed
98
        return self.idx_count
oahzxl's avatar
oahzxl committed
99

100
    def _del_dim(self, idx, dim_idx):
oahzxl's avatar
oahzxl committed
101
102
103
104
        self.idx_trace_list[idx]["idx"].pop(dim_idx)
        self.idx_trace_list[idx]["compute"].pop(dim_idx)
        self.idx_trace_list[idx]["source"].pop(dim_idx)

105
106
107
108
    def _add_dim(self, node_idx, dim_idx):
        self.idx_trace_list[node_idx]["idx"].insert(dim_idx, self._add_index())
        self.idx_trace_list[node_idx]["compute"].insert(dim_idx, [])
        self.idx_trace_list[node_idx]["source"].insert(dim_idx, {})
oahzxl's avatar
oahzxl committed
109

110
111
112
113
    def _transform_index(self, node, node_dim):
        node_idx = self._find_idx_trace_from_node(node)
        dims = list(range(len(node_idx)))
        return dims[node_dim]
oahzxl's avatar
oahzxl committed
114

115
116
117
118
119
    def _inherit_index(self, node_from, node_from_dim, node_to, node_to_dim):
        node_from_dim = self._transform_index(node_from, node_from_dim)
        node_to_dim = self._transform_index(node_to, node_to_dim)
        node_from_trace = self._find_trace_from_node(node_from)
        node_to_trace = self._find_trace_from_node(node_to)
oahzxl's avatar
oahzxl committed
120
121
122
123
        node_to_trace["idx"][node_to_dim] = node_from_trace["idx"][node_from_dim]
        node_to_trace["compute"][node_to_dim] = copy.deepcopy(
            node_from_trace["compute"][node_from_dim]
        )
oahzxl's avatar
oahzxl committed
124
        self._add_source(node_from, node_from_dim, node_to, node_to_dim, init=True)
oahzxl's avatar
oahzxl committed
125

126
127
128
129
130
131
132
    def _inherit_all_computation(self, node_from, node_to):
        node_from_compute = self._find_compute_trace_from_node(node_from)
        node_to_compute = self._find_compute_trace_from_node(node_to)
        assert len(node_from_compute) == len(node_to_compute)
        for i in range(len(node_from_compute)):
            self._add_source(node_from, i, node_to, i)
            node_to_compute[i] = copy.deepcopy(node_from_compute[i])
oahzxl's avatar
oahzxl committed
133

oahzxl's avatar
oahzxl committed
134
    def _add_source(self, node_from, node_from_dim, node_to, node_to_dim, init=False):
135
136
137
138
        node_from_dim = self._transform_index(node_from, node_from_dim)
        node_from_trace = self._find_trace_from_node(node_from)
        node_to_dim = self._transform_index(node_to, node_to_dim)
        node_to_trace = self._find_trace_from_node(node_to)
oahzxl's avatar
oahzxl committed
139
        node_from_idx = _find_idx_by_name(node_from.name, self.node_list)
oahzxl's avatar
oahzxl committed
140
        if init:
oahzxl's avatar
oahzxl committed
141
            node_to_trace["source"][node_to_dim] = {}
oahzxl's avatar
oahzxl committed
142
143
144
145
146
        # add dim to cur new source
        if node_from_idx not in node_to_trace["source"][node_to_dim]:
            node_to_trace["source"][node_to_dim][node_from_idx] = [node_from_dim]
        else:
            if node_from_dim not in node_to_trace["source"][node_to_dim][node_from_idx]:
oahzxl's avatar
oahzxl committed
147
148
149
                node_to_trace["source"][node_to_dim][node_from_idx].append(
                    node_from_dim
                )
oahzxl's avatar
oahzxl committed
150
        # update inputs source
oahzxl's avatar
oahzxl committed
151
152
153
154
        node_to_trace["source"][node_to_dim].update(
            node_from_trace["source"][node_from_dim]
        )

155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
    def _mark_computation_from_node(self, node_from, node_to, exclude=None):
        if exclude == None:
            exclude = []
        else:
            exclude = [self._transform_index(node_to, i) for i in exclude]
        node_from_compute = self._find_compute_trace_from_node(node_from)
        node_to_compute = self._find_compute_trace_from_node(node_to)
        # assert len(node_from_compute) == len(node_to_compute)
        for i in range(-1, -min(len(node_from_compute), len(node_to_compute)) - 1, -1):
            if self._transform_index(node_to, i) in exclude:
                continue
            self._add_source(node_from, i, node_to, i)
            for j in node_from_compute[i]:
                if j not in node_to_compute[i]:
                    node_to_compute[i].append(j)
oahzxl's avatar
oahzxl committed
170

171
    def _mark_idx_equal(self, node1, dim1, node2, dim2):
oahzxl's avatar
oahzxl committed
172
173
174
175
176
177
        """
        Mark 2 index to be equal.

        Args:
            idx1 (int): index count.
            idx2 (int): index count.
178
179
180
181
182
183
184
        """
        # node1_idx = _find_idx_by_name(node1.name, self.nodes_list)
        # node2_idx = _find_idx_by_name(node2.name, self.nodes_list)
        # if node1_idx > node2_idx:
        #     self._add_source(node2, dim2, node1, dim1)
        # else:
        #     self._add_source(node1, dim1, node2, dim2)
oahzxl's avatar
oahzxl committed
185

oahzxl's avatar
oahzxl committed
186
    def _mark_computation(self, node, idx, dim):
oahzxl's avatar
oahzxl committed
187
188
189
190
191
192
193
        """
        Mark some dims of node as computed.

        Args:
            node (node)
            idx (int): node index
            dim (list or int): dims to be marked as computed
oahzxl's avatar
oahzxl committed
194
        """
oahzxl's avatar
oahzxl committed
195
196
        if isinstance(dim, int):
            dim = [dim]
197
        dims = list(range(len(_get_node_shape(node))))
oahzxl's avatar
oahzxl committed
198
        for d in dim:
199
            cur_dim = dims[d]
oahzxl's avatar
oahzxl committed
200
201
            if idx not in self.idx_trace_list[idx]["compute"][cur_dim]:
                self.idx_trace_list[idx]["compute"][cur_dim].append(idx)
202

oahzxl's avatar
oahzxl committed
203
    def _find_trace_from_node(self, node):
oahzxl's avatar
oahzxl committed
204
205
206
207
208
209
210
211
        """
        Find node idx and compute trace by the node.

        Args:
            node (node)
        Returns:
            idx (list): idx of the node
            compute (list): computed idx of the node.
oahzxl's avatar
oahzxl committed
212
        """
oahzxl's avatar
oahzxl committed
213
        node_idx = _find_idx_by_name(node.name, self.node_list)
oahzxl's avatar
oahzxl committed
214
        node_dict = self.idx_trace_list[node_idx]
215
        return node_dict
oahzxl's avatar
oahzxl committed
216

oahzxl's avatar
oahzxl committed
217
218
219
220
221
222
223
224
225
226
    def _find_source_trace_from_node(self, node):
        """
        Find node source trace by the node.

        Args:
            node (node)
        Returns:
            idx (list): idx of the node
            compute (list): computed idx of the node.
        """
oahzxl's avatar
oahzxl committed
227
        node_idx = _find_idx_by_name(node.name, self.node_list)
oahzxl's avatar
oahzxl committed
228
229
230
        node_dict = self.idx_trace_list[node_idx]
        return node_dict["source"]

oahzxl's avatar
oahzxl committed
231
    def _find_idx_trace_from_node(self, node):
oahzxl's avatar
oahzxl committed
232
233
234
235
236
237
238
        """
        Find node idx trace by the node.

        Args:
            node (node)
        Returns:
            idx (list): idx of the node
oahzxl's avatar
oahzxl committed
239
        """
oahzxl's avatar
oahzxl committed
240
        node_idx = _find_idx_by_name(node.name, self.node_list)
oahzxl's avatar
oahzxl committed
241
242
        return self.idx_trace_list[node_idx]["idx"]

oahzxl's avatar
oahzxl committed
243
    def _find_compute_trace_from_node(self, node):
oahzxl's avatar
oahzxl committed
244
245
246
247
248
249
250
        """
        Find node compute trace by the node.

        Args:
            node (node)
        Returns:
            compute (list): computed idx of the node.
oahzxl's avatar
oahzxl committed
251
        """
oahzxl's avatar
oahzxl committed
252
        node_idx = _find_idx_by_name(node.name, self.node_list)
oahzxl's avatar
oahzxl committed
253
254
        return self.idx_trace_list[node_idx]["compute"]

255
    def _assign_index_as_input(self, node, node_idx, input_node=None):
oahzxl's avatar
oahzxl committed
256
257
258
259
260
261
        """
        Assign node's trace as its input node.

        Args:
            node (node)
            node_idx (int)
262
263
264
        """
        if input_node == None:
            input_node = node.args[0]
oahzxl's avatar
oahzxl committed
265
        input_node_idx = _find_idx_by_name(input_node.name, self.node_list)
oahzxl's avatar
oahzxl committed
266
267
        input_node_idx_trace = self.idx_trace_list[input_node_idx]["idx"]

oahzxl's avatar
oahzxl committed
268
        new_idx_trace = copy.deepcopy(input_node_idx_trace)
oahzxl's avatar
oahzxl committed
269
270
        self.idx_trace_list[node_idx]["idx"] = new_idx_trace

271
        self._inherit_all_computation(input_node, node)
oahzxl's avatar
oahzxl committed
272

oahzxl's avatar
oahzxl committed
273
    def _assign_all_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
274
275
276
277
278
279
        """
        Add new index for all node's dims.

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
280
281
        """
        shape = node.meta["tensor_meta"].shape
oahzxl's avatar
oahzxl committed
282
283
        new_trace = []
        for _ in shape:
oahzxl's avatar
oahzxl committed
284
            new_trace.append(self._add_index())
oahzxl's avatar
oahzxl committed
285
        self.idx_trace_list[node_idx]["idx"] = new_trace
oahzxl's avatar
oahzxl committed
286

oahzxl's avatar
oahzxl committed
287
    def _assign_transpose_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
288
289
290
291
292
293
294
295
        """
        Assign index for transpose op.
        1. swap input's dim according to transpose args
        2. inherit input's computation

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
296
        """
297
        input_node = node.args[0]
oahzxl's avatar
oahzxl committed
298
        tranpose_dim = node.args[1:]
oahzxl's avatar
oahzxl committed
299

300
301
302
        self._assign_index_as_input(node, node_idx, input_node)
        self._inherit_index(input_node, tranpose_dim[1], node, tranpose_dim[0])
        self._inherit_index(input_node, tranpose_dim[0], node, tranpose_dim[1])
oahzxl's avatar
oahzxl committed
303

oahzxl's avatar
oahzxl committed
304
    def _assign_permute_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
305
306
307
308
309
310
311
312
        """
        Assign index for permute op.
        1. swap input's dim according to permute args
        2. inherit input's computation

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
313
        """
oahzxl's avatar
oahzxl committed
314
        permute_dim = node.args[1:]
315
        input_node = node.args[0]
oahzxl's avatar
oahzxl committed
316

317
        self._assign_index_as_input(node, node_idx, input_node)
oahzxl's avatar
oahzxl committed
318
        for idx, d in enumerate(permute_dim):
319
            self._inherit_index(input_node, d, node, idx)
oahzxl's avatar
oahzxl committed
320

oahzxl's avatar
oahzxl committed
321
    def _assign_linear_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
322
323
324
325
326
327
328
329
330
        """
        Assign index for linear op.
        1. copy trace from input node and change last index accroding to weight
        2. mark equal for input node last index, weight first dim and bias dim.
        3. inherit input's computation, mark computation for last dim.

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
331
332
333
334
335
336
        """
        if len(node.args) == 2:
            input_node, weight = node.args
            bias = None
        else:
            input_node, weight, bias = node.args
oahzxl's avatar
oahzxl committed
337

338
339
        self._assign_index_as_input(node, node_idx)
        self._inherit_index(weight, 1, node, -1)
oahzxl's avatar
oahzxl committed
340

oahzxl's avatar
oahzxl committed
341
        self._mark_computation(node, node_idx, [-1])
342
        self._mark_idx_equal(input_node, -1, weight, 0)
oahzxl's avatar
oahzxl committed
343

oahzxl's avatar
oahzxl committed
344
        if bias:
345
            self._mark_idx_equal(input_node, -1, bias, 0)
oahzxl's avatar
oahzxl committed
346

oahzxl's avatar
oahzxl committed
347
    def _assign_matmul_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
348
349
350
351
352
353
354
355
356
        """
        Assign index for matmul op.
        1. copy trace from matmul_left and change last index accroding to matmul_right. (assert they have same length)
        2. mark equal for input matmul_left -1 index and matmul_right -2 dim.
        3. inherit matmul_left and matmul_right computation, mark computation for last dim.

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
357
        """
oahzxl's avatar
oahzxl committed
358
        matmul_left, matmul_right = node.args
oahzxl's avatar
oahzxl committed
359
360

        assert len(_get_node_shape(matmul_left)) == len(_get_node_shape(matmul_right))
361
362
        self._assign_index_as_input(node, node_idx, matmul_left)
        self._inherit_index(matmul_right, -1, node, -1)
oahzxl's avatar
oahzxl committed
363

364
        self._mark_computation_from_node(matmul_right, node, [-1, -2])
oahzxl's avatar
oahzxl committed
365
        self._mark_computation(node, node_idx, [-1])
366
        self._mark_idx_equal(matmul_left, -1, matmul_right, -2)
oahzxl's avatar
oahzxl committed
367

oahzxl's avatar
oahzxl committed
368
    def _assign_layernorm_index(self, node, idx):
oahzxl's avatar
oahzxl committed
369
370
371
372
373
374
375
376
377
        """
        Assign index for layernorm op.
        1. assign index as input node
        2. inherit computation and mark last 2 dims as computed.

        Args:
            node (node)
            node_idx (int)
        """
oahzxl's avatar
oahzxl committed
378
        self._assign_index_as_input(node, idx)
oahzxl's avatar
oahzxl committed
379
        self._mark_computation(node, idx, [-1])
oahzxl's avatar
oahzxl committed
380

oahzxl's avatar
oahzxl committed
381
    def _assign_elementwise_index(self, node, idx):
oahzxl's avatar
oahzxl committed
382
383
384
385
386
387
388
389
        """
        Assign index for element-wise op (eg. relu sigmoid add mul).
        1. assign index as input node
        2. inherit computation from all input nodes.

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
390
        """
oahzxl's avatar
oahzxl committed
391
        self._assign_index_as_input(node, idx)
392
        nodes_in = []
oahzxl's avatar
oahzxl committed
393
        for node_in in node.args:
394
395
396
397
398
399
400
401
402
403
            if type(node_in) == type(node):
                nodes_in.append(node_in)
                self._mark_computation_from_node(node_in, node)
        assert len(nodes_in) <= 2
        if len(nodes_in) == 2:
            node_in0_shape = _get_node_shape(nodes_in[0])
            node_in1_shape = _get_node_shape(nodes_in[1])
            for i in range(-1, -min(len(node_in0_shape), len(node_in1_shape)) - 1, -1):
                if node_in0_shape[i] == node_in1_shape[i]:
                    self._mark_idx_equal(nodes_in[0], i, nodes_in[1], i)
oahzxl's avatar
oahzxl committed
404

405
406
407
408
409
    def _assgin_no_change_index(self, node, idx):
        self._assign_index_as_input(node, idx)
        for node_in in node.args:
            if type(node_in) == type(node):
                self._mark_computation_from_node(node_in, node)
oahzxl's avatar
oahzxl committed
410

411
412
413
414
415
416
417
418
419
420
    def _assign_einsum_index(self, node, idx):
        """
        Assign index for einsum op.

        Args:
            node (node)
            node_idx (int)
        """
        patterns = node.args[0]
        input_nodes = node.args[1:]
oahzxl's avatar
oahzxl committed
421

422
423
424
        patterns = patterns.replace(" ", "")
        left, right = patterns.split("->")
        left = left.split(",")
oahzxl's avatar
oahzxl committed
425

426
427
428
429
430
431
432
        all_index = []
        for i in left:
            for c in i:
                all_index.append(c)
        all_index = set(all_index)
        free_index = set([i for i in right])
        sum_index = all_index - free_index
oahzxl's avatar
oahzxl committed
433

434
435
436
437
        for right_idx, right_indice in enumerate(right):
            for left_idx, left_str in enumerate(left):
                if right_indice in left_str:
                    source_idx = left_str.index(right_indice)
oahzxl's avatar
oahzxl committed
438
439
440
441
                    self._inherit_index(
                        input_nodes[left_idx], source_idx, node, right_idx
                    )

oahzxl's avatar
oahzxl committed
442
443
444
445
446
        # for i in sum_index:
        #     for left_idx, left_str in enumerate(left):
        #         if i in left_str:
        #             self._mark_computation(node, idx, left_str.index(i))
        #             break
oahzxl's avatar
oahzxl committed
447

oahzxl's avatar
oahzxl committed
448
    def _assign_softmax_index(self, node, idx):
oahzxl's avatar
oahzxl committed
449
450
451
452
453
454
455
456
        """
        Assign index for softmax op.
        1. assign index as input node
        2. inherit computation and mark softmax dim as computed.

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
457
        """
oahzxl's avatar
oahzxl committed
458
        self._assign_index_as_input(node, idx)
oahzxl's avatar
oahzxl committed
459
460
        self._mark_computation(node, idx, [node.kwargs["dim"]])

oahzxl's avatar
oahzxl committed
461
462
463
464
465
466
467
468
    def _assign_unsqueeze_index(self, node, node_idx):
        """
        Assign index for unsqueeze op.
        1. assign new index for unsqueeze dim

        Args:
            node (node)
            node_idx (int)
469
470
        """
        self._del_dim(node_idx, -1)
oahzxl's avatar
oahzxl committed
471
        self._assign_index_as_input(node, node_idx)
472
        self._add_dim(node_idx, node.args[1])
oahzxl's avatar
oahzxl committed
473

oahzxl's avatar
oahzxl committed
474
475
476
477
478
479
480
481
    def _assign_dropout_index(self, node, node_idx):
        """
        Assign index for unsqueeze op.
        1. assign new index for unsqueeze dim

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
482
        """
oahzxl's avatar
oahzxl committed
483
        self._assign_index_as_input(node, node_idx)
oahzxl's avatar
oahzxl committed
484

oahzxl's avatar
oahzxl committed
485
486
487
488
489
490
491
492
    def _assign_ones_like_index(self, node, node_idx):
        """
        Assign index for oneslike op.
        1. assign new index for all dim

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
493
        """
oahzxl's avatar
oahzxl committed
494
        self._assign_all_index(node, node_idx)
oahzxl's avatar
oahzxl committed
495

oahzxl's avatar
oahzxl committed
496
    def _assign_view_reshape_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
497
498
499
500
501
502
        """
        Assign index for view and reshape op.
        1. get origin shape and target shape by meta info.
        2. compute the real value of -1 in target shape.
        3. determine changed dim, and assgin index for generated dim.
        4. log changed dim and generated dim for restore
oahzxl's avatar
oahzxl committed
503
504
        5. inherit computation.
        6. TODO: look into view list to see whether the view is associated with other,
oahzxl's avatar
oahzxl committed
505
506
507
508
509
           if so assgin equal dim according to previous view.

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
510
        """
oahzxl's avatar
oahzxl committed
511
512
        # get data, turn into number
        origin_node = node.args[0]
oahzxl's avatar
oahzxl committed
513
        origin_shape = origin_node.meta["tensor_meta"].shape
oahzxl's avatar
oahzxl committed
514
515
516
517
518
        target_shape = []
        for i in range(1, len(node.args)):
            if isinstance(node.args[i], int):
                target_shape.append(node.args[i])
            else:
oahzxl's avatar
oahzxl committed
519
                target_shape.append(node.args[i].meta["fwd_out"][0])
oahzxl's avatar
oahzxl committed
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538

        # compute the value of -1
        if -1 in target_shape:
            origin_product = 1
            for i in origin_shape:
                origin_product *= i
            target_product = -1
            for i in target_shape:
                target_product *= i
            shape_idx = target_shape.index(-1)
            target_shape[shape_idx] = origin_product // target_product

        # determine changed dim
        len_diff = len(origin_shape) - len(target_shape)
        if len_diff == 1:
            # dim merge
            dim_equal = [i == j for i, j in zip(origin_shape[:-1], target_shape)]
            dim_to = [dim_equal.index(False)]
            dim_from = [dim_equal.index(False), dim_equal.index(False) + 1]
539
            self._add_dim(node_idx, -1)
oahzxl's avatar
oahzxl committed
540
541
542
543
544
        elif len_diff == -1:
            # dim expand
            dim_equal = [i == j for i, j in zip(origin_shape, target_shape[:-1])]
            dim_from = [dim_equal.index(False)]
            dim_to = [dim_equal.index(False), dim_equal.index(False) + 1]
545
            self._del_dim(node_idx, -1)
oahzxl's avatar
oahzxl committed
546
        else:
oahzxl's avatar
oahzxl committed
547
548
549
550
551
552
553
            raise NotImplementedError(
                "shape"
                + str(origin_shape)
                + "and"
                + str(target_shape)
                + "view not implemented"
            )
oahzxl's avatar
oahzxl committed
554
555

        # get new index
oahzxl's avatar
oahzxl committed
556
        origin_trace = self._find_idx_trace_from_node(origin_node)
557
        self._assign_index_as_input(node, node_idx, origin_node)
oahzxl's avatar
oahzxl committed
558
559
        dim_from.reverse()
        for i in dim_from:
560
            self._del_dim(node_idx, i)
oahzxl's avatar
oahzxl committed
561
        for i in dim_to:
562
            self._add_dim(node_idx, i)
oahzxl's avatar
oahzxl committed
563

oahzxl's avatar
oahzxl committed
564
        # inherit computation
oahzxl's avatar
oahzxl committed
565
        compute_log = self._find_compute_trace_from_node(origin_node)
oahzxl's avatar
oahzxl committed
566
567
568
        for i in dim_from:
            if origin_trace[i] in compute_log:
                for j in dim_to:
oahzxl's avatar
oahzxl committed
569
                    self._mark_computation(node, node_idx, [j])
oahzxl's avatar
oahzxl committed
570
                break
oahzxl's avatar
oahzxl committed
571

oahzxl's avatar
oahzxl committed
572
        # log view, not used now
oahzxl's avatar
oahzxl committed
573
574
575
576
577
578
        view_dict = {
            "idx_from": [origin_trace[i] for i in dim_from],
            "dim_from": dim_from,
            "idx_to": [self.idx_trace_list[node_idx]["idx"][i] for i in dim_to],
            "dim_to": dim_to,
        }
oahzxl's avatar
oahzxl committed
579
        self.idx_view_list[node] = view_dict
580

oahzxl's avatar
oahzxl committed
581
582
583
584
585
586
587
    def _merge_equal_idx(self):
        idx_equal = copy.deepcopy(self.idx_trace_equal)
        idx_equal.reverse()
        for idx in idx_equal:
            merge_to = min(idx)
            merge_from = max(idx)
            for trace in self.idx_trace_list:
oahzxl's avatar
oahzxl committed
588
589
590
591
592
                if merge_from in trace["idx"]:
                    trace["idx"] = [
                        merge_to if i == merge_from else i for i in trace["idx"]
                    ]

oahzxl's avatar
oahzxl committed
593
    def trace_index(self):
oahzxl's avatar
oahzxl committed
594
        for idx, node in enumerate(self.node_list):
oahzxl's avatar
oahzxl committed
595
            if node.op == "placeholder":
oahzxl's avatar
oahzxl committed
596
                self._assign_all_index(node, idx)
oahzxl's avatar
oahzxl committed
597
598
            elif node.op == "call_method":
                if "transpose" in node.name:
oahzxl's avatar
oahzxl committed
599
                    self._assign_transpose_index(node, idx)
oahzxl's avatar
oahzxl committed
600
                elif "permute" in node.name:
oahzxl's avatar
oahzxl committed
601
                    self._assign_permute_index(node, idx)
oahzxl's avatar
oahzxl committed
602
                elif "view" in node.name or "reshape" in node.name:
oahzxl's avatar
oahzxl committed
603
                    self._assign_view_reshape_index(node, idx)
oahzxl's avatar
oahzxl committed
604
                elif "unsqueeze" in node.name:
oahzxl's avatar
oahzxl committed
605
                    self._assign_unsqueeze_index(node, idx)
oahzxl's avatar
oahzxl committed
606
                elif any(i in node.name for i in ["to", "contiguous"]):
607
                    self._assgin_no_change_index(node, idx)
oahzxl's avatar
oahzxl committed
608
609
                else:
                    raise NotImplementedError(node.name, "method not implemented yet!")
oahzxl's avatar
oahzxl committed
610
611
            elif node.op == "call_function":
                if "linear" in node.name:
oahzxl's avatar
oahzxl committed
612
                    self._assign_linear_index(node, idx)
oahzxl's avatar
oahzxl committed
613
                elif "matmul" in node.name:
oahzxl's avatar
oahzxl committed
614
                    self._assign_matmul_index(node, idx)
oahzxl's avatar
oahzxl committed
615
                elif "softmax" in node.name:
oahzxl's avatar
oahzxl committed
616
                    self._assign_softmax_index(node, idx)
oahzxl's avatar
oahzxl committed
617
                elif any(n in node.name for n in ["mul", "add", "sigmoid", "relu"]):
oahzxl's avatar
oahzxl committed
618
                    self._assign_elementwise_index(node, idx)
oahzxl's avatar
oahzxl committed
619
                elif "ones_like" in node.name:
oahzxl's avatar
oahzxl committed
620
                    self._assign_ones_like_index(node, idx)
oahzxl's avatar
oahzxl committed
621
                elif "dropout" in node.name:
oahzxl's avatar
oahzxl committed
622
                    self._assign_dropout_index(node, idx)
oahzxl's avatar
oahzxl committed
623
                elif "einsum" in node.name:
624
                    self._assign_einsum_index(node, idx)
oahzxl's avatar
oahzxl committed
625
626
627
628
                elif "getattr" in node.name:
                    continue  # get attr like shape
                elif "getitem" in node.name:
                    continue  # get item in list
oahzxl's avatar
oahzxl committed
629
                else:
oahzxl's avatar
oahzxl committed
630
631
632
633
634
                    raise NotImplementedError(
                        node.name, "function not implemented yet!"
                    )
            elif node.op == "call_module":
                if any(n in node.name for n in ["layernorm", "norm"]):
oahzxl's avatar
oahzxl committed
635
                    self._assign_layernorm_index(node, idx)
oahzxl's avatar
oahzxl committed
636
637
                else:
                    raise NotImplementedError(node.name, "module not implemented yet!")
oahzxl's avatar
oahzxl committed
638
639
640
            elif node.op == "get_attr":
                self._assign_all_index(node, idx)  # get param
            elif node.op == "output":
oahzxl's avatar
oahzxl committed
641
                continue
oahzxl's avatar
oahzxl committed
642
643
            else:
                raise NotImplementedError(node.op, "op not implemented yet!")
644
        # self._merge_equal_idx()
oahzxl's avatar
oahzxl committed
645

oahzxl's avatar
oahzxl committed
646
647
648
649
650
651
652
653
654
655
656
657
    def check_index_source(self, start_dim, start_node, start_idx, end_dim, end_node):
        """
        Check 2 given index: one index should be source of the other
        Args:
            start_idx(int): start node chunk dim
            start_node(node): start node
            end_idx(int): end node chunk dim
            end_node(node): end node

        Returns:
            bool: True if check pass
        """
oahzxl's avatar
oahzxl committed
658
        start_node_idx = _find_idx_by_name(start_node.name, self.node_list)
oahzxl's avatar
oahzxl committed
659
        end_node_trace = self._find_trace_from_node(end_node)
oahzxl's avatar
oahzxl committed
660
661
662
663
        end_node_trace_source = end_node_trace["source"][end_dim]
        sorted_source = sorted(
            end_node_trace_source.items(), key=lambda d: d[0], reverse=True
        )
oahzxl's avatar
oahzxl committed
664
        for node_idx, node_dim in sorted_source:
oahzxl's avatar
oahzxl committed
665
            if node_idx == start_node_idx and start_dim in node_dim:
oahzxl's avatar
oahzxl committed
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
                return True
            # it means we meet a node outside the loop, and the node is not input node
            if node_idx < start_idx:
                return False
        return False

    def check_index_compute(self, start_idx, end_dim, end_node, end_idx):
        """
        Check 2 given index: check they haven't been computed in the source trace.
        Args:
            start_idx(int): start node chunk dim
            start_node(node): start node
            end_idx(int): end node chunk dim
            end_node(node): end node

        Returns:
            bool: True if check pass
        """
        end_node_trace = self._find_trace_from_node(end_node)
oahzxl's avatar
oahzxl committed
685
        end_node_compute = end_node_trace["compute"][end_dim]
oahzxl's avatar
oahzxl committed
686
687
        if any(start_idx <= i <= end_idx for i in end_node_compute):
            return False
688
        return True
oahzxl's avatar
oahzxl committed
689

690
    def get_node_chunk_dim(self, node_from, node_from_dim, node_to):
oahzxl's avatar
oahzxl committed
691
692
        node_from_source = self._find_source_trace_from_node(node_from)
        dim_source = node_from_source[node_from_dim]
oahzxl's avatar
oahzxl committed
693
        node_to_idx = _find_idx_by_name(node_to.name, self.node_list)
oahzxl's avatar
oahzxl committed
694
695
696
697
698
        for k, v in dim_source.items():
            if k == node_to_idx:
                return v
        return None

699
    def _find_inherit_dim(self, input_node, input_dim, node):
oahzxl's avatar
oahzxl committed
700
        input_node_idx = _find_idx_by_name(input_node.name, self.node_list)
701
702
703
704
        node_trace_source = self._find_source_trace_from_node(node)
        for node_dim in range(len(_get_node_shape(node))):
            if (
                input_node_idx in node_trace_source[node_dim]
oahzxl's avatar
oahzxl committed
705
                and input_dim[0] in node_trace_source[node_dim][input_node_idx]
706
            ):
oahzxl's avatar
oahzxl committed
707
708
                return node_dim
        return None
709

oahzxl's avatar
oahzxl committed
710
    def check_index_duplicate(self, chunk_infos, return_dim=False):
711
712
713
        input_dim_after_node = {}
        for input_node_idx, input_node in enumerate(chunk_infos["inputs"]):
            for k, v in chunk_infos["inputs_dim"][input_node_idx].items():
oahzxl's avatar
oahzxl committed
714
                inherit_dim = self._find_inherit_dim(input_node, v, self.node_list[k])
oahzxl's avatar
oahzxl committed
715
716
                if inherit_dim:
                    input_dim_after_node[k] = inherit_dim
717

oahzxl's avatar
oahzxl committed
718
        for node in self.node_list[
719
720
721
722
723
            chunk_infos["region"][0] : chunk_infos["region"][1] + 1
        ]:
            if _is_non_compute_node_except_placeholder(node):
                continue
            count = 0
oahzxl's avatar
oahzxl committed
724
            duplicate_dims = []
725
726
            node_trace_source = self._find_source_trace_from_node(node)
            for node_dim in range(len(_get_node_shape(node))):
oahzxl's avatar
oahzxl committed
727
728
                duplicate_dim = []
                duplicate_flag = False
729
730
731
                dim_source = node_trace_source[node_dim]
                for k, v in dim_source.items():
                    if chunk_infos["region"][0] <= k <= chunk_infos["region"][1]:
oahzxl's avatar
oahzxl committed
732
733
734
735
736
737
738
                        if k in input_dim_after_node and input_dim_after_node[k] in v:
                            duplicate_flag = True
                            duplicate_dim.append((k, v))
                duplicate_dims.append(duplicate_dim)
                if duplicate_flag:
                    count += 1

739
            if count > 1:
oahzxl's avatar
oahzxl committed
740
741
742
743
744
745
746
747
                if return_dim:
                    return False, duplicate_dims
                else:
                    return False
        if return_dim:
            return True, None
        else:
            return True
748

oahzxl's avatar
oahzxl committed
749
750
751
752
753
754
755
756
757
758
759
760
    def _assgin_single_node_flow(
        self,
        arg_node,
        start_idx,
        end_idx,
        cur_node_dim,
        cur_node_compute,
        cur_node_source,
        cur_node_fix_dim,
        all_node_info,
        next_node_list,
    ):
oahzxl's avatar
oahzxl committed
761
        arg_idx = _find_idx_by_name(arg_node.name, self.node_list)
oahzxl's avatar
oahzxl committed
762
763
764
        # arg in chunk range or be inputs
        if not (start_idx <= arg_idx < end_idx):
            return True
oahzxl's avatar
oahzxl committed
765

oahzxl's avatar
oahzxl committed
766
767
768
769
770
771
772
773
774
775
776
        # find arg dim
        if cur_node_dim is not None:
            # dim is computed
            if arg_idx in cur_node_compute[cur_node_dim]:
                return False
            if arg_idx not in cur_node_source[cur_node_dim]:
                arg_dim = None
            else:
                arg_dim = cur_node_source[cur_node_dim][arg_idx][0]
        else:
            arg_dim = None
oahzxl's avatar
oahzxl committed
777

oahzxl's avatar
oahzxl committed
778
779
780
781
782
783
784
        # get fix dim
        arg_fix_dim = []
        if cur_node_dim is not None:
            for i in cur_node_fix_dim:
                fix_dim_source = cur_node_source[i]
                if arg_idx in fix_dim_source:
                    arg_fix_dim.append(fix_dim_source[arg_idx][0])
oahzxl's avatar
oahzxl committed
785

oahzxl's avatar
oahzxl committed
786
787
        # if already in node_info, arg dim must be same
        if arg_node in all_node_info:
oahzxl's avatar
oahzxl committed
788
            if all_node_info[arg_node]["chunk_dim"] != arg_dim:
oahzxl's avatar
oahzxl committed
789
                return False
oahzxl's avatar
oahzxl committed
790
791
792
            all_node_info[arg_node]["fix_dim"] = list(
                set(all_node_info[arg_node]["fix_dim"] + arg_fix_dim)
            )
oahzxl's avatar
oahzxl committed
793
794
        # else add it to list
        else:
oahzxl's avatar
oahzxl committed
795
796
            all_node_info[arg_node] = {"chunk_dim": arg_dim, "fix_dim": arg_fix_dim}

oahzxl's avatar
oahzxl committed
797
798
        next_node_list.append(arg_node)
        return True
oahzxl's avatar
oahzxl committed
799

oahzxl's avatar
oahzxl committed
800
    def flow_search(self, start_idx, start_dim, end_idx, end_dim):
oahzxl's avatar
oahzxl committed
801
802
803
804
805
806
        inputs, outputs = _find_chunk_compute_input_and_output_nodes(
            self.node_list[start_idx : end_idx + 1]
        )
        # only single ouput
        if len(outputs) > 1:
            return None
oahzxl's avatar
oahzxl committed
807

oahzxl's avatar
oahzxl committed
808
        cur_node_list = [self.node_list[end_idx]]  # start from the last node
oahzxl's avatar
oahzxl committed
809
810
        all_node_info = {cur_node_list[0]: {"chunk_dim": end_dim, "fix_dim": []}}

oahzxl's avatar
oahzxl committed
811
812
813
814
815
        while len(cur_node_list) > 0:
            next_node_list = []

            for cur_node in cur_node_list:
                # get cur node info
oahzxl's avatar
oahzxl committed
816
817
                cur_node_chunk_dim = all_node_info[cur_node]["chunk_dim"]
                cur_node_fix_dim = all_node_info[cur_node]["fix_dim"]
oahzxl's avatar
oahzxl committed
818
                cur_node_idx = _find_idx_by_name(cur_node.name, self.node_list)
oahzxl's avatar
oahzxl committed
819
                if cur_node_chunk_dim:
oahzxl's avatar
oahzxl committed
820
821
                    cur_node_compute = self._find_compute_trace_from_node(cur_node)
                    cur_node_source = self._find_source_trace_from_node(cur_node)
oahzxl's avatar
oahzxl committed
822
823
                else:
                    cur_node_compute = cur_node_source = None
oahzxl's avatar
oahzxl committed
824

oahzxl's avatar
oahzxl committed
825
826
827
828
829
830
831
832
                # get all valid args
                arg_list = []
                for arg in cur_node.args:
                    if type(arg) != type(cur_node):
                        continue
                    if _is_non_compute_node(arg):
                        continue
                    arg_list.append(arg)
oahzxl's avatar
oahzxl committed
833
834
835
836
837
838
839
840
841
842
843
                    flow_flag = self._assgin_single_node_flow(
                        arg,
                        start_idx,
                        end_idx,
                        cur_node_chunk_dim,
                        cur_node_compute,
                        cur_node_source,
                        cur_node_fix_dim,
                        all_node_info,
                        next_node_list,
                    )
oahzxl's avatar
oahzxl committed
844
845
                    if flow_flag == False:
                        return None
oahzxl's avatar
oahzxl committed
846

oahzxl's avatar
oahzxl committed
847
848
849
                if len(arg_list) == 2:
                    if any(i in cur_node.name for i in ["add", "mul"]):
                        for arg in arg_list:
oahzxl's avatar
oahzxl committed
850
851
                            if not (
                                start_idx
oahzxl's avatar
oahzxl committed
852
                                <= _find_idx_by_name(arg.name, self.node_list)
oahzxl's avatar
oahzxl committed
853
854
                                < end_idx
                            ):
oahzxl's avatar
oahzxl committed
855
                                continue
oahzxl's avatar
oahzxl committed
856
857
                            arg_chunk_dim = all_node_info[arg]["chunk_dim"]
                            arg_fix_dim = all_node_info[arg]["fix_dim"]
oahzxl's avatar
oahzxl committed
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
                            arg_shape = _get_node_shape(arg)
                            # add all dim as fix dim except chunk dim
                            for i, shape in enumerate(arg_shape):
                                if shape != 1 and i != cur_node_chunk_dim:
                                    if i == arg_chunk_dim:
                                        return None
                                    if i not in arg_fix_dim:
                                        arg_fix_dim.append(i)
                    elif "einsum" in cur_node.name:
                        pass
                    elif "matmul" in cur_node.name:
                        pass
                    else:
                        raise NotImplementedError()
            cur_node_list = next_node_list
oahzxl's avatar
oahzxl committed
873

oahzxl's avatar
oahzxl committed
874
875
876
877
        inputs_dim = []
        remove_inputs = []
        for input_node in inputs:
            input_dict = {}
oahzxl's avatar
oahzxl committed
878
            input_node_idx = _find_idx_by_name(input_node.name, self.node_list)
oahzxl's avatar
oahzxl committed
879
880
881
882
883
            for user in input_node.users.keys():
                if _is_non_compute_node(user):
                    continue
                user_idx = _find_idx_by_name(user.name, self.node_list)
                if start_idx <= user_idx <= end_idx:
oahzxl's avatar
oahzxl committed
884
                    chunk_dim = all_node_info[user]["chunk_dim"]
oahzxl's avatar
oahzxl committed
885
                    if chunk_dim is not None:
oahzxl's avatar
oahzxl committed
886
887
888
889
890
                        user_source = self._find_source_trace_from_node(user)[chunk_dim]
                        if input_node_idx in user_source:
                            input_dict[user_idx] = user_source[input_node_idx]
                        else:
                            return None
oahzxl's avatar
oahzxl committed
891
892
893
894
895
896
897
            if len(input_dict) == 0:
                remove_inputs.append(input_node)
            else:
                inputs_dim.append(input_dict)
        for i in remove_inputs:
            if i in inputs:
                inputs.remove(i)
oahzxl's avatar
oahzxl committed
898

oahzxl's avatar
oahzxl committed
899
900
901
902
903
904
905
        chunk_info = {
            "region": (start_idx, end_idx),
            "inputs": inputs,
            "inputs_non_chunk": [],
            "inputs_dim": inputs_dim,
            "outputs": outputs,
            "outputs_dim": end_dim,
oahzxl's avatar
oahzxl committed
906
            "node_chunk_dim": all_node_info,
oahzxl's avatar
oahzxl committed
907
908
            "args": {},
        }
oahzxl's avatar
oahzxl committed
909

oahzxl's avatar
oahzxl committed
910
911
912
913
        # move useless nodes ahead of loop
        # get all possible prepose nodes
        maybe_prepose_nodes = []
        for node, node_info in all_node_info.items():
oahzxl's avatar
oahzxl committed
914
            if node_info["chunk_dim"] is None:
oahzxl's avatar
oahzxl committed
915
                maybe_prepose_nodes.append(node)
oahzxl's avatar
oahzxl committed
916
        maybe_prepose_nodes.sort(
oahzxl's avatar
oahzxl committed
917
            key=lambda x: _find_idx_by_name(x.name, self.node_list),
oahzxl's avatar
oahzxl committed
918
919
            reverse=True,
        )  # from last node to first node
oahzxl's avatar
oahzxl committed
920
921
922
923
924
925
        prepose_nodes = []
        # set every node as root, search its args, if all legal, turn root and args as prepose nodes
        while len(maybe_prepose_nodes) > 0:
            tmp_cur_prepose_nodes = [maybe_prepose_nodes[0]]
            tmp_cur_related_prepose_nodes = []
            prepose_flag = True
oahzxl's avatar
oahzxl committed
926

oahzxl's avatar
oahzxl committed
927
928
            # loop cur node's all arg until out of chunk
            while len(tmp_cur_prepose_nodes) > 0:
oahzxl's avatar
oahzxl committed
929
930
                if prepose_flag == False:
                    break
oahzxl's avatar
oahzxl committed
931
932
933
                tmp_next_prepose_nodes = []
                tmp_cur_related_prepose_nodes.extend(tmp_cur_prepose_nodes)
                for cur_prepose_node in tmp_cur_prepose_nodes:
oahzxl's avatar
oahzxl committed
934
935
                    if prepose_flag == False:
                        break
oahzxl's avatar
oahzxl committed
936
937
938
939
                    for cur_prepose_node_arg in cur_prepose_node.args:
                        if type(cur_prepose_node_arg) != type(cur_prepose_node):
                            continue
                        # out of loop
oahzxl's avatar
oahzxl committed
940
941
942
943
944
945
946
                        if not (
                            start_idx
                            <= _find_idx_by_name(
                                cur_prepose_node_arg.name, self.node_list
                            )
                            < end_idx
                        ):
oahzxl's avatar
oahzxl committed
947
948
949
                            continue
                        # compute op in loop
                        elif cur_prepose_node_arg in all_node_info:
oahzxl's avatar
oahzxl committed
950
                            if all_node_info[cur_prepose_node_arg]["chunk_dim"] is None:
oahzxl's avatar
oahzxl committed
951
952
953
                                tmp_next_prepose_nodes.append(cur_prepose_node_arg)
                            else:
                                prepose_flag = False
oahzxl's avatar
oahzxl committed
954
                                break
oahzxl's avatar
oahzxl committed
955
956
957
958
                        # non compute op
                        else:
                            tmp_next_prepose_nodes.append(cur_prepose_node_arg)
                tmp_cur_prepose_nodes = tmp_next_prepose_nodes
oahzxl's avatar
oahzxl committed
959

oahzxl's avatar
oahzxl committed
960
961
962
963
964
965
966
967
968
969
            if prepose_flag == False:
                maybe_prepose_nodes.remove(maybe_prepose_nodes[0])
                continue
            else:
                for n in tmp_cur_related_prepose_nodes:
                    if n not in prepose_nodes:
                        prepose_nodes.append(n)
                    if n in maybe_prepose_nodes:
                        maybe_prepose_nodes.remove(n)
        # sort by index
oahzxl's avatar
oahzxl committed
970
        prepose_nodes.sort(key=lambda x: _find_idx_by_name(x.name, self.node_list))
oahzxl's avatar
oahzxl committed
971
        chunk_info["args"]["prepose_nodes"] = prepose_nodes
oahzxl's avatar
oahzxl committed
972

oahzxl's avatar
oahzxl committed
973
        # we need to log input nodes to avoid deleteing them in the loop
oahzxl's avatar
oahzxl committed
974
975
976
977
        chunk_node_list = self.node_list[start_idx : end_idx + 1]
        # also need to get some prepose node's arg out of non_chunk_inputs
        for n in prepose_nodes:
            chunk_node_list.remove(n)
oahzxl's avatar
oahzxl committed
978
        non_chunk_inputs = _find_chunk_all_input_nodes(chunk_node_list)
oahzxl's avatar
oahzxl committed
979
        for i in non_chunk_inputs:
oahzxl's avatar
oahzxl committed
980
            if i not in chunk_info["inputs"]:
oahzxl's avatar
oahzxl committed
981
                chunk_info["inputs_non_chunk"].append(i)
oahzxl's avatar
oahzxl committed
982

oahzxl's avatar
oahzxl committed
983
984
        # reassgin reshape size, some size may have changed due to chunk
        chunk_info = self._reassgin_reshape_size(chunk_info)
oahzxl's avatar
oahzxl committed
985

oahzxl's avatar
oahzxl committed
986
        return chunk_info
oahzxl's avatar
oahzxl committed
987

oahzxl's avatar
oahzxl committed
988
    def _reassgin_reshape_size(self, chunk_info):
oahzxl's avatar
oahzxl committed
989
        chunk_region = chunk_info["region"]
oahzxl's avatar
oahzxl committed
990
        reshape_size = {}
oahzxl's avatar
oahzxl committed
991
992
993
        chunk_shape = _get_node_shape(chunk_info["outputs"][0])[
            chunk_info["outputs_dim"]
        ]
oahzxl's avatar
oahzxl committed
994
995
        for node in self.node_list[chunk_region[0] : chunk_region[1] + 1]:
            if any(i in node.name for i in ["reshape", "view"]):
oahzxl's avatar
oahzxl committed
996
997
                reshape_args = node.args[1:]
                reshape_log = self.idx_view_list[node]
oahzxl's avatar
oahzxl committed
998
                chunk_dim = chunk_info["node_chunk_dim"][node]["chunk_dim"]
oahzxl's avatar
oahzxl committed
999
1000
                reshape_size[node.name] = {}
                for reshape_arg_dim, reshape_arg in enumerate(reshape_args):
oahzxl's avatar
oahzxl committed
1001
                    if reshape_arg_dim in reshape_log["dim_to"]:
oahzxl's avatar
oahzxl committed
1002
1003
                        continue
                    if reshape_arg_dim == chunk_dim:
oahzxl's avatar
oahzxl committed
1004
1005
1006
                        reshape_size[node.name][reshape_arg.name] = (
                            "min(chunk_size, %d - chunk_idx)" % chunk_shape
                        )
oahzxl's avatar
oahzxl committed
1007
        chunk_info["reshape_size"] = reshape_size
oahzxl's avatar
oahzxl committed
1008
1009
        return chunk_info

oahzxl's avatar
oahzxl committed
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
    def _get_reorder_map(self, chunk_info):
        reorder_map = {i: i for i in range(len(self.node_list))}

        chunk_region_start = chunk_info["region"][0]
        chunk_region_end = chunk_info["region"][1]
        chunk_prepose_nodes = chunk_info["args"]["prepose_nodes"]
        chunk_prepose_nodes_idx = [
            _find_idx_by_name(i.name, self.node_list) for i in chunk_prepose_nodes
        ]
        # put prepose nodes ahead
        for idx, n in enumerate(chunk_prepose_nodes):
            n_idx = chunk_prepose_nodes_idx[idx]
            reorder_map[n_idx] = chunk_region_start + idx
        # put other nodes after prepose nodes
        for n in self.node_list[chunk_region_start : chunk_region_end + 1]:
            if n in chunk_prepose_nodes:
                continue
            n_idx = _find_idx_by_name(n.name, self.node_list)
            pos = sum([n_idx < i for i in chunk_prepose_nodes_idx])
            reorder_map[n_idx] = n_idx + pos

        return reorder_map

    def _reorder_chunk_info(self, chunk_info, reorder_map):
        # update chunk info
        chunk_info["region"] = (
            chunk_info["region"][0] + len(chunk_info["args"]["prepose_nodes"]),
            chunk_info["region"][1],
        )
        for idx, input_dim in enumerate(chunk_info["inputs_dim"]):
            new_input_dim = {}
            for k, v in input_dim.items():
                new_input_dim[reorder_map[k]] = v
            chunk_info["inputs_dim"][idx] = new_input_dim
        return chunk_info

    def _update_all_reorder_map(self, reorder_map):
        for origin_idx, map_idx in self.all_reorder_map.items():
            self.all_reorder_map[origin_idx] = reorder_map[map_idx]

    def _reorder_self_node_list(self, reorder_map):
        new_node_list = [None for _ in range(len(self.node_list))]
        for old_idx, new_idx in reorder_map.items():
            new_node_list[new_idx] = self.node_list[old_idx]
        self.node_list = new_node_list

    def _reorder_idx_trace(self, reorder_map):
        # reorder list
        new_idx_trace_list = [None for _ in range(len(self.idx_trace_list))]
        for old_idx, new_idx in reorder_map.items():
            new_idx_trace_list[new_idx] = self.idx_trace_list[old_idx]
        self.idx_trace_list = new_idx_trace_list
        # update compute
        for idx_trace in self.idx_trace_list:
            compute = idx_trace["compute"]
            for dim_compute in compute:
                for idx, i in enumerate(dim_compute):
                    dim_compute[idx] = reorder_map[i]
        # update source
        for idx_trace in self.idx_trace_list:
            source = idx_trace["source"]
            for dim_idx, dim_source in enumerate(source):
                new_dim_source = {}
                for k, v in dim_source.items():
                    new_dim_source[reorder_map[k]] = v
                source[dim_idx] = new_dim_source

    def reorder_all(self, chunk_info):
        if chunk_info is None:
            return chunk_info
        if len(chunk_info["args"]["prepose_nodes"]) == 0:
            return chunk_info
        reorder_map = self._get_reorder_map(chunk_info)
        self._update_all_reorder_map(reorder_map)
        self._reorder_idx_trace(reorder_map)
        self._reorder_self_node_list(reorder_map)
        chunk_info = self._reorder_chunk_info(chunk_info, reorder_map)
        return chunk_info

    def reorder_node_list(self, node_list):
        new_node_list = [None for _ in range(len(node_list))]
        for old_idx, new_idx in self.all_reorder_map.items():
            new_node_list[new_idx] = node_list[old_idx]
        return new_node_list

oahzxl's avatar
oahzxl committed
1095

oahzxl's avatar
oahzxl committed
1096
class MemoryEstimator(object):
oahzxl's avatar
oahzxl committed
1097
1098
    def __init__(self, index_tracer: IndexTracer) -> None:
        self.index_tracer = index_tracer
oahzxl's avatar
oahzxl committed
1099

oahzxl's avatar
oahzxl committed
1100
    def _get_meta_node_size(self, x):
oahzxl's avatar
oahzxl committed
1101
        x = x.meta["tensor_meta"]
oahzxl's avatar
oahzxl committed
1102
1103
        x = x.numel * torch.tensor([], dtype=x.dtype).element_size()
        return x
oahzxl's avatar
oahzxl committed
1104

oahzxl's avatar
oahzxl committed
1105
    def _get_output_node(self, n):
oahzxl's avatar
oahzxl committed
1106
1107
1108
1109
1110
        fwd_out = {
            x.uuid: x
            for x in n.meta["fwd_out"]
            if isinstance(x, torch.Tensor) and hasattr(x, "uuid")
        }
oahzxl's avatar
oahzxl committed
1111
1112
        out_size = activation_size(fwd_out)
        out_node = [n.name] if out_size > 0 else []
oahzxl's avatar
oahzxl committed
1113
1114
        # if any(i in n.name for i in ['transpose', 'permute', 'view']):
        #     out_size = 0
oahzxl's avatar
oahzxl committed
1115
        return out_size, out_node
oahzxl's avatar
oahzxl committed
1116

oahzxl's avatar
oahzxl committed
1117
1118
    def _get_output_node_size(self, n):
        return self._get_output_node(n)[0]
oahzxl's avatar
oahzxl committed
1119

oahzxl's avatar
oahzxl committed
1120
1121
    def _add_active_node(self, n, active_list):
        new_active = self._get_output_node(n)[1]
oahzxl's avatar
oahzxl committed
1122
        if n.op == "placeholder":
oahzxl's avatar
oahzxl committed
1123
            new_active.append(n.name)
oahzxl's avatar
oahzxl committed
1124
1125
1126
        for i in new_active:
            if i not in active_list:
                active_list.append(i)
oahzxl's avatar
oahzxl committed
1127

oahzxl's avatar
oahzxl committed
1128
    def _get_delete_node(self, user, user_to_last_uses, to_keep=None):
oahzxl's avatar
oahzxl committed
1129
1130
        delete_size = 0
        delete_node = []
oahzxl's avatar
oahzxl committed
1131
        if user.op not in ("output",):
oahzxl's avatar
oahzxl committed
1132
            nodes_to_delete = user_to_last_uses.get(user, [])
oahzxl's avatar
oahzxl committed
1133
1134
1135
1136
1137
1138
1139
1140
            if to_keep is not None:
                keep_list = []
                for n in nodes_to_delete:
                    if n.name in to_keep:
                        keep_list.append(n)
                for n in keep_list:
                    if n in nodes_to_delete:
                        nodes_to_delete.remove(n)
oahzxl's avatar
oahzxl committed
1141
1142
1143
1144
1145
1146
            if len(nodes_to_delete):
                out_node = [self._get_output_node(i) for i in nodes_to_delete]
                delete_size = sum([i[0] for i in out_node])
                for i in range(len(out_node)):
                    if out_node[i][0] > 0:
                        delete_node.append(out_node[i][1][0])
oahzxl's avatar
oahzxl committed
1147
                    elif nodes_to_delete[i].op == "placeholder":
oahzxl's avatar
oahzxl committed
1148
                        delete_node.append(nodes_to_delete[i].name)
oahzxl's avatar
oahzxl committed
1149
1150
                    # elif any(j in nodes_to_delete[i].name for j in ['transpose', 'permute', 'view']):
                    #     delete_node.append(nodes_to_delete[i].name)
oahzxl's avatar
oahzxl committed
1151
        return delete_size, delete_node
oahzxl's avatar
oahzxl committed
1152

oahzxl's avatar
oahzxl committed
1153
1154
    def _get_delete_node_size(self, user, user_to_last_uses, to_keep):
        return self._get_delete_node(user, user_to_last_uses, to_keep)[0]
oahzxl's avatar
oahzxl committed
1155

oahzxl's avatar
oahzxl committed
1156
    def _remove_deactive_node(self, user, user_to_last_uses, active_list):
oahzxl's avatar
oahzxl committed
1157
1158
        delete_node = self._get_delete_node(user, user_to_last_uses)[1]
        for i in delete_node:
oahzxl's avatar
oahzxl committed
1159
1160
            if i in active_list:
                active_list.remove(i)
oahzxl's avatar
oahzxl committed
1161
1162
1163
1164

    def _get_chunk_inputs_size(
        self, chunk_inputs, chunk_inputs_non_chunk, node_list, chunk_end_idx
    ):
oahzxl's avatar
oahzxl committed
1165
1166
1167
        nodes_to_delete = []
        for chunk_input in chunk_inputs + chunk_inputs_non_chunk:
            chunk_input_users = chunk_input.users.keys()
oahzxl's avatar
oahzxl committed
1168
1169
1170
            chunk_input_users_idx = [
                _find_idx_by_name(i.name, node_list) for i in chunk_input_users
            ]
oahzxl's avatar
oahzxl committed
1171
1172
1173
1174
1175
1176
            if all(i <= chunk_end_idx for i in chunk_input_users_idx):
                if chunk_input not in nodes_to_delete:
                    nodes_to_delete.append(chunk_input)
        out_node = [self._get_output_node(i) for i in nodes_to_delete]
        delete_size = sum([i[0] for i in out_node])
        return delete_size
oahzxl's avatar
oahzxl committed
1177

oahzxl's avatar
oahzxl committed
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
    def _get_last_usr(self, nodes):
        node_to_last_use: Dict[Node, Node] = {}
        user_to_last_uses: Dict[Node, List[Node]] = {}

        def register_last_uses(n: Node, user: Node):
            if n not in node_to_last_use:
                node_to_last_use[n] = user
                user_to_last_uses.setdefault(user, []).append(n)

        for node in reversed(nodes):
            map_arg(node.args, lambda n: register_last_uses(n, node))
            map_arg(node.kwargs, lambda n: register_last_uses(n, node))
        return user_to_last_uses

    def _get_contiguous_memory(self, node, not_contiguous_list, delete=False):
        mem = 0
oahzxl's avatar
oahzxl committed
1194
1195
        not_contiguous_ops = ["permute"]
        inherit_contiguous_ops = ["transpose", "view"]
oahzxl's avatar
oahzxl committed
1196

oahzxl's avatar
oahzxl committed
1197
1198
1199
        if node.op == "call_function" and any(
            n in node.name for n in ["matmul", "reshape"]
        ):
oahzxl's avatar
oahzxl committed
1200
1201
1202
1203
            for n in node.args:
                if n in not_contiguous_list:
                    # matmul won't change origin tensor, but create a tmp copy
                    mem += self._get_output_node_size(n)
oahzxl's avatar
oahzxl committed
1204
        elif node.op == "call_module":
oahzxl's avatar
oahzxl committed
1205
1206
1207
1208
1209
            for n in node.args:
                if n in not_contiguous_list:
                    # module will just make origin tensor to contiguous
                    if delete:
                        not_contiguous_list.remove(n)
oahzxl's avatar
oahzxl committed
1210
1211
1212
        elif node.op == "call_method" and any(
            i in node.name for i in not_contiguous_ops
        ):
oahzxl's avatar
oahzxl committed
1213
1214
1215
1216
            if node not in not_contiguous_list:
                not_contiguous_list.append(node)
        return mem

oahzxl's avatar
oahzxl committed
1217
1218
1219
    def _get_chunk_ratio(self, node, chunk_node_dim, chunk_size):
        if node not in chunk_node_dim:
            return 1.0
oahzxl's avatar
oahzxl committed
1220
        node_shape = _get_node_shape(node)
oahzxl's avatar
oahzxl committed
1221
        chunk_dim = chunk_node_dim[node]["chunk_dim"]
oahzxl's avatar
oahzxl committed
1222
1223
1224
1225
        if chunk_dim is None:
            return 1.0
        else:
            return float(chunk_size) / node_shape[chunk_dim]
oahzxl's avatar
oahzxl committed
1226

oahzxl's avatar
oahzxl committed
1227
    def _get_chunk_delete_node_size(
oahzxl's avatar
oahzxl committed
1228
        self, user, user_to_last_uses, chunk_ratio, chunk_inputs_names
oahzxl's avatar
oahzxl committed
1229
    ):
oahzxl's avatar
oahzxl committed
1230
1231
        # if any(j in user.name for j in ['transpose', 'permute', 'view']):
        #     return 0
oahzxl's avatar
oahzxl committed
1232
        if user.op in ("placeholder", "output"):
oahzxl's avatar
oahzxl committed
1233
1234
1235
1236
            return 0
        nodes_to_delete = user_to_last_uses.get(user, [])
        delete_size = 0
        for n in nodes_to_delete:
oahzxl's avatar
oahzxl committed
1237
1238
1239
            if n.name in chunk_inputs_names:
                continue
            delete_size += self._get_output_node_size(n) * chunk_ratio
oahzxl's avatar
oahzxl committed
1240
        return delete_size
oahzxl's avatar
oahzxl committed
1241

oahzxl's avatar
oahzxl committed
1242
1243
1244
1245
    def _print_mem_log(self, log, nodes, title=None):
        if title:
            print(title)
        for idx, (l, n) in enumerate(zip(log, nodes)):
oahzxl's avatar
oahzxl committed
1246
            print("%s:%.2f \t" % (n.name, l), end="")
oahzxl's avatar
oahzxl committed
1247
1248
1249
1250
            if (idx + 1) % 3 == 0:
                print("")
        print("\n")

oahzxl's avatar
oahzxl committed
1251
1252
1253
1254
    def _print_compute_op_mem_log(self, log, nodes, title=None):
        if title:
            print(title)
        for idx, (l, n) in enumerate(zip(log, nodes)):
oahzxl's avatar
oahzxl committed
1255
            if n.op in ["placeholder", "get_attr", "output"]:
oahzxl's avatar
oahzxl committed
1256
                continue
oahzxl's avatar
oahzxl committed
1257
            if any(i in n.name for i in ["getitem", "getattr"]):
oahzxl's avatar
oahzxl committed
1258
                continue
oahzxl's avatar
oahzxl committed
1259
            print("%s:%.2f \t" % (n.name, l), end="")
oahzxl's avatar
oahzxl committed
1260
1261
1262
            if (idx + 1) % 3 == 0:
                print("")
        print("\n")
oahzxl's avatar
oahzxl committed
1263
1264
1265

    def estimate_chunk_inference_mem(
        self,
oahzxl's avatar
oahzxl committed
1266
        node_list,
oahzxl's avatar
oahzxl committed
1267
        chunk_infos=None,
oahzxl's avatar
oahzxl committed
1268
        print_mem=False,
oahzxl's avatar
oahzxl committed
1269
    ):
oahzxl's avatar
oahzxl committed
1270
1271
1272
        act_memory = 0.0
        act_memory_peak_log = []
        act_memory_after_node_log = []
oahzxl's avatar
oahzxl committed
1273
1274
        active_node_list = []
        active_node_list_log = []
oahzxl's avatar
oahzxl committed
1275
        not_contiguous_list = []
oahzxl's avatar
oahzxl committed
1276
1277
1278
        user_to_last_uses = self._get_last_usr(node_list)
        user_to_last_uses_no_free_var = self._get_last_usr(node_list)
        _delete_free_var_from_last_use(user_to_last_uses_no_free_var)
oahzxl's avatar
oahzxl committed
1279

oahzxl's avatar
oahzxl committed
1280
        use_chunk = True if chunk_infos is not None else False
oahzxl's avatar
oahzxl committed
1281
        chunk_within = False
oahzxl's avatar
oahzxl committed
1282
        chunk_region_idx = None
oahzxl's avatar
oahzxl committed
1283
        chunk_ratio = 1  # use it to estimate chunk mem
oahzxl's avatar
oahzxl committed
1284
        chunk_inputs_names = []
oahzxl's avatar
oahzxl committed
1285

oahzxl's avatar
oahzxl committed
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
        if use_chunk:
            chunk_regions = [i["region"] for i in chunk_infos]
            chunk_starts = [i[0] for i in chunk_regions]
            chunk_ends = [i[1] for i in chunk_regions]
            chunk_inputs = [i["inputs"] for i in chunk_infos]
            chunk_inputs_non_chunk = [i["inputs_non_chunk"] for i in chunk_infos]
            chunk_inputs_names = [j.name for i in chunk_inputs for j in i] + [
                j.name for i in chunk_inputs_non_chunk for j in i
            ]
            chunk_outputs = [i["outputs"][0] for i in chunk_infos]
oahzxl's avatar
oahzxl committed
1296
            chunk_node_dim = [i["node_chunk_dim"] for i in chunk_infos]
1297
1298
1299
            chunk_sizes = [
                i["chunk_size"] if "chunk_size" in i else 1 for i in chunk_infos
            ]
oahzxl's avatar
oahzxl committed
1300
1301
1302

        for idx, node in enumerate(node_list):
            # if node in chunk start nodes, change chunk ratio and add chunk_tensor
oahzxl's avatar
oahzxl committed
1303
            if use_chunk and idx in chunk_starts:
oahzxl's avatar
oahzxl committed
1304
                chunk_within = True
oahzxl's avatar
oahzxl committed
1305
                chunk_region_idx = chunk_starts.index(idx)
oahzxl's avatar
oahzxl committed
1306
1307
1308
                act_memory += self._get_output_node_size(
                    chunk_outputs[chunk_region_idx]
                ) / (1024**2)
oahzxl's avatar
oahzxl committed
1309
1310
1311

            # determine chunk ratio for current node
            if chunk_within:
oahzxl's avatar
oahzxl committed
1312
                chunk_ratio = self._get_chunk_ratio(
oahzxl's avatar
oahzxl committed
1313
                    node,
oahzxl's avatar
oahzxl committed
1314
                    chunk_node_dim[chunk_region_idx],
1315
                    chunk_sizes[chunk_region_idx],
oahzxl's avatar
oahzxl committed
1316
1317
                )

oahzxl's avatar
oahzxl committed
1318
            # if node is placeholder, just add the size of the node
oahzxl's avatar
oahzxl committed
1319
1320
            if node.op == "placeholder":
                act_memory += self._get_meta_node_size(node) * chunk_ratio / (1024**2)
oahzxl's avatar
oahzxl committed
1321
1322
                act_memory_peak_log.append(act_memory)
            # skip output
oahzxl's avatar
oahzxl committed
1323
            elif node.op == "output":
oahzxl's avatar
oahzxl committed
1324
                continue
oahzxl's avatar
oahzxl committed
1325
1326
1327
1328
1329
            # no change for non compute node
            elif _is_non_compute_node_except_placeholder(node):
                act_memory_peak_log.append(act_memory)
            # node is a compute op
            # calculate tmp, output node and delete node memory
oahzxl's avatar
oahzxl committed
1330
            else:
oahzxl's avatar
oahzxl committed
1331
                # forward memory
oahzxl's avatar
oahzxl committed
1332
                # TODO: contiguous_memory still not accurate for matmul, view, reshape and transpose
oahzxl's avatar
oahzxl committed
1333
1334
1335
1336
1337
1338
1339
1340
                act_memory += (
                    self._get_contiguous_memory(node, not_contiguous_list)
                    * chunk_ratio
                    / (1024**2)
                )
                act_memory += (
                    self._get_output_node_size(node) * chunk_ratio / (1024**2)
                )
oahzxl's avatar
oahzxl committed
1341
1342
1343
                # record max act memory
                act_memory_peak_log.append(act_memory)
                # delete useless memory
oahzxl's avatar
oahzxl committed
1344
1345
1346
1347
1348
                act_memory -= (
                    self._get_contiguous_memory(node, not_contiguous_list, delete=True)
                    * chunk_ratio
                    / (1024**2)
                )
oahzxl's avatar
oahzxl committed
1349
                # delete unused vars not in chunk_input_list
oahzxl's avatar
oahzxl committed
1350
                # we can't delete input nodes until chunk ends
oahzxl's avatar
oahzxl committed
1351
                if chunk_within:
oahzxl's avatar
oahzxl committed
1352
                    act_memory -= self._get_chunk_delete_node_size(
oahzxl's avatar
oahzxl committed
1353
1354
1355
                        node,
                        user_to_last_uses_no_free_var,
                        chunk_ratio,
oahzxl's avatar
oahzxl committed
1356
                        chunk_inputs_names,
oahzxl's avatar
oahzxl committed
1357
                    ) / (1024**2)
oahzxl's avatar
oahzxl committed
1358
                else:
oahzxl's avatar
oahzxl committed
1359
                    act_memory -= self._get_delete_node_size(
oahzxl's avatar
oahzxl committed
1360
                        node, user_to_last_uses_no_free_var, chunk_inputs_names
oahzxl's avatar
oahzxl committed
1361
                    ) / (1024**2)
oahzxl's avatar
oahzxl committed
1362

oahzxl's avatar
oahzxl committed
1363
            # log active node, only effective without chunk
oahzxl's avatar
oahzxl committed
1364
1365
1366
1367
            self._add_active_node(node, active_node_list)
            self._remove_deactive_node(node, user_to_last_uses, active_node_list)

            # if node in chunk end nodes, restore chunk settings
oahzxl's avatar
oahzxl committed
1368
            if use_chunk and idx in chunk_ends:
oahzxl's avatar
oahzxl committed
1369
1370
1371
                act_memory -= (
                    self._get_output_node_size(node) * chunk_ratio / (1024**2)
                )
oahzxl's avatar
oahzxl committed
1372
                act_memory -= self._get_chunk_inputs_size(
oahzxl's avatar
oahzxl committed
1373
1374
                    chunk_inputs[chunk_region_idx],
                    chunk_inputs_non_chunk[chunk_region_idx],
oahzxl's avatar
oahzxl committed
1375
                    node_list,
oahzxl's avatar
oahzxl committed
1376
1377
                    chunk_regions[chunk_region_idx][1],
                ) / (1024**2)
oahzxl's avatar
oahzxl committed
1378
                chunk_within = False
oahzxl's avatar
oahzxl committed
1379
                chunk_ratio = 1
oahzxl's avatar
oahzxl committed
1380
                chunk_region_idx = None
oahzxl's avatar
oahzxl committed
1381

oahzxl's avatar
oahzxl committed
1382
            act_memory_after_node_log.append(act_memory)
oahzxl's avatar
oahzxl committed
1383
            active_node_list_log.append(copy.deepcopy(active_node_list))
oahzxl's avatar
oahzxl committed
1384

oahzxl's avatar
oahzxl committed
1385
1386
1387
1388
1389
        if print_mem:
            print("with chunk" if use_chunk else "without chunk")
            # self._print_mem_log(act_memory_peak_log, node_list, "peak")
            # self._print_mem_log(act_memory_after_node_log, node_list, "after")
            self._print_compute_op_mem_log(act_memory_peak_log, node_list, "peak")
oahzxl's avatar
oahzxl committed
1390
1391
1392
            self._print_compute_op_mem_log(
                act_memory_after_node_log, node_list, "after"
            )
oahzxl's avatar
oahzxl committed
1393

oahzxl's avatar
oahzxl committed
1394
1395
1396
1397
1398
        # param_memory = parameter_size(gm)
        # all_memory = act_memory + param_memory
        return act_memory_peak_log, act_memory_after_node_log, active_node_list_log


oahzxl's avatar
oahzxl committed
1399
class ChunkSelector(object):
oahzxl's avatar
oahzxl committed
1400
    def __init__(
oahzxl's avatar
oahzxl committed
1401
        self, index_tracer: IndexTracer, memory_estimator: MemoryEstimator, stratge, max_memory=None
oahzxl's avatar
oahzxl committed
1402
    ):
oahzxl's avatar
oahzxl committed
1403
        self.index_tracer = index_tracer
oahzxl's avatar
oahzxl committed
1404
        self.memory_estimator = memory_estimator
oahzxl's avatar
oahzxl committed
1405
        assert stratge in ["min_memory", "fit_memory"]
oahzxl's avatar
oahzxl committed
1406
        assert (stratge == "fit_memory" and max_memory is not None) or stratge != "fit_memory"
oahzxl's avatar
oahzxl committed
1407
        self.stratge = stratge
oahzxl's avatar
oahzxl committed
1408
        self.max_memory = max_memory  # MB
oahzxl's avatar
oahzxl committed
1409
1410
1411
1412
1413
1414
1415
1416
1417

    def _select_best_chunk_region(
        self, possible_chunk_regions, chunk_infos, peak_node, max_chunk_region, mem_peak
    ):
        if self.stratge == "min_memory":
            best_region = self._select_min_memory_chunk_region(
                possible_chunk_regions, chunk_infos
            )
        elif self.stratge == "fit_memory":
oahzxl's avatar
oahzxl committed
1418
            best_region = self._select_fit_memory_chunk_region(
oahzxl's avatar
oahzxl committed
1419
1420
1421
1422
1423
1424
                possible_chunk_regions,
                chunk_infos,
                peak_node,
                max_chunk_region,
                mem_peak,
            )
oahzxl's avatar
oahzxl committed
1425
1426
1427
        else:
            raise RuntimeError()
        return best_region
oahzxl's avatar
oahzxl committed
1428
1429
1430
1431

    def _select_fit_memory_chunk_region(
        self, possible_chunk_regions, chunk_infos, peak_node, max_chunk_region, mem_peak
    ):
oahzxl's avatar
oahzxl committed
1432
1433
1434
        # stop chunk if max memory satisfy memory limit
        if max(mem_peak) < self.max_memory:
            return None
oahzxl's avatar
oahzxl committed
1435

oahzxl's avatar
oahzxl committed
1436
1437
1438
1439
1440
1441
1442
1443
        # remove illegal regions
        illegal_regions = []
        for i in possible_chunk_regions:
            if not self._is_legal_region(i, chunk_infos):
                illegal_regions.append(i)
        for i in illegal_regions:
            if i in possible_chunk_regions:
                possible_chunk_regions.remove(i)
oahzxl's avatar
oahzxl committed
1444

oahzxl's avatar
oahzxl committed
1445
1446
1447
1448
1449
        # get mem for chunk region
        regions_dict = []
        for region in possible_chunk_regions:
            cur_chunk_infos = chunk_infos + [region]
            cur_mem_peak = self.memory_estimator.estimate_chunk_inference_mem(
oahzxl's avatar
oahzxl committed
1450
1451
1452
1453
1454
                self.index_tracer.node_list, cur_chunk_infos
            )[0]
            cur_chunk_region_peak = cur_mem_peak[
                max_chunk_region[0] : max_chunk_region[1] + 1
            ]
oahzxl's avatar
oahzxl committed
1455
1456
            cur_chunk_region_max_peak = max(cur_chunk_region_peak)
            if cur_chunk_region_max_peak < self.max_memory:
oahzxl's avatar
oahzxl committed
1457
1458
1459
1460
1461
1462
1463
1464
1465
                regions_dict.append(
                    {
                        "chunk_info": region,
                        "chunk_max_mem": cur_chunk_region_max_peak,
                        "chunk_len": self._get_compute_node_num(
                            region["region"][0], region["region"][1]
                        ),
                    }
                )
oahzxl's avatar
oahzxl committed
1466
1467
1468
        # no region found
        if len(regions_dict) == 0:
            return None
oahzxl's avatar
oahzxl committed
1469

oahzxl's avatar
oahzxl committed
1470
1471
1472
1473
        # select the min chunk len
        chunk_len = [i["chunk_len"] for i in regions_dict]
        best_region_idx = chunk_len.index(min(chunk_len))
        best_region = regions_dict[best_region_idx]["chunk_info"]
1474
1475
1476

        # get max chunk size
        best_region = self._get_fit_chunk_size(best_region, chunk_infos)
oahzxl's avatar
oahzxl committed
1477
        return best_region
oahzxl's avatar
oahzxl committed
1478

1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
    def _get_fit_chunk_size(self, chunk_info, chunk_infos):
        chunk_size = 1
        chunk_info["chunk_size"] = chunk_size
        cur_chunk_max_mem = 0
        # search a region
        while cur_chunk_max_mem < self.max_memory:
            chunk_size *= 2
            chunk_info["chunk_size"] = chunk_size
            cur_chunk_infos = chunk_infos + [chunk_info]
            cur_mem_peak = self.memory_estimator.estimate_chunk_inference_mem(
                self.index_tracer.node_list, cur_chunk_infos
            )[0]
            cur_chunk_max_mem = max(
                cur_mem_peak[chunk_info["region"][0] : chunk_info["region"][1] + 1]
            )
        # search exact size
        chunk_info["chunk_size"] = self._chunk_size_binary_search(
            chunk_size // 2, chunk_size, chunk_info, chunk_infos
        )
        return chunk_info

    def _chunk_size_binary_search(self, l, r, chunk_info, chunk_infos):
        if l >= 16:
            gap = 4
        else:
            gap = 1
        while r >= l + gap:
oahzxl's avatar
oahzxl committed
1506
            mid = int(l + (r - l) / 2)
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
            chunk_info["chunk_size"] = mid
            cur_chunk_infos = chunk_infos + [chunk_info]
            cur_mem_peak = self.memory_estimator.estimate_chunk_inference_mem(
                self.index_tracer.node_list, cur_chunk_infos
            )[0]
            cur_chunk_max_mem = max(
                cur_mem_peak[chunk_info["region"][0] : chunk_info["region"][1] + 1]
            )
            if cur_chunk_max_mem >= self.max_memory:
                r = mid - gap
            else:
                l = mid + gap
        return l

oahzxl's avatar
oahzxl committed
1521
1522
    def _get_compute_node_num(self, start, end):
        count = 0
oahzxl's avatar
oahzxl committed
1523
        for i in self.index_tracer.node_list[start : end + 1]:
oahzxl's avatar
oahzxl committed
1524
1525
1526
            if _is_non_compute_node(i):
                count += 1
        return count
oahzxl's avatar
oahzxl committed
1527

oahzxl's avatar
oahzxl committed
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
    def _select_min_memory_chunk_region(self, possible_chunk_regions, chunk_infos):
        max_region_range = 0
        best_region = None
        while len(possible_chunk_regions) > 0:
            for i in possible_chunk_regions:
                if i["region"][1] - i["region"][0] > max_region_range:
                    best_region = i
                    max_region_range = i["region"][1] - i["region"][0]
            if self._is_legal_region(best_region, chunk_infos):
                break
            possible_chunk_regions.remove(i)
            max_region_range = 0
            best_region = None
        return best_region

    def _is_legal_region(self, cur_chunk_info, chunk_infos):
        (chunk_region_start, chunk_region_end) = cur_chunk_info["region"]
        if cur_chunk_info in chunk_infos:
            return False
        if chunk_region_end < chunk_region_start:
            return False
        for i in chunk_infos:
            region = i["region"]
            if not (
                (chunk_region_start > region[1] and chunk_region_end > region[1])
                or (chunk_region_start < region[0] and chunk_region_end < region[0])
            ):
                return False
        return True


oahzxl's avatar
oahzxl committed
1559
class ChunkRegionSearch(object):
oahzxl's avatar
oahzxl committed
1560
    def __init__(self, gm, max_memory=None) -> None:
oahzxl's avatar
oahzxl committed
1561
        self.gm = gm
oahzxl's avatar
oahzxl committed
1562
        self.index_tracer = IndexTracer(list(gm.graph.nodes))
oahzxl's avatar
oahzxl committed
1563
        self.index_tracer.trace_index()
oahzxl's avatar
oahzxl committed
1564
        self.memory_estimator = MemoryEstimator(self.index_tracer)
oahzxl's avatar
oahzxl committed
1565
        self.chunk_selector = ChunkSelector(
oahzxl's avatar
oahzxl committed
1566
            self.index_tracer, self.memory_estimator, stratge="fit_memory", max_memory=max_memory
oahzxl's avatar
oahzxl committed
1567
        )
oahzxl's avatar
oahzxl committed
1568
1569
1570

    def _find_peak_node(self, mem_peak):
        max_value = max(mem_peak)
oahzxl's avatar
oahzxl committed
1571
        max_idx = mem_peak.index(max_value)
oahzxl's avatar
oahzxl committed
1572
        return max_idx
oahzxl's avatar
oahzxl committed
1573

oahzxl's avatar
oahzxl committed
1574
1575
    def _get_free_var(self):
        free_var_idx = []
oahzxl's avatar
oahzxl committed
1576
        for idx, n in enumerate(self.index_tracer.node_list):
oahzxl's avatar
oahzxl committed
1577
            if n.op == "placeholder":
oahzxl's avatar
oahzxl committed
1578
1579
                free_var_idx.append(idx)
        return free_var_idx
oahzxl's avatar
oahzxl committed
1580

oahzxl's avatar
oahzxl committed
1581
1582
1583
1584
1585
1586
1587
1588
    def _get_min_free_var(self, active_node_list, free_vars):
        min_len = 999
        for idx, n in enumerate(active_node_list):
            if idx in free_vars:
                continue
            if len(n) < min_len:
                min_len = len(n)
        return min_len
oahzxl's avatar
oahzxl committed
1589

1590
    def _search_max_chunk_region(self, active_node, peak_node, chunk_regions):
oahzxl's avatar
oahzxl committed
1591
        free_vars = self._get_free_var()
oahzxl's avatar
oahzxl committed
1592
1593
1594
1595
        free_var_num = len(free_vars)
        active_node_num = [len(i) for i in active_node]
        min_active_node_num = min(active_node_num[free_var_num:])
        threshold = max(free_var_num, min_active_node_num)
oahzxl's avatar
oahzxl committed
1596

oahzxl's avatar
oahzxl committed
1597
        # from peak_node to free_var
oahzxl's avatar
oahzxl committed
1598
1599
        inside_flag = False
        chunk_region_start = free_var_num
oahzxl's avatar
oahzxl committed
1600
        for i in range(peak_node, -1, -1):
oahzxl's avatar
oahzxl committed
1601
1602
1603
            if active_node_num[i] <= threshold:
                inside_flag = True
            if inside_flag and active_node_num[i] > threshold:
oahzxl's avatar
oahzxl committed
1604
1605
                chunk_region_start = i + 1
                break
oahzxl's avatar
oahzxl committed
1606

oahzxl's avatar
oahzxl committed
1607
        # from peak_node to len-2
oahzxl's avatar
oahzxl committed
1608
        inside_flag = False
oahzxl's avatar
oahzxl committed
1609
        chunk_region_end = len(active_node) - 1
oahzxl's avatar
oahzxl committed
1610
        for i in range(peak_node, len(active_node)):
oahzxl's avatar
oahzxl committed
1611
1612
1613
            if active_node_num[i] <= threshold:
                inside_flag = True
            if inside_flag and active_node_num[i] > threshold:
oahzxl's avatar
oahzxl committed
1614
                chunk_region_end = i
oahzxl's avatar
oahzxl committed
1615
                break
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630

        for i in chunk_regions:
            region = i["region"]
            if chunk_region_start >= region[0] and chunk_region_end <= region[1]:
                return None
            elif (
                region[0] <= chunk_region_start <= region[1]
                and chunk_region_end > region[1]
            ):
                chunk_region_start = region[1] + 1
            elif (
                region[0] <= chunk_region_end <= region[1]
                and chunk_region_start < region[0]
            ):
                chunk_region_end = region[0] - 1
oahzxl's avatar
oahzxl committed
1631
        return chunk_region_start, chunk_region_end
oahzxl's avatar
oahzxl committed
1632

oahzxl's avatar
oahzxl committed
1633
    def _is_not_compute(self, trace, chunk_range, dim_idx):
oahzxl's avatar
oahzxl committed
1634
        if trace["idx"][dim_idx] not in trace["compute"]:
oahzxl's avatar
oahzxl committed
1635
            return True
oahzxl's avatar
oahzxl committed
1636
1637
1638
1639
        if trace["idx"][dim_idx] in trace["compute"] and all(
            i < chunk_range[0] or i > chunk_range[1]
            for i in trace["compute"][trace["idx"][dim_idx]]
        ):
oahzxl's avatar
oahzxl committed
1640
1641
            return True
        return False
oahzxl's avatar
oahzxl committed
1642

oahzxl's avatar
oahzxl committed
1643
    def _find_free_dim(self, input_trace, output_trace, start_idx, end_idx):
oahzxl's avatar
oahzxl committed
1644
1645
        start_traces = input_trace[start_idx]
        end_trace = output_trace[end_idx]
oahzxl's avatar
oahzxl committed
1646
        end_node = self.index_tracer.node_list[end_idx]
oahzxl's avatar
oahzxl committed
1647
        chunk_infos = []
oahzxl's avatar
oahzxl committed
1648
        for end_dim, _ in enumerate(end_trace["idx"]):
oahzxl's avatar
oahzxl committed
1649
            if len(start_traces) > 1:
1650
                continue
oahzxl's avatar
oahzxl committed
1651
            for start_node, start_trace in start_traces.items():
oahzxl's avatar
oahzxl committed
1652
                for start_dim, _ in enumerate(start_trace["idx"]):
oahzxl's avatar
oahzxl committed
1653
                    # dim size cannot be 1
oahzxl's avatar
oahzxl committed
1654
1655
1656
1657
                    if (
                        _get_node_shape(end_node)[end_dim] == 1
                        or _get_node_shape(start_node)[start_dim] == 1
                    ):
oahzxl's avatar
oahzxl committed
1658
1659
1660
                        continue
                    # check index source align
                    if not self.index_tracer.check_index_source(
oahzxl's avatar
oahzxl committed
1661
1662
                        start_dim, start_node, start_idx, end_dim, end_node
                    ):
oahzxl's avatar
oahzxl committed
1663
1664
1665
                        continue
                    # check index copmute
                    if not self.index_tracer.check_index_compute(
oahzxl's avatar
oahzxl committed
1666
1667
                        start_idx, end_dim, end_node, end_idx
                    ):
oahzxl's avatar
oahzxl committed
1668
                        continue
oahzxl's avatar
oahzxl committed
1669
                    # flow search
oahzxl's avatar
oahzxl committed
1670
1671
                    chunk_info = self.index_tracer.flow_search(
                        start_idx, start_dim, end_idx, end_dim
oahzxl's avatar
oahzxl committed
1672
                    )
oahzxl's avatar
oahzxl committed
1673
                    if chunk_info is None:
oahzxl's avatar
oahzxl committed
1674
                        continue
1675
1676
1677
                    # check index copmute
                    if not self.index_tracer.check_index_duplicate(chunk_info):
                        continue
oahzxl's avatar
oahzxl committed
1678
1679
                    chunk_infos.append(chunk_info)
        return chunk_infos
oahzxl's avatar
oahzxl committed
1680

oahzxl's avatar
oahzxl committed
1681
1682
    def _search_possible_chunk_regions(self, max_chunk_region, peak_node):
        possible_chunk_region = []
oahzxl's avatar
oahzxl committed
1683
        output_trace = copy.deepcopy(self.index_tracer.idx_trace_list)
oahzxl's avatar
oahzxl committed
1684
        input_trace = []  # trace of a node's input nodes
oahzxl's avatar
oahzxl committed
1685
        for _, n in enumerate(self.index_tracer.node_list):
oahzxl's avatar
oahzxl committed
1686
1687
            cur_trace = {}
            for arg in n.args:
oahzxl's avatar
oahzxl committed
1688
1689
1690
                if type(arg) == type(n) and not _is_non_compute_node_except_placeholder(
                    arg
                ):
oahzxl's avatar
oahzxl committed
1691
1692
1693
1694
                    cur_trace[arg] = self.index_tracer._find_trace_from_node(arg)
            input_trace.append(cur_trace)

        for start_idx in range(max_chunk_region[0], peak_node + 1):
oahzxl's avatar
oahzxl committed
1695
            for end_idx in range(peak_node, max_chunk_region[1] + 1):
oahzxl's avatar
oahzxl committed
1696
                # skip non compute nodes
oahzxl's avatar
oahzxl committed
1697
                if _is_non_compute_node(
oahzxl's avatar
oahzxl committed
1698
1699
                    self.index_tracer.node_list[start_idx]
                ) or _is_non_compute_node(self.index_tracer.node_list[end_idx]):
oahzxl's avatar
oahzxl committed
1700
                    continue
oahzxl's avatar
oahzxl committed
1701

oahzxl's avatar
oahzxl committed
1702
                # select free dim
oahzxl's avatar
oahzxl committed
1703
1704
1705
                chunk_info = self._find_free_dim(
                    input_trace, output_trace, start_idx, end_idx
                )
oahzxl's avatar
oahzxl committed
1706
1707
                if len(chunk_info) > 0:
                    possible_chunk_region.extend(chunk_info)
oahzxl's avatar
oahzxl committed
1708
        return possible_chunk_region
oahzxl's avatar
oahzxl committed
1709

1710
    def _step_search(self, mem_peak, active_node, chunk_regions):
oahzxl's avatar
oahzxl committed
1711
        peak_node = self._find_peak_node(mem_peak)
1712
1713
1714
1715
1716
        max_chunk_region = self._search_max_chunk_region(
            active_node, peak_node, chunk_regions
        )
        if max_chunk_region == None:
            return None
oahzxl's avatar
oahzxl committed
1717
1718
1719
        possible_chunk_regions = self._search_possible_chunk_regions(
            max_chunk_region, peak_node
        )
oahzxl's avatar
oahzxl committed
1720
        best_chunk_region = self.chunk_selector._select_best_chunk_region(
oahzxl's avatar
oahzxl committed
1721
            possible_chunk_regions, chunk_regions, peak_node, max_chunk_region, mem_peak
oahzxl's avatar
oahzxl committed
1722
        )
oahzxl's avatar
oahzxl committed
1723
        best_chunk_region = self.index_tracer.reorder_all(best_chunk_region)
oahzxl's avatar
oahzxl committed
1724
        return best_chunk_region
oahzxl's avatar
oahzxl committed
1725

oahzxl's avatar
oahzxl committed
1726
1727
1728
1729
1730
    def _stop_search(self, init_mem_peak, mem_peak):
        sorted_init_mem_peak = sorted(init_mem_peak)
        if max(mem_peak) < sorted_init_mem_peak[int(len(sorted_init_mem_peak) * 0.5)]:
            return True
        return False
oahzxl's avatar
oahzxl committed
1731

oahzxl's avatar
oahzxl committed
1732
    def search_region(self):
oahzxl's avatar
oahzxl committed
1733
        chunk_infos = []
oahzxl's avatar
oahzxl committed
1734
1735
1736
1737
        (
            init_mem_peak,
            _,
            active_node,
oahzxl's avatar
oahzxl committed
1738
1739
1740
        ) = self.memory_estimator.estimate_chunk_inference_mem(
            self.index_tracer.node_list
        )
oahzxl's avatar
oahzxl committed
1741
        mem_peak = init_mem_peak
oahzxl's avatar
oahzxl committed
1742

oahzxl's avatar
oahzxl committed
1743
        while True:
oahzxl's avatar
oahzxl committed
1744
1745
            chunk_info = self._step_search(mem_peak, active_node, chunk_infos)
            if chunk_info is None:
oahzxl's avatar
oahzxl committed
1746
                break
oahzxl's avatar
oahzxl committed
1747
            chunk_infos.append(chunk_info)
oahzxl's avatar
oahzxl committed
1748

oahzxl's avatar
oahzxl committed
1749
1750
1751
1752
            (
                mem_peak,
                _,
                active_node,
oahzxl's avatar
oahzxl committed
1753
            ) = self.memory_estimator.estimate_chunk_inference_mem(
oahzxl's avatar
oahzxl committed
1754
                self.index_tracer.node_list, chunk_infos
oahzxl's avatar
oahzxl committed
1755
            )
oahzxl's avatar
oahzxl committed
1756
1757
            if self._stop_search(init_mem_peak, mem_peak):
                break
oahzxl's avatar
oahzxl committed
1758
1759
1760
        # self.memory_estimator.estimate_chunk_inference_mem(
        #     self.index_tracer.node_list, chunk_infos, print_mem=True
        # )
oahzxl's avatar
oahzxl committed
1761
        return chunk_infos
oahzxl's avatar
oahzxl committed
1762
1763


oahzxl's avatar
oahzxl committed
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
def _gen_chunk_slice_dim(chunk_dim, chunk_idx_name, shape):
    new_shape = "["
    for idx, i in enumerate(shape):
        if idx == chunk_dim:
            new_shape += "%s:%s + chunk_size" % (chunk_idx_name, chunk_idx_name)
        else:
            new_shape += ":"
        new_shape += ", "
    new_shape = new_shape[:-2] + "]"
    return new_shape


oahzxl's avatar
oahzxl committed
1776
1777
1778
1779
1780
1781
1782
1783
1784
def _gen_loop_start(chunk_input, chunk_output, chunk_ouput_dim, chunk_size=2):
    input_node = chunk_input[0]
    out_shape = _get_node_shape(chunk_output)
    out_str = str(list(out_shape))
    context = (
        "chunk_result = torch.empty(%s, dtype=%s.dtype, device=%s.device); chunk_size = %d\nfor chunk_idx in range"
        % (out_str, input_node.name, input_node.name, chunk_size)
    )
    context += "(0, %d, chunk_size):\n" % (out_shape[chunk_ouput_dim])
oahzxl's avatar
oahzxl committed
1785
1786
1787
    return context


oahzxl's avatar
oahzxl committed
1788
1789
1790
def _gen_loop_end(
    chunk_inputs, chunk_non_compute_inputs, chunk_outputs, chunk_outputs_dim, node_list
):
oahzxl's avatar
oahzxl committed
1791
1792
    chunk_outputs_name = chunk_outputs.name
    chunk_outputs_idx = _find_idx_by_name(chunk_outputs_name, node_list)
oahzxl's avatar
oahzxl committed
1793
    chunk_output_shape = chunk_outputs.meta["tensor_meta"].shape
oahzxl's avatar
oahzxl committed
1794
1795
1796
    chunk_slice = _gen_chunk_slice_dim(
        chunk_outputs_dim, "chunk_idx", chunk_output_shape
    )
oahzxl's avatar
oahzxl committed
1797
1798
1799
1800
1801
    context = "    chunk_result%s = %s;  %s = None\n" % (
        chunk_slice,
        chunk_outputs_name,
        chunk_outputs_name,
    )
oahzxl's avatar
oahzxl committed
1802
1803
1804
    context += (
        chunk_outputs_name + " = chunk_result;  chunk_result = None;  chunk_size = None"
    )
oahzxl's avatar
oahzxl committed
1805

oahzxl's avatar
oahzxl committed
1806
    # determine if its the last use for chunk input
oahzxl's avatar
oahzxl committed
1807
    for chunk_input in chunk_inputs + chunk_non_compute_inputs:
oahzxl's avatar
oahzxl committed
1808
1809
1810
1811
1812
1813
1814
        if all(
            [
                _find_idx_by_name(user.name, node_list) <= chunk_outputs_idx
                for user in chunk_input.users.keys()
            ]
        ):
            context += ";  %s = None" % chunk_input.name
oahzxl's avatar
oahzxl committed
1815
1816

    context += "\n"
oahzxl's avatar
oahzxl committed
1817
1818
    return context

oahzxl's avatar
init  
oahzxl committed
1819

oahzxl's avatar
oahzxl committed
1820
1821
1822
1823
1824
1825
1826
1827
1828
def _find_chunk_all_input_nodes(nodes: List[Node]):
    """
    Find non-compute input and output node names.
    input nodes are nodes used in the list
    output nodes are nodes will use nodes in the list
    """
    input_nodes = []
    for node in nodes:
        for input_node in node._input_nodes.keys():
oahzxl's avatar
oahzxl committed
1829
            if input_node not in nodes and input_node not in input_nodes:
oahzxl's avatar
oahzxl committed
1830
1831
1832
1833
1834
                input_nodes.append(input_node)
    return input_nodes


def _find_chunk_compute_input_and_output_nodes(nodes: List[Node]):
oahzxl's avatar
oahzxl committed
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
    """
    Find non-compute input and output node names.
    input nodes are nodes used in the list
    output nodes are nodes will use nodes in the list
    """
    input_nodes = []
    output_nodes = []

    # if a node has an input node which is not in the node list
    # we treat that input node as the input of the checkpoint function
    for node in nodes:
        for input_node in node._input_nodes.keys():
oahzxl's avatar
oahzxl committed
1847
1848
1849
1850
1851
            if (
                input_node not in nodes
                and input_node not in input_nodes
                and not _is_non_compute_node_except_placeholder(input_node)
            ):
oahzxl's avatar
oahzxl committed
1852
1853
1854
1855
1856
1857
                input_nodes.append(input_node)

    # if a node has a user node which is not in the node list
    # we treat that user node as the node receiving the current node output
    for node in nodes:
        for output_node in node.users.keys():
oahzxl's avatar
oahzxl committed
1858
1859
1860
            if (
                output_node not in nodes
                and node not in output_nodes
oahzxl's avatar
oahzxl committed
1861
                and not _is_non_compute_node_except_placeholder_output(output_node)
oahzxl's avatar
oahzxl committed
1862
            ):
oahzxl's avatar
oahzxl committed
1863
1864
1865
1866
1867
                output_nodes.append(node)

    return input_nodes, output_nodes


oahzxl's avatar
oahzxl committed
1868
1869
1870
1871
1872
def _find_idx_by_name(name, nodes_list):
    for idx, node in enumerate(nodes_list):
        if node.name == name:
            return idx
    raise RuntimeError("name %s not found in node list" % name)
oahzxl's avatar
init  
oahzxl committed
1873
1874


oahzxl's avatar
oahzxl committed
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
def _replace_name(context, name_from, name_to):
    patterns = [(" ", " "), (" ", "."), (" ", ","), ("(", ")"), ("(", ",")]
    for p in patterns:
        source = p[0] + name_from + p[1]
        target = p[0] + name_to + p[1]
        if source in context:
            context = context.replace(source, target)
    return context


oahzxl's avatar
oahzxl committed
1885
1886
1887
def _replace_reshape_size(context, node_name, reshape_size_dict):
    if node_name not in reshape_size_dict:
        return context
oahzxl's avatar
oahzxl committed
1888
    for size_name, size_value in reshape_size_dict[node_name].items():
oahzxl's avatar
oahzxl committed
1889
1890
1891
        context = context.replace(size_name, size_value)
    return context

oahzxl's avatar
oahzxl committed
1892

oahzxl's avatar
oahzxl committed
1893
1894
1895
1896
1897
1898
1899
1900
def emit_code_with_chunk(
    body,
    ckpt_func,
    nodes,
    emit_node_func,
    delete_unused_value_func,
    meta_nodes,
    meta_graph,
oahzxl's avatar
oahzxl committed
1901
    max_memory=None,
oahzxl's avatar
oahzxl committed
1902
):
oahzxl's avatar
init  
oahzxl committed
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
    """Emit code with nested activation checkpoint
    When we detect some of the node.activation_checkpoint is a List, we will use
    this function to emit the activation checkpoint codes.

    Args:
        body: forward code
        ckpt_func: checkpoint functions code
        nodes: graph.nodes
        emit_node_func: function to emit node
        delete_unused_value_func: function to remove the unused value
    """
oahzxl's avatar
oahzxl committed
1914
    node_list = list(nodes)
oahzxl's avatar
init  
oahzxl committed
1915

oahzxl's avatar
oahzxl committed
1916
    # find the chunk regions
oahzxl's avatar
oahzxl committed
1917
    chunk_region_search = ChunkRegionSearch(meta_graph, max_memory)
oahzxl's avatar
oahzxl committed
1918
    chunk_search = chunk_region_search.search_region()
oahzxl's avatar
init  
oahzxl committed
1919

oahzxl's avatar
oahzxl committed
1920
1921
1922
    chunk_regions = [i["region"] for i in chunk_search]
    chunk_starts = [i[0] for i in chunk_regions]
    chunk_ends = [i[1] for i in chunk_regions]
oahzxl's avatar
oahzxl committed
1923

oahzxl's avatar
oahzxl committed
1924
1925
1926
    chunk_inputs = [i["inputs"] for i in chunk_search]
    chunk_inputs_non_chunk = [i["inputs_non_chunk"] for i in chunk_search]
    chunk_inputs_dim = [i["inputs_dim"] for i in chunk_search]
oahzxl's avatar
oahzxl committed
1927
1928
    chunk_inputs_names = [j.name for i in chunk_inputs for j in i] + [
        j.name for i in chunk_inputs_non_chunk for j in i
oahzxl's avatar
oahzxl committed
1929
    ]
oahzxl's avatar
oahzxl committed
1930
1931
1932

    chunk_outputs = [i["outputs"][0] for i in chunk_search]
    chunk_outputs_dim = [i["outputs_dim"] for i in chunk_search]
oahzxl's avatar
oahzxl committed
1933

oahzxl's avatar
oahzxl committed
1934
    node_list = chunk_region_search.index_tracer.reorder_node_list(node_list)
oahzxl's avatar
init  
oahzxl committed
1935
    node_idx = 0
oahzxl's avatar
oahzxl committed
1936
    region_idx = 0
oahzxl's avatar
oahzxl committed
1937
1938
    within_chunk_region = False

oahzxl's avatar
oahzxl committed
1939
    while node_idx < len(node_list):
oahzxl's avatar
oahzxl committed
1940
        node = node_list[node_idx]
oahzxl's avatar
init  
oahzxl committed
1941

oahzxl's avatar
oahzxl committed
1942
1943
        if node_idx in chunk_starts:
            within_chunk_region = True
1944
            region_idx = chunk_starts.index(node_idx)
oahzxl's avatar
oahzxl committed
1945
1946
            body.append(
                _gen_loop_start(
oahzxl's avatar
oahzxl committed
1947
1948
1949
                    chunk_inputs[region_idx],
                    chunk_outputs[region_idx],
                    chunk_outputs_dim[region_idx],
oahzxl's avatar
oahzxl committed
1950
                    chunk_search[region_idx]["chunk_size"],
oahzxl's avatar
oahzxl committed
1951
1952
                )
            )
oahzxl's avatar
init  
oahzxl committed
1953

oahzxl's avatar
oahzxl committed
1954
        if within_chunk_region:
oahzxl's avatar
oahzxl committed
1955
1956
1957
1958
1959
1960
            emit_node_func(node, body)
            # replace input var with chunk var
            for input_node_idx, input_node in enumerate(chunk_inputs[region_idx]):
                for idx, dim in chunk_inputs_dim[region_idx][input_node_idx].items():
                    if idx == node_idx:
                        chunk_slice = _gen_chunk_slice_dim(
oahzxl's avatar
oahzxl committed
1961
                            dim[0], "chunk_idx", _get_node_shape(input_node)
oahzxl's avatar
oahzxl committed
1962
1963
1964
1965
                        )
                        body[-1] = _replace_name(
                            body[-1], input_node.name, input_node.name + chunk_slice
                        )
oahzxl's avatar
oahzxl committed
1966
1967
1968
            body[-1] = _replace_reshape_size(
                body[-1], node.name, chunk_search[region_idx]["reshape_size"]
            )
oahzxl's avatar
oahzxl committed
1969
1970
            body[-1] = "    " + body[-1]
            delete_unused_value_func(node, body, chunk_inputs_names)
oahzxl's avatar
oahzxl committed
1971
1972
1973
1974
        else:
            emit_node_func(node, body)
            if node_idx not in chunk_inputs:
                delete_unused_value_func(node, body, chunk_inputs_names)
oahzxl's avatar
init  
oahzxl committed
1975

oahzxl's avatar
oahzxl committed
1976
        if node_idx in chunk_ends:
oahzxl's avatar
oahzxl committed
1977
1978
            body.append(
                _gen_loop_end(
oahzxl's avatar
oahzxl committed
1979
1980
1981
                    chunk_inputs[region_idx],
                    chunk_inputs_non_chunk[region_idx],
                    chunk_outputs[region_idx],
oahzxl's avatar
oahzxl committed
1982
1983
                    chunk_outputs_dim[region_idx],
                    node_list,
oahzxl's avatar
oahzxl committed
1984
1985
                )
            )
oahzxl's avatar
oahzxl committed
1986
            within_chunk_region = False
oahzxl's avatar
init  
oahzxl committed
1987

oahzxl's avatar
oahzxl committed
1988
        node_idx += 1
oahzxl's avatar
init  
oahzxl committed
1989
1990
1991
1992


if CODEGEN_AVAILABLE:

oahzxl's avatar
oahzxl committed
1993
    class ChunkCodeGen(CodeGen):
oahzxl's avatar
oahzxl committed
1994
        def __init__(self, meta_graph, max_memory=None):
oahzxl's avatar
oahzxl committed
1995
            super().__init__()
oahzxl's avatar
oahzxl committed
1996
            self.meta_graph = meta_graph
oahzxl's avatar
oahzxl committed
1997
            self.max_memory = max_memory
oahzxl's avatar
oahzxl committed
1998
            self.meta_node = list(meta_graph.graph.nodes)
oahzxl's avatar
init  
oahzxl committed
1999

oahzxl's avatar
oahzxl committed
2000
2001
2002
        def _gen_python_code(
            self, nodes, root_module: str, namespace: _Namespace
        ) -> PythonCode:
oahzxl's avatar
init  
oahzxl committed
2003
2004
2005
2006
2007
2008
            free_vars: List[str] = []
            body: List[str] = []
            globals_: Dict[str, Any] = {}
            wrapped_fns: Dict[str, None] = {}

            # Wrap string in list to pass by reference
oahzxl's avatar
oahzxl committed
2009
            maybe_return_annotation: List[str] = [""]
oahzxl's avatar
init  
oahzxl committed
2010
2011
2012
2013
2014
2015
2016
2017
2018

            def add_global(name_hint: str, obj: Any):
                """Add an obj to be tracked as a global.

                We call this for names that reference objects external to the
                Graph, like functions or types.

                Returns: the global name that should be used to reference 'obj' in generated source.
                """
oahzxl's avatar
oahzxl committed
2019
2020
2021
                if (
                    _is_from_torch(obj) and obj != torch.device
                ):  # to support registering torch.device
oahzxl's avatar
init  
oahzxl committed
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
                    # HACK: workaround for how torch custom ops are registered. We
                    # can't import them like normal modules so they must retain their
                    # fully qualified name.
                    return _get_qualified_name(obj)

                # normalize the name hint to get a proper identifier
                global_name = namespace.create_name(name_hint, obj)

                if global_name in globals_:
                    assert globals_[global_name] is obj
                    return global_name
                globals_[global_name] = obj
                return global_name

            # set _custom_builtins here so that we needn't import colossalai in forward
oahzxl's avatar
oahzxl committed
2037
2038
2039
            _custom_builtins["colossalai"] = _CustomBuiltin(
                "import colossalai", colossalai
            )
oahzxl's avatar
init  
oahzxl committed
2040
2041
2042
2043
2044
2045
2046
2047

            # Pre-fill the globals table with registered builtins.
            for name, (_, obj) in _custom_builtins.items():
                add_global(name, obj)

            def type_repr(o: Any):
                if o == ():
                    # Empty tuple is used for empty tuple type annotation Tuple[()]
oahzxl's avatar
oahzxl committed
2048
                    return "()"
oahzxl's avatar
init  
oahzxl committed
2049
2050
2051

                typename = _type_repr(o)

oahzxl's avatar
oahzxl committed
2052
                if hasattr(o, "__origin__"):
oahzxl's avatar
init  
oahzxl committed
2053
2054
2055
2056
                    # This is a generic type, e.g. typing.List[torch.Tensor]
                    origin_type = _origin_type_map.get(o.__origin__, o.__origin__)
                    origin_typename = add_global(_type_repr(origin_type), origin_type)

oahzxl's avatar
oahzxl committed
2057
                    if hasattr(o, "__args__"):
oahzxl's avatar
init  
oahzxl committed
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
                        # Assign global names for each of the inner type variables.
                        args = [type_repr(arg) for arg in o.__args__]

                        if len(args) == 0:
                            # Bare type, such as `typing.Tuple` with no subscript
                            # This code-path used in Python < 3.9
                            return origin_typename

                        return f'{origin_typename}[{",".join(args)}]'
                    else:
                        # Bare type, such as `typing.Tuple` with no subscript
                        # This code-path used in Python 3.9+
                        return origin_typename

                # Common case: this is a regular module name like 'foo.bar.baz'
                return add_global(typename, o)

oahzxl's avatar
oahzxl committed
2075
2076
2077
            def _format_args(
                args: Tuple[Argument, ...], kwargs: Dict[str, Argument]
            ) -> str:
oahzxl's avatar
init  
oahzxl committed
2078
2079
                def _get_repr(arg):
                    # Handle NamedTuples (if it has `_fields`) via add_global.
oahzxl's avatar
oahzxl committed
2080
                    if isinstance(arg, tuple) and hasattr(arg, "_fields"):
oahzxl's avatar
init  
oahzxl committed
2081
2082
2083
2084
2085
                        qualified_name = _get_qualified_name(type(arg))
                        global_name = add_global(qualified_name, type(arg))
                        return f"{global_name}{repr(tuple(arg))}"
                    return repr(arg)

oahzxl's avatar
oahzxl committed
2086
2087
                args_s = ", ".join(_get_repr(a) for a in args)
                kwargs_s = ", ".join(f"{k} = {_get_repr(v)}" for k, v in kwargs.items())
oahzxl's avatar
init  
oahzxl committed
2088
                if args_s and kwargs_s:
oahzxl's avatar
oahzxl committed
2089
                    return f"{args_s}, {kwargs_s}"
oahzxl's avatar
init  
oahzxl committed
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
                return args_s or kwargs_s

            # Run through reverse nodes and record the first instance of a use
            # of a given node. This represents the *last* use of the node in the
            # execution order of the program, which we will use to free unused
            # values
            node_to_last_use: Dict[Node, Node] = {}
            user_to_last_uses: Dict[Node, List[Node]] = {}

            def register_last_uses(n: Node, user: Node):
                if n not in node_to_last_use:
                    node_to_last_use[n] = user
                    user_to_last_uses.setdefault(user, []).append(n)

            for node in reversed(nodes):
                map_arg(node.args, lambda n: register_last_uses(n, node))
                map_arg(node.kwargs, lambda n: register_last_uses(n, node))
oahzxl's avatar
oahzxl committed
2107

oahzxl's avatar
oahzxl committed
2108
            _delete_free_var_from_last_use(user_to_last_uses)
oahzxl's avatar
oahzxl committed
2109

oahzxl's avatar
init  
oahzxl committed
2110
            # NOTE: we add a variable to distinguish body and ckpt_func
oahzxl's avatar
oahzxl committed
2111
            def delete_unused_values(user: Node, body, to_keep=[]):
oahzxl's avatar
init  
oahzxl committed
2112
2113
2114
2115
2116
                """
                Delete values after their last use. This ensures that values that are
                not used in the remainder of the code are freed and the memory usage
                of the code is optimal.
                """
oahzxl's avatar
oahzxl committed
2117
                if user.op == "placeholder":
oahzxl's avatar
init  
oahzxl committed
2118
                    return
oahzxl's avatar
oahzxl committed
2119
2120
                if user.op == "output":
                    body.append("\n")
oahzxl's avatar
init  
oahzxl committed
2121
2122
                    return
                nodes_to_delete = user_to_last_uses.get(user, [])
oahzxl's avatar
oahzxl committed
2123
                nodes_to_delete = [i for i in nodes_to_delete if i.name not in to_keep]
oahzxl's avatar
init  
oahzxl committed
2124
                if len(nodes_to_delete):
oahzxl's avatar
oahzxl committed
2125
2126
2127
2128
                    to_delete_str = " = ".join(
                        [repr(n) for n in nodes_to_delete] + ["None"]
                    )
                    body.append(f";  {to_delete_str}\n")
oahzxl's avatar
init  
oahzxl committed
2129
                else:
oahzxl's avatar
oahzxl committed
2130
                    body.append("\n")
oahzxl's avatar
init  
oahzxl committed
2131
2132
2133

            # NOTE: we add a variable to distinguish body and ckpt_func
            def emit_node(node: Node, body):
oahzxl's avatar
oahzxl committed
2134
2135
2136
2137
                maybe_type_annotation = (
                    "" if node.type is None else f" : {type_repr(node.type)}"
                )
                if node.op == "placeholder":
oahzxl's avatar
init  
oahzxl committed
2138
                    assert isinstance(node.target, str)
oahzxl's avatar
oahzxl committed
2139
2140
2141
2142
2143
2144
2145
                    maybe_default_arg = (
                        "" if not node.args else f" = {repr(node.args[0])}"
                    )
                    free_vars.append(
                        f"{node.target}{maybe_type_annotation}{maybe_default_arg}"
                    )
                    raw_name = node.target.replace("*", "")
oahzxl's avatar
init  
oahzxl committed
2146
                    if raw_name != repr(node):
oahzxl's avatar
oahzxl committed
2147
                        body.append(f"{repr(node)} = {raw_name}\n")
oahzxl's avatar
init  
oahzxl committed
2148
                    return
oahzxl's avatar
oahzxl committed
2149
                elif node.op == "call_method":
oahzxl's avatar
init  
oahzxl committed
2150
2151
                    assert isinstance(node.target, str)
                    body.append(
oahzxl's avatar
oahzxl committed
2152
2153
2154
                        f"{repr(node)}{maybe_type_annotation} = {_format_target(repr(node.args[0]), node.target)}"
                        f"({_format_args(node.args[1:], node.kwargs)})"
                    )
oahzxl's avatar
init  
oahzxl committed
2155
                    return
oahzxl's avatar
oahzxl committed
2156
                elif node.op == "call_function":
oahzxl's avatar
init  
oahzxl committed
2157
2158
                    assert callable(node.target)
                    # pretty print operators
oahzxl's avatar
oahzxl committed
2159
2160
2161
2162
                    if (
                        node.target.__module__ == "_operator"
                        and node.target.__name__ in magic_methods
                    ):
oahzxl's avatar
init  
oahzxl committed
2163
                        assert isinstance(node.args, tuple)
oahzxl's avatar
oahzxl committed
2164
2165
2166
2167
                        body.append(
                            f"{repr(node)}{maybe_type_annotation} = "
                            f"{magic_methods[node.target.__name__].format(*(repr(a) for a in node.args))}"
                        )
oahzxl's avatar
init  
oahzxl committed
2168
2169
2170
2171
                        return

                    # pretty print inplace operators; required for jit.script to work properly
                    # not currently supported in normal FX graphs, but generated by torchdynamo
oahzxl's avatar
oahzxl committed
2172
2173
2174
2175
2176
2177
2178
2179
                    if (
                        node.target.__module__ == "_operator"
                        and node.target.__name__ in inplace_methods
                    ):
                        body.append(
                            f"{inplace_methods[node.target.__name__].format(*(repr(a) for a in node.args))};  "
                            f"{repr(node)}{maybe_type_annotation} = {repr(node.args[0])}"
                        )
oahzxl's avatar
init  
oahzxl committed
2180
2181
2182
2183
2184
2185
                        return

                    qualified_name = _get_qualified_name(node.target)
                    global_name = add_global(qualified_name, node.target)
                    # special case for getattr: node.args could be 2-argument or 3-argument
                    # 2-argument: attribute access; 3-argument: fall through to attrib function call with default value
oahzxl's avatar
oahzxl committed
2186
2187
2188
2189
2190
2191
2192
                    if (
                        global_name == "getattr"
                        and isinstance(node.args, tuple)
                        and isinstance(node.args[1], str)
                        and node.args[1].isidentifier()
                        and len(node.args) == 2
                    ):
oahzxl's avatar
init  
oahzxl committed
2193
                        body.append(
oahzxl's avatar
oahzxl committed
2194
2195
                            f"{repr(node)}{maybe_type_annotation} = {_format_target(repr(node.args[0]), node.args[1])}"
                        )
oahzxl's avatar
init  
oahzxl committed
2196
2197
                        return
                    body.append(
oahzxl's avatar
oahzxl committed
2198
2199
2200
                        f"{repr(node)}{maybe_type_annotation} = {global_name}({_format_args(node.args, node.kwargs)})"
                    )
                    if node.meta.get("is_wrapped", False):
oahzxl's avatar
init  
oahzxl committed
2201
2202
                        wrapped_fns.setdefault(global_name)
                    return
oahzxl's avatar
oahzxl committed
2203
                elif node.op == "call_module":
oahzxl's avatar
init  
oahzxl committed
2204
                    assert isinstance(node.target, str)
oahzxl's avatar
oahzxl committed
2205
2206
2207
2208
                    body.append(
                        f"{repr(node)}{maybe_type_annotation} = "
                        f"{_format_target(root_module, node.target)}({_format_args(node.args, node.kwargs)})"
                    )
oahzxl's avatar
init  
oahzxl committed
2209
                    return
oahzxl's avatar
oahzxl committed
2210
                elif node.op == "get_attr":
oahzxl's avatar
init  
oahzxl committed
2211
                    assert isinstance(node.target, str)
oahzxl's avatar
oahzxl committed
2212
2213
2214
                    body.append(
                        f"{repr(node)}{maybe_type_annotation} = {_format_target(root_module, node.target)}"
                    )
oahzxl's avatar
init  
oahzxl committed
2215
                    return
oahzxl's avatar
oahzxl committed
2216
                elif node.op == "output":
oahzxl's avatar
init  
oahzxl committed
2217
2218
2219
2220
                    if node.type is not None:
                        maybe_return_annotation[0] = f" -> {type_repr(node.type)}"
                    body.append(self.generate_output(node.args[0]))
                    return
oahzxl's avatar
oahzxl committed
2221
                raise NotImplementedError(f"node: {node.op} {node.target}")
oahzxl's avatar
init  
oahzxl committed
2222
2223
2224
2225
2226
2227

            # Modified for activation checkpointing
            ckpt_func = []

            # if any node has a list of labels for activation_checkpoint, we
            # will use nested type of activation checkpoint codegen
oahzxl's avatar
oahzxl committed
2228
2229
2230
2231
2232
2233
2234
2235
            emit_code_with_chunk(
                body,
                ckpt_func,
                nodes,
                emit_node,
                delete_unused_values,
                self.meta_node,
                self.meta_graph,
oahzxl's avatar
oahzxl committed
2236
                self.max_memory
oahzxl's avatar
oahzxl committed
2237
            )
oahzxl's avatar
init  
oahzxl committed
2238
2239
2240
2241
2242

            if len(body) == 0:
                # If the Graph has no non-placeholder nodes, no lines for the body
                # have been emitted. To continue to have valid Python code, emit a
                # single pass statement
oahzxl's avatar
oahzxl committed
2243
                body.append("pass\n")
oahzxl's avatar
init  
oahzxl committed
2244
2245

            if len(wrapped_fns) > 0:
oahzxl's avatar
oahzxl committed
2246
2247
2248
2249
                wrap_name = add_global("wrap", torch.fx.wrap)
                wrap_stmts = "\n".join(
                    [f'{wrap_name}("{name}")' for name in wrapped_fns]
                )
oahzxl's avatar
init  
oahzxl committed
2250
            else:
oahzxl's avatar
oahzxl committed
2251
                wrap_stmts = ""
oahzxl's avatar
init  
oahzxl committed
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261

            if self._body_transformer:
                body = self._body_transformer(body)

            for name, value in self.additional_globals():
                add_global(name, value)

            # as we need colossalai.utils.checkpoint, we need to import colossalai
            # in forward function
            prologue = self.gen_fn_def(free_vars, maybe_return_annotation[0])
oahzxl's avatar
oahzxl committed
2262
            prologue = "".join(ckpt_func) + prologue
oahzxl's avatar
init  
oahzxl committed
2263
2264
            prologue = prologue

oahzxl's avatar
oahzxl committed
2265
2266
            code = "".join(body)
            code = "\n".join("    " + line for line in code.split("\n"))
oahzxl's avatar
init  
oahzxl committed
2267
2268
2269
2270
            fn_code = f"""
{wrap_stmts}

{prologue}
oahzxl's avatar
oahzxl committed
2271
{code}"""
oahzxl's avatar
oahzxl committed
2272
            # print(fn_code)
oahzxl's avatar
init  
oahzxl committed
2273
            return PythonCode(fn_code, globals_)