chunk_codegen.py 68.5 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
class FlowTracer(object):
    def __init__(self, gm) -> None:
        self.gm = gm
oahzxl's avatar
oahzxl committed
62
        self.node_list = list(gm.graph.nodes)
oahzxl's avatar
oahzxl committed
63
64
65
66
        self.flow_trace = {}

    def _add_trace(self, name):
        self.flow_trace[name] = []
oahzxl's avatar
oahzxl committed
67

oahzxl's avatar
oahzxl committed
68
    def _add_node(self, trace_name, node):
oahzxl's avatar
oahzxl committed
69
70
71
72
        self.flow_trace[trace_name].append(
            {"node": node, "inside_depend": [], "outside_depend": []}
        )

oahzxl's avatar
oahzxl committed
73
74
    def _add_inside_depend(self, flow_name, node, inside_depend_node):
        for i in self.flow_trace[flow_name]:
oahzxl's avatar
oahzxl committed
75
76
            if i["node"] == node:
                i["inside_depend"].append(inside_depend_node)
oahzxl's avatar
oahzxl committed
77
78
                return
        raise RuntimeError("node not found")
oahzxl's avatar
oahzxl committed
79
80
81
82

    def _add_outside_depend(
        self, flow_name, node, outside_depend_node, outside_depend_trace
    ):
oahzxl's avatar
oahzxl committed
83
        for i in self.flow_trace[flow_name]:
oahzxl's avatar
oahzxl committed
84
85
            if i["node"] == node:
                i["outside_depend"].append({outside_depend_trace: outside_depend_node})
oahzxl's avatar
oahzxl committed
86
87
88
89
                return
        raise RuntimeError("node not found")

    def _init_trace(self):
oahzxl's avatar
oahzxl committed
90
        for i in self.node_list:
oahzxl's avatar
oahzxl committed
91
            if i.op == "placeholder":
oahzxl's avatar
oahzxl committed
92
93
94
95
                self._add_trace(i.name)
                self._add_node(i.name, i)

    def _find_flow_for_node(self, node):
oahzxl's avatar
oahzxl committed
96
        if type(self.node_list[0]) != type(node):
oahzxl's avatar
oahzxl committed
97
            return None
oahzxl's avatar
oahzxl committed
98
        if _is_non_compute_node_except_placeholder(node):
oahzxl's avatar
oahzxl committed
99
100
101
            return None
        for name, trace in self.flow_trace.items():
            for i in trace:
oahzxl's avatar
oahzxl committed
102
                if node == i["node"]:
oahzxl's avatar
oahzxl committed
103
104
105
106
107
108
                    return name
        if any(i in node.name for i in ["ones_like"]):
            self._add_trace(node.name)
            self._add_node(node.name, node)
            return node.name
        raise RuntimeError("node not found")
oahzxl's avatar
oahzxl committed
109

oahzxl's avatar
oahzxl committed
110
111
112
113
114
    def _find_first_valid_flow(self, flow):
        for i in flow:
            if i is not None:
                return i
        raise RuntimeError("invalid flow")
oahzxl's avatar
oahzxl committed
115

oahzxl's avatar
oahzxl committed
116
117
118
    def find_node_flow(self, node):
        for name, trace in self.flow_trace.items():
            for i in trace:
oahzxl's avatar
oahzxl committed
119
                if node == i["node"]:
oahzxl's avatar
oahzxl committed
120
121
                    return name, i
        raise RuntimeError("invalid node")
oahzxl's avatar
oahzxl committed
122

oahzxl's avatar
oahzxl committed
123
    def _get_flow_mix_node(self, node):
oahzxl's avatar
oahzxl committed
124
        if _is_non_compute_node(node):
oahzxl's avatar
oahzxl committed
125
126
            return None
        _, node_trace = self.find_node_flow(node)
oahzxl's avatar
oahzxl committed
127
        if len(node_trace["outside_depend"]) == 0:
oahzxl's avatar
oahzxl committed
128
            return None
oahzxl's avatar
oahzxl committed
129
        elif len(node_trace["outside_depend"]) > 1:
oahzxl's avatar
oahzxl committed
130
            raise NotImplementedError
oahzxl's avatar
oahzxl committed
131
        vars = list(node_trace["outside_depend"][0].values())[0]
oahzxl's avatar
oahzxl committed
132
        return vars
oahzxl's avatar
oahzxl committed
133

oahzxl's avatar
oahzxl committed
134
    def _get_same_flow_node(self, node_list, node):
oahzxl's avatar
oahzxl committed
135
136
137
        name, _ = self.find_node_flow(node)
        result = []
        for i in self.flow_trace[name]:
oahzxl's avatar
oahzxl committed
138
139
            if i["node"] in node_list:
                result.append(i["node"])
oahzxl's avatar
oahzxl committed
140
        return result
oahzxl's avatar
oahzxl committed
141
142

    def trace_flow(self):
oahzxl's avatar
oahzxl committed
143
144
145
        # init trace
        self._init_trace()

oahzxl's avatar
oahzxl committed
146
        for node in self.node_list:
oahzxl's avatar
oahzxl committed
147
            # skip if non compute node
oahzxl's avatar
oahzxl committed
148
            if all(
oahzxl's avatar
oahzxl committed
149
                type(arg) != type(node) or _is_non_compute_node_except_placeholder(arg)
oahzxl's avatar
oahzxl committed
150
                for arg in node.args
oahzxl's avatar
oahzxl committed
151
            ) or _is_non_compute_node(node):
oahzxl's avatar
oahzxl committed
152
153
154
155
156
157
158
159
160
161
162
163
                continue

            node_input_flows = [self._find_flow_for_node(arg) for arg in node.args]

            node_domin_flow = self._find_first_valid_flow(node_input_flows)
            self._add_node(node_domin_flow, node)
            for node_input_flow, arg in zip(node_input_flows, node.args):
                if node_input_flow is None:
                    continue
                elif node_input_flow == node_domin_flow:
                    self._add_inside_depend(node_domin_flow, node, arg)
                else:
oahzxl's avatar
oahzxl committed
164
165
166
                    self._add_outside_depend(
                        node_domin_flow, node, arg, node_input_flow
                    )
oahzxl's avatar
oahzxl committed
167
        return self.flow_trace
oahzxl's avatar
oahzxl committed
168

oahzxl's avatar
oahzxl committed
169
170
    def _detect_flow(self, start_idx, start_dim, end_idx, end_dim, index_tracer):
        inputs, outputs = _find_chunk_compute_input_and_output_nodes(
oahzxl's avatar
oahzxl committed
171
172
173
174
175
            self.node_list[start_idx : end_idx + 1]
        )
        chunk_info = {
            "region": (start_idx, end_idx),
            "inputs": inputs,
oahzxl's avatar
oahzxl committed
176
            "inputs_non_chunk": [],
oahzxl's avatar
oahzxl committed
177
178
179
180
181
            "inputs_dim": start_dim,
            "outputs": outputs,
            "outputs_dim": end_dim,
            "args": {},
        }
oahzxl's avatar
oahzxl committed
182
183
184
185
186
187
        flow_block = False
        
        # TODO don't allow multi outputs now
        if len(outputs) > 1:
            flow_block = True
            return flow_block, chunk_info
oahzxl's avatar
oahzxl committed
188

oahzxl's avatar
oahzxl committed
189
190
        for idx in range(start_idx, end_idx + 1):
            node = self.node_list[idx]
oahzxl's avatar
oahzxl committed
191
192
            mix_flow_node = self._get_flow_mix_node(node)
            if mix_flow_node is None:
oahzxl's avatar
oahzxl committed
193
                continue
oahzxl's avatar
oahzxl committed
194

oahzxl's avatar
oahzxl committed
195
            # if there is a flow mix, op must be in [mul, add, matmul]
oahzxl's avatar
oahzxl committed
196
            # element-wise op requires dim to be equal in every dim
oahzxl's avatar
oahzxl committed
197
            if any(n in node.name for n in ["mul", "add"]):
oahzxl's avatar
oahzxl committed
198
                for i in node.args:
oahzxl's avatar
oahzxl committed
199
                    if type(i) == type(mix_flow_node) and i != mix_flow_node:
oahzxl's avatar
oahzxl committed
200
                        main_flow_var = i
oahzxl's avatar
oahzxl committed
201
                # if mix flow is a broadcast in chunk dim,
oahzxl's avatar
oahzxl committed
202
                # TODO: need to move that flow out of the chunk
oahzxl's avatar
oahzxl committed
203
204
205
206
                mix_flow_node_dim = index_tracer._get_node_chunk_dim(
                    self.node_list[end_idx], end_dim, node
                )
                if mix_flow_node_dim is None:
oahzxl's avatar
oahzxl committed
207
                    flow_block = True
oahzxl's avatar
oahzxl committed
208
209
                    break
                if _get_node_shape(mix_flow_node)[mix_flow_node_dim] == 1:
oahzxl's avatar
oahzxl committed
210
                    flow_block = False
oahzxl's avatar
oahzxl committed
211
212
                    for i in self._get_same_flow_node(
                        chunk_info["inputs"], mix_flow_node
oahzxl's avatar
oahzxl committed
213
214
                    ):
                        chunk_info["inputs"].remove(i)
oahzxl's avatar
oahzxl committed
215
216
217
                # else, we need to chunk mix var as well
                else:
                    # TODO chunk another value
oahzxl's avatar
oahzxl committed
218
                    flow_block = True
oahzxl's avatar
oahzxl committed
219
220
221
                    break
            else:
                raise NotImplementedError("%s not implemented" % node.name)
oahzxl's avatar
oahzxl committed
222

oahzxl's avatar
oahzxl committed
223
224
225
226
        if flow_block:
            flow_block = True
            return flow_block, chunk_info
        
oahzxl's avatar
oahzxl committed
227
228
        inputs_dim = []
        remove_inputs = []
oahzxl's avatar
oahzxl committed
229
        for input_node in chunk_info["inputs"]:
oahzxl's avatar
oahzxl committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
            input_dict = {}
            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)
                dim = None
                if start_dim <= user_idx < end_idx:
                    dim = index_tracer._get_node_chunk_dim(
                        self.node_list[end_idx], end_dim, input_node
                    )
                elif user_idx == end_idx:
                    dim = end_dim
                # n has relation with chunk dim
                if dim is not None and _get_node_shape(user)[dim] != 1:
                    input_dict[user_idx] = dim
            if len(input_dict) == 0:
                remove_inputs.append(input_node)
            else:
                inputs_dim.append(input_dict)
oahzxl's avatar
oahzxl committed
249
        chunk_info["inputs_dim"] = inputs_dim
oahzxl's avatar
oahzxl committed
250
        for i in remove_inputs:
oahzxl's avatar
oahzxl committed
251
252
253
            if i in chunk_info["inputs"]:
                chunk_info["inputs"].remove(i)

oahzxl's avatar
oahzxl committed
254
        # we need to log input nodes to avoid deleteing them in the loop
oahzxl's avatar
oahzxl committed
255
256
257
        non_chunk_inputs = _find_chunk_all_input_nodes(
            self.node_list[start_idx : end_idx + 1]
        )
oahzxl's avatar
oahzxl committed
258
        for i in non_chunk_inputs:
oahzxl's avatar
oahzxl committed
259
            if i not in chunk_info["inputs"]:
oahzxl's avatar
oahzxl committed
260
261
                chunk_info["inputs_non_chunk"].append(i)

oahzxl's avatar
oahzxl committed
262
        return flow_block, chunk_info
oahzxl's avatar
oahzxl committed
263
264


oahzxl's avatar
oahzxl committed
265
class IndexTracer(object):
oahzxl's avatar
oahzxl committed
266
267
268
    def __init__(self, gm) -> None:
        self.gm = gm
        self.nodes_list = list(gm.graph.nodes)
269
        self.idx_trace_list = self._init_idx_trace_list()
oahzxl's avatar
oahzxl committed
270
        self.idx_trace_equal = []
oahzxl's avatar
oahzxl committed
271
        self.idx_view_list = []
oahzxl's avatar
oahzxl committed
272
        self.idx_count = -1
oahzxl's avatar
oahzxl committed
273

274
275
276
    def _init_idx_trace_list(self):
        idx_trace_list = []
        for n in self.nodes_list:
oahzxl's avatar
oahzxl committed
277
            if _get_node_shape(n) != None:
278
                cur_trace = {
oahzxl's avatar
oahzxl committed
279
280
281
                    "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)))],
282
283
                }
            else:
oahzxl's avatar
oahzxl committed
284
                cur_trace = {"idx": [], "compute": [], "source": []}
285
286
            idx_trace_list.append(cur_trace)
        return idx_trace_list
oahzxl's avatar
oahzxl committed
287

oahzxl's avatar
oahzxl committed
288
    def _add_index(self):
oahzxl's avatar
oahzxl committed
289
290
        """
        Update the count and return it. To record the idx number.
oahzxl's avatar
oahzxl committed
291

oahzxl's avatar
oahzxl committed
292
293
        Returns:
            idx_count: int
oahzxl's avatar
oahzxl committed
294
        """
oahzxl's avatar
oahzxl committed
295
        self.idx_count += 1
oahzxl's avatar
oahzxl committed
296
        return self.idx_count
oahzxl's avatar
oahzxl committed
297

298
    def _del_dim(self, idx, dim_idx):
oahzxl's avatar
oahzxl committed
299
300
301
302
        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)

303
    def _add_dim(self, idx, dim_idx):
oahzxl's avatar
oahzxl committed
304
305
306
307
        self.idx_trace_list[idx]["idx"].insert(dim_idx, self._add_index())
        self.idx_trace_list[idx]["compute"].insert(dim_idx, [])
        self.idx_trace_list[idx]["source"].insert(dim_idx, {})

308
309
310
311
    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
312

313
314
315
316
317
    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
318
319
320
321
        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
322
        self._add_source(node_from, node_from_dim, node_to, node_to_dim, init=True)
oahzxl's avatar
oahzxl committed
323

324
325
326
327
328
329
330
    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
331

oahzxl's avatar
oahzxl committed
332
    def _add_source(self, node_from, node_from_dim, node_to, node_to_dim, init=False):
333
334
335
336
337
        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)
        node_from_idx = _find_idx_by_name(node_from.name, self.nodes_list)
oahzxl's avatar
oahzxl committed
338
        if init:
oahzxl's avatar
oahzxl committed
339
340
341
342
343
344
            node_to_trace["source"][node_to_dim] = {}
        node_to_trace["source"][node_to_dim][node_from_idx] = node_from_dim
        node_to_trace["source"][node_to_dim].update(
            node_from_trace["source"][node_from_dim]
        )

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    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
360

361
    def _mark_idx_equal(self, node1, dim1, node2, dim2):
oahzxl's avatar
oahzxl committed
362
363
364
365
366
367
        """
        Mark 2 index to be equal.

        Args:
            idx1 (int): index count.
            idx2 (int): index count.
368
369
370
371
372
373
374
        """
        # 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
375

oahzxl's avatar
oahzxl committed
376
    def _mark_computation(self, node, idx, dim):
oahzxl's avatar
oahzxl committed
377
378
379
380
381
382
383
        """
        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
384
        """
oahzxl's avatar
oahzxl committed
385
386
        if isinstance(dim, int):
            dim = [dim]
387
        dims = list(range(len(_get_node_shape(node))))
oahzxl's avatar
oahzxl committed
388
        for d in dim:
389
            cur_dim = dims[d]
oahzxl's avatar
oahzxl committed
390
391
            if idx not in self.idx_trace_list[idx]["compute"][cur_dim]:
                self.idx_trace_list[idx]["compute"][cur_dim].append(idx)
392

oahzxl's avatar
oahzxl committed
393
    def _find_trace_from_node(self, node):
oahzxl's avatar
oahzxl committed
394
395
396
397
398
399
400
401
        """
        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
402
        """
oahzxl's avatar
oahzxl committed
403
404
        node_idx = _find_idx_by_name(node.name, self.nodes_list)
        node_dict = self.idx_trace_list[node_idx]
405
        return node_dict
oahzxl's avatar
oahzxl committed
406

oahzxl's avatar
oahzxl committed
407
408
409
410
411
412
413
414
415
416
417
418
419
420
    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.
        """
        node_idx = _find_idx_by_name(node.name, self.nodes_list)
        node_dict = self.idx_trace_list[node_idx]
        return node_dict["source"]

oahzxl's avatar
oahzxl committed
421
    def _find_idx_trace_from_node(self, node):
oahzxl's avatar
oahzxl committed
422
423
424
425
426
427
428
        """
        Find node idx trace by the node.

        Args:
            node (node)
        Returns:
            idx (list): idx of the node
oahzxl's avatar
oahzxl committed
429
        """
oahzxl's avatar
oahzxl committed
430
        node_idx = _find_idx_by_name(node.name, self.nodes_list)
oahzxl's avatar
oahzxl committed
431
432
        return self.idx_trace_list[node_idx]["idx"]

oahzxl's avatar
oahzxl committed
433
    def _find_compute_trace_from_node(self, node):
oahzxl's avatar
oahzxl committed
434
435
436
437
438
439
440
        """
        Find node compute trace by the node.

        Args:
            node (node)
        Returns:
            compute (list): computed idx of the node.
oahzxl's avatar
oahzxl committed
441
        """
oahzxl's avatar
oahzxl committed
442
        node_idx = _find_idx_by_name(node.name, self.nodes_list)
oahzxl's avatar
oahzxl committed
443
444
        return self.idx_trace_list[node_idx]["compute"]

445
    def _assign_index_as_input(self, node, node_idx, input_node=None):
oahzxl's avatar
oahzxl committed
446
447
448
449
450
451
        """
        Assign node's trace as its input node.

        Args:
            node (node)
            node_idx (int)
452
453
454
455
        """
        if input_node == None:
            input_node = node.args[0]
        input_node_idx = _find_idx_by_name(input_node.name, self.nodes_list)
oahzxl's avatar
oahzxl committed
456
457
        input_node_idx_trace = self.idx_trace_list[input_node_idx]["idx"]

oahzxl's avatar
oahzxl committed
458
        new_idx_trace = copy.deepcopy(input_node_idx_trace)
oahzxl's avatar
oahzxl committed
459
460
        self.idx_trace_list[node_idx]["idx"] = new_idx_trace

461
        self._inherit_all_computation(input_node, node)
oahzxl's avatar
oahzxl committed
462

oahzxl's avatar
oahzxl committed
463
    def _assign_all_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
464
465
466
467
468
469
        """
        Add new index for all node's dims.

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
470
471
        """
        shape = node.meta["tensor_meta"].shape
oahzxl's avatar
oahzxl committed
472
473
        new_trace = []
        for _ in shape:
oahzxl's avatar
oahzxl committed
474
            new_trace.append(self._add_index())
oahzxl's avatar
oahzxl committed
475
        self.idx_trace_list[node_idx]["idx"] = new_trace
oahzxl's avatar
oahzxl committed
476

oahzxl's avatar
oahzxl committed
477
    def _assign_transpose_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
478
479
480
481
482
483
484
485
        """
        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
486
        """
487
        input_node = node.args[0]
oahzxl's avatar
oahzxl committed
488
        tranpose_dim = node.args[1:]
oahzxl's avatar
oahzxl committed
489

490
491
492
        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
493

oahzxl's avatar
oahzxl committed
494
    def _assign_permute_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
495
496
497
498
499
500
501
502
        """
        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
503
        """
oahzxl's avatar
oahzxl committed
504
        permute_dim = node.args[1:]
505
        input_node = node.args[0]
oahzxl's avatar
oahzxl committed
506

507
        self._assign_index_as_input(node, node_idx, input_node)
oahzxl's avatar
oahzxl committed
508
        for idx, d in enumerate(permute_dim):
509
            self._inherit_index(input_node, d, node, idx)
oahzxl's avatar
oahzxl committed
510

oahzxl's avatar
oahzxl committed
511
    def _assign_linear_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
512
513
514
515
516
517
518
519
520
        """
        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
521
522
523
524
525
526
        """
        if len(node.args) == 2:
            input_node, weight = node.args
            bias = None
        else:
            input_node, weight, bias = node.args
oahzxl's avatar
oahzxl committed
527

528
529
        self._assign_index_as_input(node, node_idx)
        self._inherit_index(weight, 1, node, -1)
oahzxl's avatar
oahzxl committed
530

oahzxl's avatar
oahzxl committed
531
        self._mark_computation(node, node_idx, [-1])
532
        self._mark_idx_equal(input_node, -1, weight, 0)
oahzxl's avatar
oahzxl committed
533

oahzxl's avatar
oahzxl committed
534
        if bias:
535
            self._mark_idx_equal(input_node, -1, bias, 0)
oahzxl's avatar
oahzxl committed
536

oahzxl's avatar
oahzxl committed
537
    def _assign_matmul_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
538
539
540
541
542
543
544
545
546
        """
        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
547
        """
oahzxl's avatar
oahzxl committed
548
        matmul_left, matmul_right = node.args
oahzxl's avatar
oahzxl committed
549
550

        assert len(_get_node_shape(matmul_left)) == len(_get_node_shape(matmul_right))
551
552
        self._assign_index_as_input(node, node_idx, matmul_left)
        self._inherit_index(matmul_right, -1, node, -1)
oahzxl's avatar
oahzxl committed
553

554
        self._mark_computation_from_node(matmul_right, node, [-1, -2])
oahzxl's avatar
oahzxl committed
555
        self._mark_computation(node, node_idx, [-1])
556
        self._mark_idx_equal(matmul_left, -1, matmul_right, -2)
oahzxl's avatar
oahzxl committed
557

oahzxl's avatar
oahzxl committed
558
    def _assign_layernorm_index(self, node, idx):
oahzxl's avatar
oahzxl committed
559
560
561
562
563
564
565
566
567
        """
        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
568
569
        self._assign_index_as_input(node, idx)
        self._mark_computation(node, idx, [-1, -2])
oahzxl's avatar
oahzxl committed
570

oahzxl's avatar
oahzxl committed
571
    def _assign_elementwise_index(self, node, idx):
oahzxl's avatar
oahzxl committed
572
573
574
575
576
577
578
579
        """
        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
580
        """
oahzxl's avatar
oahzxl committed
581
        self._assign_index_as_input(node, idx)
582
        nodes_in = []
oahzxl's avatar
oahzxl committed
583
        for node_in in node.args:
584
585
586
587
588
589
590
591
592
593
            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
594

595
596
597
598
599
    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
600

601
602
603
604
605
606
607
608
609
610
    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
611

612
613
614
        patterns = patterns.replace(" ", "")
        left, right = patterns.split("->")
        left = left.split(",")
oahzxl's avatar
oahzxl committed
615

616
617
618
619
620
621
622
        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
623

624
625
626
627
        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
628
629
630
631
                    self._inherit_index(
                        input_nodes[left_idx], source_idx, node, right_idx
                    )

oahzxl's avatar
oahzxl committed
632
633
634
635
636
        # 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
637

oahzxl's avatar
oahzxl committed
638
    def _assign_softmax_index(self, node, idx):
oahzxl's avatar
oahzxl committed
639
640
641
642
643
644
645
646
        """
        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
647
        """
oahzxl's avatar
oahzxl committed
648
        self._assign_index_as_input(node, idx)
oahzxl's avatar
oahzxl committed
649
650
        self._mark_computation(node, idx, [node.kwargs["dim"]])

oahzxl's avatar
oahzxl committed
651
652
653
654
655
656
657
658
    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)
659
660
        """
        self._del_dim(node_idx, -1)
oahzxl's avatar
oahzxl committed
661
        self._assign_index_as_input(node, node_idx)
oahzxl's avatar
oahzxl committed
662
663
664
665
        self.idx_trace_list[node_idx]["idx"].insert(node.args[1], self._add_index())
        self.idx_trace_list[node_idx]["compute"].insert(node.args[1], [])
        self.idx_trace_list[node_idx]["source"].insert(node.args[1], [])

oahzxl's avatar
oahzxl committed
666
667
668
669
670
671
672
673
    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
674
        """
oahzxl's avatar
oahzxl committed
675
        self._assign_index_as_input(node, node_idx)
oahzxl's avatar
oahzxl committed
676

oahzxl's avatar
oahzxl committed
677
678
679
680
681
682
683
684
    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
685
        """
oahzxl's avatar
oahzxl committed
686
        self._assign_all_index(node, node_idx)
oahzxl's avatar
oahzxl committed
687

oahzxl's avatar
oahzxl committed
688
    def _assign_view_reshape_index(self, node, node_idx):
oahzxl's avatar
oahzxl committed
689
690
691
692
693
694
        """
        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
695
696
        5. inherit computation.
        6. TODO: look into view list to see whether the view is associated with other,
oahzxl's avatar
oahzxl committed
697
698
699
700
701
           if so assgin equal dim according to previous view.

        Args:
            node (node)
            node_idx (int)
oahzxl's avatar
oahzxl committed
702
        """
oahzxl's avatar
oahzxl committed
703
704
        # get data, turn into number
        origin_node = node.args[0]
oahzxl's avatar
oahzxl committed
705
        origin_shape = origin_node.meta["tensor_meta"].shape
oahzxl's avatar
oahzxl committed
706
707
708
709
710
        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
711
                target_shape.append(node.args[i].meta["fwd_out"][0])
oahzxl's avatar
oahzxl committed
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730

        # 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]
731
            self._add_dim(node_idx, -1)
oahzxl's avatar
oahzxl committed
732
733
734
735
736
        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]
737
            self._del_dim(node_idx, -1)
oahzxl's avatar
oahzxl committed
738
        else:
oahzxl's avatar
oahzxl committed
739
740
741
742
743
744
745
            raise NotImplementedError(
                "shape"
                + str(origin_shape)
                + "and"
                + str(target_shape)
                + "view not implemented"
            )
oahzxl's avatar
oahzxl committed
746
747

        # get new index
oahzxl's avatar
oahzxl committed
748
        origin_trace = self._find_idx_trace_from_node(origin_node)
749
        self._assign_index_as_input(node, node_idx, origin_node)
oahzxl's avatar
oahzxl committed
750
751
        dim_from.reverse()
        for i in dim_from:
752
            self._del_dim(node_idx, i)
oahzxl's avatar
oahzxl committed
753
        for i in dim_to:
754
            self._add_dim(node_idx, i)
oahzxl's avatar
oahzxl committed
755

oahzxl's avatar
oahzxl committed
756
        # inherit computation
oahzxl's avatar
oahzxl committed
757
        compute_log = self._find_compute_trace_from_node(origin_node)
oahzxl's avatar
oahzxl committed
758
759
760
        for i in dim_from:
            if origin_trace[i] in compute_log:
                for j in dim_to:
oahzxl's avatar
oahzxl committed
761
                    self._mark_computation(node, node_idx, [j])
oahzxl's avatar
oahzxl committed
762
                break
oahzxl's avatar
oahzxl committed
763

oahzxl's avatar
oahzxl committed
764
        # log view, not used now
oahzxl's avatar
oahzxl committed
765
766
767
768
769
770
771
        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,
        }
        self.idx_view_list.append(view_dict)
772

oahzxl's avatar
oahzxl committed
773
774
775
776
777
778
779
    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
780
781
782
783
784
                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
785
    def trace_index(self):
oahzxl's avatar
oahzxl committed
786
        for idx, node in enumerate(self.nodes_list):
oahzxl's avatar
oahzxl committed
787
            if node.op == "placeholder":
oahzxl's avatar
oahzxl committed
788
                self._assign_all_index(node, idx)
oahzxl's avatar
oahzxl committed
789
790
            elif node.op == "call_method":
                if "transpose" in node.name:
oahzxl's avatar
oahzxl committed
791
                    self._assign_transpose_index(node, idx)
oahzxl's avatar
oahzxl committed
792
                elif "permute" in node.name:
oahzxl's avatar
oahzxl committed
793
                    self._assign_permute_index(node, idx)
oahzxl's avatar
oahzxl committed
794
                elif "view" in node.name or "reshape" in node.name:
oahzxl's avatar
oahzxl committed
795
                    self._assign_view_reshape_index(node, idx)
oahzxl's avatar
oahzxl committed
796
                elif "unsqueeze" in node.name:
oahzxl's avatar
oahzxl committed
797
                    self._assign_unsqueeze_index(node, idx)
oahzxl's avatar
oahzxl committed
798
                elif any(i in node.name for i in ["to", "contiguous"]):
799
                    self._assgin_no_change_index(node, idx)
oahzxl's avatar
oahzxl committed
800
801
                else:
                    raise NotImplementedError(node.name, "method not implemented yet!")
oahzxl's avatar
oahzxl committed
802
803
            elif node.op == "call_function":
                if "linear" in node.name:
oahzxl's avatar
oahzxl committed
804
                    self._assign_linear_index(node, idx)
oahzxl's avatar
oahzxl committed
805
                elif "matmul" in node.name:
oahzxl's avatar
oahzxl committed
806
                    self._assign_matmul_index(node, idx)
oahzxl's avatar
oahzxl committed
807
                elif "softmax" in node.name:
oahzxl's avatar
oahzxl committed
808
                    self._assign_softmax_index(node, idx)
oahzxl's avatar
oahzxl committed
809
                elif any(n in node.name for n in ["mul", "add", "sigmoid", "relu"]):
oahzxl's avatar
oahzxl committed
810
                    self._assign_elementwise_index(node, idx)
oahzxl's avatar
oahzxl committed
811
                elif "ones_like" in node.name:
oahzxl's avatar
oahzxl committed
812
                    self._assign_ones_like_index(node, idx)
oahzxl's avatar
oahzxl committed
813
                elif "dropout" in node.name:
oahzxl's avatar
oahzxl committed
814
                    self._assign_dropout_index(node, idx)
oahzxl's avatar
oahzxl committed
815
                elif "einsum" in node.name:
816
                    self._assign_einsum_index(node, idx)
oahzxl's avatar
oahzxl committed
817
818
819
820
                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
821
                else:
oahzxl's avatar
oahzxl committed
822
823
824
825
826
                    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
827
                    self._assign_layernorm_index(node, idx)
oahzxl's avatar
oahzxl committed
828
829
                else:
                    raise NotImplementedError(node.name, "module not implemented yet!")
oahzxl's avatar
oahzxl committed
830
831
832
            elif node.op == "get_attr":
                self._assign_all_index(node, idx)  # get param
            elif node.op == "output":
oahzxl's avatar
oahzxl committed
833
                continue
oahzxl's avatar
oahzxl committed
834
835
            else:
                raise NotImplementedError(node.op, "op not implemented yet!")
836
        # self._merge_equal_idx()
oahzxl's avatar
oahzxl committed
837

oahzxl's avatar
oahzxl committed
838
839
840
841
842
843
844
845
846
847
848
849
850
851
    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
        """
        start_node_idx = _find_idx_by_name(start_node.name, self.nodes_list)
        end_node_trace = self._find_trace_from_node(end_node)
oahzxl's avatar
oahzxl committed
852
853
854
855
        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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
        for node_idx, node_dim in sorted_source:
            if node_idx == start_node_idx and node_dim == start_dim:
                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
877
        end_node_compute = end_node_trace["compute"][end_dim]
oahzxl's avatar
oahzxl committed
878
879
        if any(start_idx <= i <= end_idx for i in end_node_compute):
            return False
880
        return True
oahzxl's avatar
oahzxl committed
881

oahzxl's avatar
oahzxl committed
882
883
884
885
886
887
888
889
890
    def _get_node_chunk_dim(self, node_from, node_from_dim, node_to):
        node_from_source = self._find_source_trace_from_node(node_from)
        dim_source = node_from_source[node_from_dim]
        node_to_idx = _find_idx_by_name(node_to.name, self.nodes_list)
        for k, v in dim_source.items():
            if k == node_to_idx:
                return v
        return None

oahzxl's avatar
oahzxl committed
891

oahzxl's avatar
oahzxl committed
892
893
894
class MemoryEstimator(object):
    def __init__(self) -> None:
        pass
oahzxl's avatar
oahzxl committed
895

oahzxl's avatar
oahzxl committed
896
    def _get_meta_node_size(self, x):
oahzxl's avatar
oahzxl committed
897
        x = x.meta["tensor_meta"]
oahzxl's avatar
oahzxl committed
898
899
        x = x.numel * torch.tensor([], dtype=x.dtype).element_size()
        return x
oahzxl's avatar
oahzxl committed
900

oahzxl's avatar
oahzxl committed
901
    def _get_output_node(self, n):
oahzxl's avatar
oahzxl committed
902
903
904
905
906
        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
907
908
909
        out_size = activation_size(fwd_out)
        out_node = [n.name] if out_size > 0 else []
        return out_size, out_node
oahzxl's avatar
oahzxl committed
910

oahzxl's avatar
oahzxl committed
911
912
    def _get_output_node_size(self, n):
        return self._get_output_node(n)[0]
oahzxl's avatar
oahzxl committed
913

oahzxl's avatar
oahzxl committed
914
915
916
917
918
    def _add_active_node(self, n, active_list):
        new_active = self._get_output_node(n)[1]
        for i in new_active:
            if i not in active_list:
                active_list.append(i)
oahzxl's avatar
oahzxl committed
919

oahzxl's avatar
oahzxl committed
920
921
922
    def _get_delete_node(self, user, user_to_last_uses):
        delete_size = 0
        delete_node = []
oahzxl's avatar
oahzxl committed
923
        if user.op not in ("placeholder", "output"):
oahzxl's avatar
oahzxl committed
924
925
926
927
928
929
930
            nodes_to_delete = user_to_last_uses.get(user, [])
            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
931
                    elif nodes_to_delete[i].op == "placeholder":
oahzxl's avatar
oahzxl committed
932
                        delete_node.append(nodes_to_delete[i].name)
oahzxl's avatar
oahzxl committed
933
        return delete_size, delete_node
oahzxl's avatar
oahzxl committed
934

oahzxl's avatar
oahzxl committed
935
    def _get_delete_node_size(self, user, user_to_last_uses):
oahzxl's avatar
oahzxl committed
936
        return self._get_delete_node(user, user_to_last_uses)[0]
oahzxl's avatar
oahzxl committed
937

oahzxl's avatar
oahzxl committed
938
    def _remove_deactive_node(self, user, user_to_last_uses, active_list):
oahzxl's avatar
oahzxl committed
939
940
941
        delete_node = self._get_delete_node(user, user_to_last_uses)[1]
        for i in delete_node:
            active_list.remove(i)
oahzxl's avatar
oahzxl committed
942

oahzxl's avatar
oahzxl committed
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
    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
959
        not_contiguous_ops = ["transpose", "permute"]
oahzxl's avatar
oahzxl committed
960

oahzxl's avatar
oahzxl committed
961
962
963
        if node.op == "call_function" and any(
            n in node.name for n in ["matmul", "reshape"]
        ):
oahzxl's avatar
oahzxl committed
964
965
966
967
            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
968
        elif node.op == "call_module":
oahzxl's avatar
oahzxl committed
969
970
971
972
973
            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
974
975
976
        elif node.op == "call_method" and any(
            i in node.name for i in not_contiguous_ops
        ):
oahzxl's avatar
oahzxl committed
977
978
979
980
981
982
983
984
985
            if node not in not_contiguous_list:
                not_contiguous_list.append(node)
        elif any(i in node.args for i in not_contiguous_list):
            if node not in not_contiguous_list:
                not_contiguous_list.append(node)

        return mem

    def _get_chunk_ratio(self, node, chunk_dim, chunk_size):
oahzxl's avatar
oahzxl committed
986
987
        sorted_dim = sorted(chunk_dim, key=lambda x: list(x.keys())[0])
        dim = list(sorted_dim[-1].values())[0]
oahzxl's avatar
oahzxl committed
988
        shape = node.meta["tensor_meta"].shape
oahzxl's avatar
oahzxl committed
989
        chunk_ratio = float(chunk_size) / shape[dim]
oahzxl's avatar
oahzxl committed
990
991
        return chunk_ratio

oahzxl's avatar
oahzxl committed
992
993
994
995
    def _get_chunk_delete_node_size(
        self, user, user_to_last_uses, chunk_ratio, node_list, start_node, end_node
    ):
        if user.op in ("placeholder", "output"):
oahzxl's avatar
oahzxl committed
996
997
998
999
1000
1001
1002
1003
            return 0
        nodes_to_delete = user_to_last_uses.get(user, [])
        delete_size = 0
        for n in nodes_to_delete:
            node_idx = _find_idx_by_name(n.name, node_list)
            if start_node <= node_idx < end_node:
                delete_size += self._get_output_node_size(n) * chunk_ratio
        return delete_size
oahzxl's avatar
oahzxl committed
1004

oahzxl's avatar
oahzxl committed
1005
1006
1007
1008
    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
1009
            print("%s:%.2f \t" % (n.name, l), end="")
oahzxl's avatar
oahzxl committed
1010
1011
1012
1013
            if (idx + 1) % 3 == 0:
                print("")
        print("\n")

oahzxl's avatar
oahzxl committed
1014
1015
1016
1017
    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
1018
            if n.op in ["placeholder", "get_attr", "output"]:
oahzxl's avatar
oahzxl committed
1019
                continue
oahzxl's avatar
oahzxl committed
1020
            if any(i in n.name for i in ["getitem", "getattr"]):
oahzxl's avatar
oahzxl committed
1021
                continue
oahzxl's avatar
oahzxl committed
1022
            print("%s:%.2f \t" % (n.name, l), end="")
oahzxl's avatar
oahzxl committed
1023
1024
1025
            if (idx + 1) % 3 == 0:
                print("")
        print("\n")
oahzxl's avatar
oahzxl committed
1026
1027
1028
1029
1030
1031
1032
1033
1034

    def estimate_chunk_inference_mem(
        self,
        gm: torch.fx.GraphModule,
        start_nodes=None,
        end_nodes=None,
        chunk_dims=None,
        chunk_sizes=None,
    ):
oahzxl's avatar
oahzxl committed
1035
1036
1037
        act_memory = 0.0
        act_memory_peak_log = []
        act_memory_after_node_log = []
oahzxl's avatar
oahzxl committed
1038
1039
        active_node_list = []
        active_node_list_log = []
oahzxl's avatar
oahzxl committed
1040
        not_contiguous_list = []
oahzxl's avatar
oahzxl committed
1041
        node_list = list(gm.graph.nodes)
oahzxl's avatar
oahzxl committed
1042
1043
1044
        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
1045
1046
1047
1048

        use_chunk = all(
            i is not None for i in [start_nodes, end_nodes, chunk_dims, chunk_sizes]
        )
oahzxl's avatar
oahzxl committed
1049
1050
        chunk_within = False
        chunk_region_idx = 0
oahzxl's avatar
oahzxl committed
1051
        chunk_ratio = 1  # use it to estimate chunk mem
oahzxl's avatar
oahzxl committed
1052
1053
1054

        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
1055
1056
            if use_chunk and idx in start_nodes:
                chunk_within = True
oahzxl's avatar
oahzxl committed
1057
1058
1059
1060
1061
1062
1063
                chunk_ratio = self._get_chunk_ratio(
                    node, chunk_dims[chunk_region_idx], chunk_sizes[chunk_region_idx]
                )
                act_memory += self._get_output_node_size(
                    node_list[end_nodes[chunk_region_idx]]
                ) / (1024**2)

oahzxl's avatar
oahzxl committed
1064
            # if node is placeholder, just add the size of the node
oahzxl's avatar
oahzxl committed
1065
1066
            if node.op == "placeholder":
                act_memory += self._get_meta_node_size(node) * chunk_ratio / (1024**2)
oahzxl's avatar
oahzxl committed
1067
                act_memory_peak_log.append(act_memory)
oahzxl's avatar
oahzxl committed
1068
                active_node_list.append(node.name)
oahzxl's avatar
oahzxl committed
1069
            # skip output
oahzxl's avatar
oahzxl committed
1070
            elif node.op == "output":
oahzxl's avatar
oahzxl committed
1071
1072
                continue
            # node is an operation, calculate tmp, output node and delete node memory
oahzxl's avatar
oahzxl committed
1073
            else:
oahzxl's avatar
oahzxl committed
1074
                # forward memory
oahzxl's avatar
oahzxl committed
1075
1076
1077
1078
1079
1080
1081
1082
                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
1083
1084
1085
                # record max act memory
                act_memory_peak_log.append(act_memory)
                # delete useless memory
oahzxl's avatar
oahzxl committed
1086
1087
1088
1089
1090
                act_memory -= (
                    self._get_contiguous_memory(node, not_contiguous_list, delete=True)
                    * chunk_ratio
                    / (1024**2)
                )
oahzxl's avatar
oahzxl committed
1091
                if chunk_within:
oahzxl's avatar
oahzxl committed
1092
                    act_memory -= self._get_chunk_delete_node_size(
oahzxl's avatar
oahzxl committed
1093
1094
1095
1096
1097
1098
1099
                        node,
                        user_to_last_uses_no_free_var,
                        chunk_ratio,
                        node_list,
                        start_nodes[chunk_region_idx],
                        end_nodes[chunk_region_idx],
                    ) / (1024**2)
oahzxl's avatar
oahzxl committed
1100
                else:
oahzxl's avatar
oahzxl committed
1101
1102
1103
                    act_memory -= self._get_delete_node_size(
                        node, user_to_last_uses_no_free_var
                    ) / (1024**2)
oahzxl's avatar
oahzxl committed
1104
1105
1106
1107
1108
1109
1110

            # log active node
            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
            if use_chunk and idx in end_nodes:
oahzxl's avatar
oahzxl committed
1111
1112
1113
                act_memory -= (
                    self._get_output_node_size(node) * chunk_ratio / (1024**2)
                )
oahzxl's avatar
oahzxl committed
1114
                chunk_within = False
oahzxl's avatar
oahzxl committed
1115
                chunk_ratio = 1
oahzxl's avatar
oahzxl committed
1116
                chunk_region_idx += 1
oahzxl's avatar
oahzxl committed
1117

oahzxl's avatar
oahzxl committed
1118
            act_memory_after_node_log.append(act_memory)
oahzxl's avatar
oahzxl committed
1119
            active_node_list_log.append(copy.deepcopy(active_node_list))
oahzxl's avatar
oahzxl committed
1120

oahzxl's avatar
oahzxl committed
1121
        print("with chunk" if use_chunk else "without chunk")
oahzxl's avatar
oahzxl committed
1122
1123
1124
1125
        # 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")
        self._print_compute_op_mem_log(act_memory_after_node_log, node_list, "after")
oahzxl's avatar
oahzxl committed
1126

oahzxl's avatar
oahzxl committed
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
        # 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


class ChunkRegionSearch(object):
    def __init__(self, gm) -> None:
        self.gm = gm
        self.node_list = list(gm.graph.nodes)
        self.memory_estimator = MemoryEstimator()
oahzxl's avatar
oahzxl committed
1137
        self.index_tracer = IndexTracer(gm)
oahzxl's avatar
oahzxl committed
1138
1139
1140
        self.index_tracer.trace_index()
        self.flow_tracer = FlowTracer(gm)
        self.flow_tracer.trace_flow()
oahzxl's avatar
oahzxl committed
1141
1142
1143

    def _find_peak_node(self, mem_peak):
        max_value = max(mem_peak)
oahzxl's avatar
oahzxl committed
1144
        max_idx = mem_peak.index(max_value)
oahzxl's avatar
oahzxl committed
1145
        return max_idx
oahzxl's avatar
oahzxl committed
1146

oahzxl's avatar
oahzxl committed
1147
1148
1149
    def _get_free_var(self):
        free_var_idx = []
        for idx, n in enumerate(self.node_list):
oahzxl's avatar
oahzxl committed
1150
            if n.op == "placeholder":
oahzxl's avatar
oahzxl committed
1151
1152
                free_var_idx.append(idx)
        return free_var_idx
oahzxl's avatar
oahzxl committed
1153

oahzxl's avatar
oahzxl committed
1154
1155
1156
1157
1158
1159
1160
1161
    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
1162

oahzxl's avatar
oahzxl committed
1163
1164
1165
    def _search_max_chunk_region(self, active_node, peak_node):
        free_vars = self._get_free_var()
        min_var = self._get_min_free_var(active_node, free_vars)
oahzxl's avatar
oahzxl committed
1166

oahzxl's avatar
oahzxl committed
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
        # from peak_node to free_var
        chunk_region_start = None
        for i in range(peak_node, -1, -1):
            if len(active_node[i]) == min_var:
                chunk_region_start = i + 1
                break
            if i in free_vars or i == 0:
                raise RuntimeError()
        # from peak_node to len-2
        chunk_region_end = None
oahzxl's avatar
oahzxl committed
1177
        for i in range(peak_node, len(active_node)):
oahzxl's avatar
oahzxl committed
1178
            if len(active_node[i]) == min_var:
oahzxl's avatar
oahzxl committed
1179
                chunk_region_end = i
oahzxl's avatar
oahzxl committed
1180
1181
1182
1183
                break
            if i in free_vars or i == 0:
                raise RuntimeError()
        return chunk_region_start, chunk_region_end
oahzxl's avatar
oahzxl committed
1184

oahzxl's avatar
oahzxl committed
1185
    def _is_not_compute(self, trace, chunk_range, dim_idx):
oahzxl's avatar
oahzxl committed
1186
        if trace["idx"][dim_idx] not in trace["compute"]:
oahzxl's avatar
oahzxl committed
1187
            return True
oahzxl's avatar
oahzxl committed
1188
1189
1190
1191
        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
1192
1193
            return True
        return False
oahzxl's avatar
oahzxl committed
1194

oahzxl's avatar
oahzxl committed
1195
    def _check_duplicate_map(self, chunk_infos):
oahzxl's avatar
oahzxl committed
1196
        dim_map = [(i["inputs_dim"], i["outputs_dim"]) for i in chunk_infos]
oahzxl's avatar
oahzxl committed
1197
1198
1199
1200
1201
1202
1203
        remove_list = []
        for idx1, (input_dim1, output_dim1) in enumerate(dim_map):
            for idx2, (input_dim2, output_dim2) in enumerate(dim_map):
                if idx1 == idx2:
                    continue
                # it means an index create 2 copy of itself
                # eg. a = torch.matmul(x, x.transpose(-1, -2))
oahzxl's avatar
oahzxl committed
1204
                # TODO: currently remove it, deal with this in future
oahzxl's avatar
oahzxl committed
1205
1206
1207
1208
1209
1210
1211
                if input_dim1 == input_dim2 and output_dim1 != output_dim2:
                    remove_list.append(chunk_infos[idx1])
                    remove_list.append(chunk_infos[idx2])
        for i in remove_list:
            if i in chunk_infos:
                chunk_infos.remove(i)
        return chunk_infos
oahzxl's avatar
oahzxl committed
1212

oahzxl's avatar
oahzxl committed
1213
    def _find_free_dim(self, input_trace, output_trace, start_idx, end_idx):
oahzxl's avatar
oahzxl committed
1214
1215
1216
        start_traces = input_trace[start_idx]
        end_trace = output_trace[end_idx]
        end_node = self.node_list[end_idx]
oahzxl's avatar
oahzxl committed
1217
        chunk_infos = []
oahzxl's avatar
oahzxl committed
1218
        for end_dim, end_trace_idx in enumerate(end_trace["idx"]):
oahzxl's avatar
oahzxl committed
1219
            if len(start_traces) > 1:
oahzxl's avatar
oahzxl committed
1220
                # TODO: implement multi input chunk
1221
                continue
oahzxl's avatar
oahzxl committed
1222
            for start_node, start_trace in start_traces.items():
oahzxl's avatar
oahzxl committed
1223
                for start_dim, start_trace_idx in enumerate(start_trace["idx"]):
oahzxl's avatar
oahzxl committed
1224
1225
1226
1227
                    # must be same trace idx
                    if start_trace_idx != end_trace_idx:
                        continue
                    # dim size cannot be 1
oahzxl's avatar
oahzxl committed
1228
1229
1230
1231
                    if (
                        _get_node_shape(end_node)[end_dim] == 1
                        or _get_node_shape(start_node)[start_dim] == 1
                    ):
oahzxl's avatar
oahzxl committed
1232
1233
1234
                        continue
                    # check index source align
                    if not self.index_tracer.check_index_source(
oahzxl's avatar
oahzxl committed
1235
1236
                        start_dim, start_node, start_idx, end_dim, end_node
                    ):
oahzxl's avatar
oahzxl committed
1237
1238
1239
                        continue
                    # check index copmute
                    if not self.index_tracer.check_index_compute(
oahzxl's avatar
oahzxl committed
1240
1241
                        start_idx, end_dim, end_node, end_idx
                    ):
oahzxl's avatar
oahzxl committed
1242
1243
                        continue
                    # detect flow meet
oahzxl's avatar
oahzxl committed
1244
                    flow_block, chunk_info = self.flow_tracer._detect_flow(
oahzxl's avatar
oahzxl committed
1245
                        start_idx, start_dim, end_idx, end_dim, self.index_tracer
oahzxl's avatar
oahzxl committed
1246
                    )
oahzxl's avatar
oahzxl committed
1247
                    if flow_block:
oahzxl's avatar
oahzxl committed
1248
1249
1250
1251
                        continue
                    chunk_infos.append(chunk_info)
        chunk_infos = self._check_duplicate_map(chunk_infos)
        return chunk_infos
oahzxl's avatar
oahzxl committed
1252

oahzxl's avatar
oahzxl committed
1253
1254
    def _search_possible_chunk_regions(self, max_chunk_region, peak_node):
        possible_chunk_region = []
oahzxl's avatar
oahzxl committed
1255
        output_trace = copy.deepcopy(self.index_tracer.idx_trace_list)
oahzxl's avatar
oahzxl committed
1256
1257
1258
1259
        input_trace = []  # trace of a node's input nodes
        for _, n in enumerate(self.node_list):
            cur_trace = {}
            for arg in n.args:
oahzxl's avatar
oahzxl committed
1260
1261
1262
                if type(arg) == type(n) and not _is_non_compute_node_except_placeholder(
                    arg
                ):
oahzxl's avatar
oahzxl committed
1263
1264
1265
1266
                    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
1267
            for end_idx in range(peak_node, max_chunk_region[1] + 1):
oahzxl's avatar
oahzxl committed
1268
                # skip non compute nodes
oahzxl's avatar
oahzxl committed
1269
1270
1271
                if _is_non_compute_node(
                    self.node_list[start_idx]
                ) or _is_non_compute_node(self.node_list[end_idx]):
oahzxl's avatar
oahzxl committed
1272
                    continue
oahzxl's avatar
oahzxl committed
1273

oahzxl's avatar
oahzxl committed
1274
                # select free dim
oahzxl's avatar
oahzxl committed
1275
1276
1277
                chunk_info = self._find_free_dim(
                    input_trace, output_trace, start_idx, end_idx
                )
oahzxl's avatar
oahzxl committed
1278
1279
                if len(chunk_info) > 0:
                    possible_chunk_region.extend(chunk_info)
oahzxl's avatar
oahzxl committed
1280
        return possible_chunk_region
oahzxl's avatar
oahzxl committed
1281

oahzxl's avatar
oahzxl committed
1282
1283
1284
1285
    def _search_best_chunk_region(self, possible_chunk_regions):
        max_region_range = 0
        best_regions = None
        for i in possible_chunk_regions:
oahzxl's avatar
oahzxl committed
1286
            if i["region"][1] - i["region"][0] > max_region_range:
oahzxl's avatar
oahzxl committed
1287
                best_regions = i
oahzxl's avatar
oahzxl committed
1288
                max_region_range = i["region"][1] - i["region"][0]
oahzxl's avatar
oahzxl committed
1289
        return best_regions
oahzxl's avatar
oahzxl committed
1290

oahzxl's avatar
oahzxl committed
1291
1292
    def _step_search(self, mem_peak, active_node):
        peak_node = self._find_peak_node(mem_peak)
oahzxl's avatar
oahzxl committed
1293
        max_chunk_region = self._search_max_chunk_region(active_node, peak_node)
oahzxl's avatar
oahzxl committed
1294
1295
1296
        possible_chunk_regions = self._search_possible_chunk_regions(
            max_chunk_region, peak_node
        )
oahzxl's avatar
oahzxl committed
1297
1298
        best_chunk_region = self._search_best_chunk_region(possible_chunk_regions)
        return best_chunk_region
oahzxl's avatar
oahzxl committed
1299

oahzxl's avatar
oahzxl committed
1300
1301
1302
1303
1304
    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
1305

oahzxl's avatar
oahzxl committed
1306
    def search_region(self):
oahzxl's avatar
oahzxl committed
1307
        chunk_regions = []
oahzxl's avatar
oahzxl committed
1308
1309
1310
1311
1312
        (
            init_mem_peak,
            _,
            active_node,
        ) = self.memory_estimator.estimate_chunk_inference_mem(self.gm)
oahzxl's avatar
oahzxl committed
1313
        mem_peak = init_mem_peak
oahzxl's avatar
oahzxl committed
1314

oahzxl's avatar
oahzxl committed
1315
        while True:
oahzxl's avatar
oahzxl committed
1316
1317
            chunk_region = self._step_search(mem_peak, active_node)
            if chunk_region is None:
oahzxl's avatar
oahzxl committed
1318
                break
oahzxl's avatar
oahzxl committed
1319

oahzxl's avatar
oahzxl committed
1320
            chunk_regions.append(chunk_region)
oahzxl's avatar
oahzxl committed
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
            (
                mem_peak,
                _,
                active_node,
            ) = self.memory_estimator.estimate_chunk_inference_mem(
                self.gm,
                [i["region"][0] for i in chunk_regions],
                [i["region"][1] for i in chunk_regions],
                [i["inputs_dim"] for i in chunk_regions],
                [1] * len(chunk_regions),
            )
oahzxl's avatar
oahzxl committed
1332
1333
1334
            if self._stop_search(init_mem_peak, mem_peak):
                break
        return chunk_regions
oahzxl's avatar
oahzxl committed
1335
1336


oahzxl's avatar
oahzxl committed
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
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
1349
1350
1351
1352
1353
1354
1355
1356
1357
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
1358
1359
1360
    return context


oahzxl's avatar
oahzxl committed
1361
1362
1363
def _gen_loop_end(
    chunk_inputs, chunk_non_compute_inputs, chunk_outputs, chunk_outputs_dim, node_list
):
oahzxl's avatar
oahzxl committed
1364
1365
    chunk_outputs_name = chunk_outputs.name
    chunk_outputs_idx = _find_idx_by_name(chunk_outputs_name, node_list)
oahzxl's avatar
oahzxl committed
1366
    chunk_output_shape = chunk_outputs.meta["tensor_meta"].shape
oahzxl's avatar
oahzxl committed
1367
1368
1369
    chunk_slice = _gen_chunk_slice_dim(
        chunk_outputs_dim, "chunk_idx", chunk_output_shape
    )
oahzxl's avatar
oahzxl committed
1370
    context = "    chunk_result%s = %s\n" % (chunk_slice, chunk_outputs_name)
oahzxl's avatar
oahzxl committed
1371
1372
1373
    context += (
        chunk_outputs_name + " = chunk_result;  chunk_result = None;  chunk_size = None"
    )
oahzxl's avatar
oahzxl committed
1374

oahzxl's avatar
oahzxl committed
1375
    # determine if its the last use for chunk input
oahzxl's avatar
oahzxl committed
1376
    for chunk_input in chunk_inputs + chunk_non_compute_inputs:
oahzxl's avatar
oahzxl committed
1377
1378
1379
1380
1381
1382
1383
        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
1384
1385

    context += "\n"
oahzxl's avatar
oahzxl committed
1386
1387
    return context

oahzxl's avatar
init  
oahzxl committed
1388

oahzxl's avatar
oahzxl committed
1389
1390
1391
1392
1393
1394
1395
1396
1397
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
1398
            if input_node not in nodes and input_node not in input_nodes:
oahzxl's avatar
oahzxl committed
1399
1400
1401
1402
1403
                input_nodes.append(input_node)
    return input_nodes


def _find_chunk_compute_input_and_output_nodes(nodes: List[Node]):
oahzxl's avatar
oahzxl committed
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
    """
    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
1416
1417
1418
1419
1420
            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
1421
1422
1423
1424
                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
oahzxl's avatar
oahzxl committed
1425
    # TODO: it is unsafe to remove non compute node here
oahzxl's avatar
oahzxl committed
1426
1427
    for node in nodes:
        for output_node in node.users.keys():
oahzxl's avatar
oahzxl committed
1428
1429
1430
            if (
                output_node not in nodes
                and node not in output_nodes
oahzxl's avatar
oahzxl committed
1431
                and not _is_non_compute_node_except_placeholder(output_node)
oahzxl's avatar
oahzxl committed
1432
            ):
oahzxl's avatar
oahzxl committed
1433
1434
1435
1436
1437
                output_nodes.append(node)

    return input_nodes, output_nodes


oahzxl's avatar
oahzxl committed
1438
1439
1440
1441
1442
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
1443
1444


oahzxl's avatar
oahzxl committed
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
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
1455
1456
1457
1458
1459
1460
1461
1462
1463
def emit_code_with_chunk(
    body,
    ckpt_func,
    nodes,
    emit_node_func,
    delete_unused_value_func,
    meta_nodes,
    meta_graph,
):
oahzxl's avatar
init  
oahzxl committed
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
    """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
1475
    node_list = list(nodes)
oahzxl's avatar
init  
oahzxl committed
1476

oahzxl's avatar
oahzxl committed
1477
    # find the chunk regions
oahzxl's avatar
oahzxl committed
1478
1479
    chunk_region_search = ChunkRegionSearch(meta_graph)
    chunk_search = chunk_region_search.search_region()
oahzxl's avatar
init  
oahzxl committed
1480

oahzxl's avatar
oahzxl committed
1481
1482
1483
    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
1484

oahzxl's avatar
oahzxl committed
1485
1486
1487
    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
1488
1489
    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
1490
    ]
oahzxl's avatar
oahzxl committed
1491
1492
1493

    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
1494

oahzxl's avatar
init  
oahzxl committed
1495
    node_idx = 0
oahzxl's avatar
oahzxl committed
1496
    region_idx = 0
oahzxl's avatar
oahzxl committed
1497
1498
    within_chunk_region = False

oahzxl's avatar
oahzxl committed
1499
    while node_idx < len(node_list):
oahzxl's avatar
oahzxl committed
1500
        node = node_list[node_idx]
oahzxl's avatar
init  
oahzxl committed
1501

oahzxl's avatar
oahzxl committed
1502
1503
        if node_idx in chunk_starts:
            within_chunk_region = True
1504
            region_idx = chunk_starts.index(node_idx)
oahzxl's avatar
oahzxl committed
1505

oahzxl's avatar
oahzxl committed
1506
            # add for loop
oahzxl's avatar
oahzxl committed
1507
1508
            body.append(
                _gen_loop_start(
oahzxl's avatar
oahzxl committed
1509
1510
1511
                    chunk_inputs[region_idx],
                    chunk_outputs[region_idx],
                    chunk_outputs_dim[region_idx],
oahzxl's avatar
oahzxl committed
1512
1513
                )
            )
oahzxl's avatar
init  
oahzxl committed
1514

oahzxl's avatar
oahzxl committed
1515
1516
1517
        if within_chunk_region:
            emit_node_func(node, body)
            # replace input var with chunk var
oahzxl's avatar
oahzxl committed
1518
1519
1520
            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:
oahzxl's avatar
oahzxl committed
1521
1522
1523
                        chunk_slice = _gen_chunk_slice_dim(
                            dim, "chunk_idx", _get_node_shape(input_node)
                        )
oahzxl's avatar
oahzxl committed
1524
1525
1526
                        body[-1] = _replace_name(
                            body[-1], input_node.name, input_node.name + chunk_slice
                        )
oahzxl's avatar
oahzxl committed
1527
            body[-1] = "    " + body[-1]
oahzxl's avatar
oahzxl committed
1528
            delete_unused_value_func(node, body, chunk_inputs_names)
oahzxl's avatar
init  
oahzxl committed
1529

oahzxl's avatar
oahzxl committed
1530
1531
1532
1533
        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
1534

oahzxl's avatar
oahzxl committed
1535
        if node_idx in chunk_ends:
oahzxl's avatar
oahzxl committed
1536
1537
            body.append(
                _gen_loop_end(
oahzxl's avatar
oahzxl committed
1538
1539
1540
                    chunk_inputs[region_idx],
                    chunk_inputs_non_chunk[region_idx],
                    chunk_outputs[region_idx],
oahzxl's avatar
oahzxl committed
1541
1542
                    chunk_outputs_dim[region_idx],
                    node_list,
oahzxl's avatar
oahzxl committed
1543
1544
                )
            )
oahzxl's avatar
oahzxl committed
1545
            within_chunk_region = False
oahzxl's avatar
init  
oahzxl committed
1546

oahzxl's avatar
oahzxl committed
1547
        node_idx += 1
oahzxl's avatar
init  
oahzxl committed
1548
1549
1550
1551


if CODEGEN_AVAILABLE:

oahzxl's avatar
oahzxl committed
1552
    class ChunkCodeGen(CodeGen):
oahzxl's avatar
oahzxl committed
1553
1554
        def __init__(self, meta_graph):
            super().__init__()
oahzxl's avatar
oahzxl committed
1555
            self.meta_graph = meta_graph
oahzxl's avatar
oahzxl committed
1556
            self.meta_node = list(meta_graph.graph.nodes)
oahzxl's avatar
init  
oahzxl committed
1557

oahzxl's avatar
oahzxl committed
1558
1559
1560
        def _gen_python_code(
            self, nodes, root_module: str, namespace: _Namespace
        ) -> PythonCode:
oahzxl's avatar
init  
oahzxl committed
1561
1562
1563
1564
1565
1566
            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
1567
            maybe_return_annotation: List[str] = [""]
oahzxl's avatar
init  
oahzxl committed
1568
1569
1570
1571
1572
1573
1574
1575
1576

            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
1577
1578
1579
                if (
                    _is_from_torch(obj) and obj != torch.device
                ):  # to support registering torch.device
oahzxl's avatar
init  
oahzxl committed
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
                    # 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
1595
1596
1597
            _custom_builtins["colossalai"] = _CustomBuiltin(
                "import colossalai", colossalai
            )
oahzxl's avatar
init  
oahzxl committed
1598
1599
1600
1601
1602
1603
1604
1605

            # 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
1606
                    return "()"
oahzxl's avatar
init  
oahzxl committed
1607
1608
1609

                typename = _type_repr(o)

oahzxl's avatar
oahzxl committed
1610
                if hasattr(o, "__origin__"):
oahzxl's avatar
init  
oahzxl committed
1611
1612
1613
1614
                    # 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
1615
                    if hasattr(o, "__args__"):
oahzxl's avatar
init  
oahzxl committed
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
                        # 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
1633
1634
1635
            def _format_args(
                args: Tuple[Argument, ...], kwargs: Dict[str, Argument]
            ) -> str:
oahzxl's avatar
init  
oahzxl committed
1636
1637
                def _get_repr(arg):
                    # Handle NamedTuples (if it has `_fields`) via add_global.
oahzxl's avatar
oahzxl committed
1638
                    if isinstance(arg, tuple) and hasattr(arg, "_fields"):
oahzxl's avatar
init  
oahzxl committed
1639
1640
1641
1642
1643
                        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
1644
1645
                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
1646
                if args_s and kwargs_s:
oahzxl's avatar
oahzxl committed
1647
                    return f"{args_s}, {kwargs_s}"
oahzxl's avatar
init  
oahzxl committed
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
                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
1665

oahzxl's avatar
oahzxl committed
1666
            _delete_free_var_from_last_use(user_to_last_uses)
oahzxl's avatar
oahzxl committed
1667

oahzxl's avatar
init  
oahzxl committed
1668
            # NOTE: we add a variable to distinguish body and ckpt_func
oahzxl's avatar
oahzxl committed
1669
            def delete_unused_values(user: Node, body, to_keep=[]):
oahzxl's avatar
init  
oahzxl committed
1670
1671
1672
1673
1674
                """
                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
1675
                if user.op == "placeholder":
oahzxl's avatar
init  
oahzxl committed
1676
                    return
oahzxl's avatar
oahzxl committed
1677
1678
                if user.op == "output":
                    body.append("\n")
oahzxl's avatar
init  
oahzxl committed
1679
1680
                    return
                nodes_to_delete = user_to_last_uses.get(user, [])
oahzxl's avatar
oahzxl committed
1681
                nodes_to_delete = [i for i in nodes_to_delete if i.name not in to_keep]
oahzxl's avatar
init  
oahzxl committed
1682
                if len(nodes_to_delete):
oahzxl's avatar
oahzxl committed
1683
1684
1685
1686
                    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
1687
                else:
oahzxl's avatar
oahzxl committed
1688
                    body.append("\n")
oahzxl's avatar
init  
oahzxl committed
1689
1690
1691

            # NOTE: we add a variable to distinguish body and ckpt_func
            def emit_node(node: Node, body):
oahzxl's avatar
oahzxl committed
1692
1693
1694
1695
                maybe_type_annotation = (
                    "" if node.type is None else f" : {type_repr(node.type)}"
                )
                if node.op == "placeholder":
oahzxl's avatar
init  
oahzxl committed
1696
                    assert isinstance(node.target, str)
oahzxl's avatar
oahzxl committed
1697
1698
1699
1700
1701
1702
1703
                    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
1704
                    if raw_name != repr(node):
oahzxl's avatar
oahzxl committed
1705
                        body.append(f"{repr(node)} = {raw_name}\n")
oahzxl's avatar
init  
oahzxl committed
1706
                    return
oahzxl's avatar
oahzxl committed
1707
                elif node.op == "call_method":
oahzxl's avatar
init  
oahzxl committed
1708
1709
                    assert isinstance(node.target, str)
                    body.append(
oahzxl's avatar
oahzxl committed
1710
1711
1712
                        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
1713
                    return
oahzxl's avatar
oahzxl committed
1714
                elif node.op == "call_function":
oahzxl's avatar
init  
oahzxl committed
1715
1716
                    assert callable(node.target)
                    # pretty print operators
oahzxl's avatar
oahzxl committed
1717
1718
1719
1720
                    if (
                        node.target.__module__ == "_operator"
                        and node.target.__name__ in magic_methods
                    ):
oahzxl's avatar
init  
oahzxl committed
1721
                        assert isinstance(node.args, tuple)
oahzxl's avatar
oahzxl committed
1722
1723
1724
1725
                        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
1726
1727
1728
1729
                        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
1730
1731
1732
1733
1734
1735
1736
1737
                    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
1738
1739
1740
1741
1742
1743
                        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
1744
1745
1746
1747
1748
1749
1750
                    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
1751
                        body.append(
oahzxl's avatar
oahzxl committed
1752
1753
                            f"{repr(node)}{maybe_type_annotation} = {_format_target(repr(node.args[0]), node.args[1])}"
                        )
oahzxl's avatar
init  
oahzxl committed
1754
1755
                        return
                    body.append(
oahzxl's avatar
oahzxl committed
1756
1757
1758
                        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
1759
1760
                        wrapped_fns.setdefault(global_name)
                    return
oahzxl's avatar
oahzxl committed
1761
                elif node.op == "call_module":
oahzxl's avatar
init  
oahzxl committed
1762
                    assert isinstance(node.target, str)
oahzxl's avatar
oahzxl committed
1763
1764
1765
1766
                    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
1767
                    return
oahzxl's avatar
oahzxl committed
1768
                elif node.op == "get_attr":
oahzxl's avatar
init  
oahzxl committed
1769
                    assert isinstance(node.target, str)
oahzxl's avatar
oahzxl committed
1770
1771
1772
                    body.append(
                        f"{repr(node)}{maybe_type_annotation} = {_format_target(root_module, node.target)}"
                    )
oahzxl's avatar
init  
oahzxl committed
1773
                    return
oahzxl's avatar
oahzxl committed
1774
                elif node.op == "output":
oahzxl's avatar
init  
oahzxl committed
1775
1776
1777
1778
                    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
1779
                raise NotImplementedError(f"node: {node.op} {node.target}")
oahzxl's avatar
init  
oahzxl committed
1780
1781
1782
1783
1784
1785

            # 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
1786
1787
1788
1789
1790
1791
1792
1793
1794
            emit_code_with_chunk(
                body,
                ckpt_func,
                nodes,
                emit_node,
                delete_unused_values,
                self.meta_node,
                self.meta_graph,
            )
oahzxl's avatar
init  
oahzxl committed
1795
1796
1797
1798
1799

            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
1800
                body.append("pass\n")
oahzxl's avatar
init  
oahzxl committed
1801
1802

            if len(wrapped_fns) > 0:
oahzxl's avatar
oahzxl committed
1803
1804
1805
1806
                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
1807
            else:
oahzxl's avatar
oahzxl committed
1808
                wrap_stmts = ""
oahzxl's avatar
init  
oahzxl committed
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818

            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
1819
            prologue = "".join(ckpt_func) + prologue
oahzxl's avatar
init  
oahzxl committed
1820
1821
            prologue = prologue

oahzxl's avatar
oahzxl committed
1822
1823
            code = "".join(body)
            code = "\n".join("    " + line for line in code.split("\n"))
oahzxl's avatar
init  
oahzxl committed
1824
1825
1826
1827
            fn_code = f"""
{wrap_stmts}

{prologue}
oahzxl's avatar
oahzxl committed
1828
{code}"""
oahzxl's avatar
oahzxl committed
1829
            print(fn_code)
oahzxl's avatar
init  
oahzxl committed
1830
            return PythonCode(fn_code, globals_)