MCPcopy Create free account
hub / github.com/pytorch/executorch / naive

Function naive

exir/memory_planning.py:1111–1166  ·  view source on GitHub ↗

Naive algorithm to allocate memory for tensors in the graph. This algorithm simply allocates memory for each tensor sequentially without reusing memory. Args: alignment: Memory alignment requirement specs: Set of TensorSpec objects with updated lifetimes graph_modul

(
    alignment: int,
    specs: Set[TensorSpec],
    graph_module: torch.fx.GraphModule,
    graph_signature: ExportGraphSignature,
    extra_padding: int,
)

Source from the content-addressed store, hash-verified

1109
1110
1111def naive(
1112 alignment: int,
1113 specs: Set[TensorSpec],
1114 graph_module: torch.fx.GraphModule,
1115 graph_signature: ExportGraphSignature,
1116 extra_padding: int,
1117) -> MemoryAlgoResult:
1118 """Naive algorithm to allocate memory for tensors in the graph.
1119
1120 This algorithm simply allocates memory for each tensor sequentially without reusing memory.
1121
1122 Args:
1123 alignment: Memory alignment requirement
1124 specs: Set of TensorSpec objects with updated lifetimes
1125 graph_module: Graph module
1126 graph_signature: Graph signature
1127 extra_padding: Additional padding to add to each memory buffer (in bytes)
1128
1129 Returns:
1130 MemoryAlgoResult containing the allocation decisions
1131 """
1132 naive_result = MemoryAlgoResult({}, [])
1133
1134 # allocate 'allocated' bytes from buffer with id mem_id.
1135 # return the starting offset of the allocated buffer.
1136 def _allocate_buf(bufsizes: List[int], mem_id: int, allocated: int) -> int:
1137 if mem_id >= len(bufsizes):
1138 bufsizes.extend([0] * (mem_id - len(bufsizes) + 1))
1139 ret = bufsizes[mem_id]
1140 bufsizes[mem_id] += allocated
1141 return ret
1142
1143 bufsizes = getattr(graph_module, "input_mem_buffer_sizes", None)
1144 if bufsizes is None:
1145 bufsizes = [0, 0]
1146 bufsizes = cast(List[int], bufsizes)
1147
1148 for spec in specs:
1149 spec_alloc_result = naive_result.spec_dict.get(spec, SpecAllocResult(0, 0, 0))
1150 # assume a single memory layer which has mem_id 1
1151 if spec.mem_id is None:
1152 spec_alloc_result.mem_id = 1
1153 else:
1154 spec_alloc_result.mem_id = spec.mem_id
1155 naive_result.spec_dict[spec] = spec_alloc_result
1156
1157 # allocate spec.allocated_memory bytes in the buffer
1158 # with the corresponding mem_id
1159 spec.realign(alignment)
1160 spec_alloc_result.mem_offset = _allocate_buf(
1161 bufsizes, spec_alloc_result.mem_id, spec.allocated_memory
1162 )
1163
1164 logging.debug(f"naive algorithm returns bufsizes: {bufsizes}")
1165 naive_result.bufsizes = bufsizes
1166 return naive_result
1167
1168

Callers

nothing calls this directly

Calls 6

MemoryAlgoResultClass · 0.85
SpecAllocResultClass · 0.85
_allocate_bufFunction · 0.85
realignMethod · 0.80
debugMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected