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

Class MLXProgramBuilder

backends/mlx/builder/program_builder.py:125–1090  ·  view source on GitHub ↗

Builds an MLXGraph from an ExportedProgram. Args: ep: The ExportedProgram to build from

Source from the content-addressed store, hash-verified

123
124
125class MLXProgramBuilder:
126 """
127 Builds an MLXGraph from an ExportedProgram.
128
129 Args:
130 ep: The ExportedProgram to build from
131 """
132
133 def __init__(self, ep: ExportedProgram, named_data_key_prefix: str = ""):
134 self.ep: ExportedProgram = ep
135 self._chains: List[List[Instruction]] = [[]] # chain 0 = main
136 self._current_chain: int = 0
137 self.init_chain_idx: int = -1
138 self.extra_constants: Dict[str, torch.Tensor] = {}
139 self.slot_manager = SlotManager()
140 self.node_info: DefaultDict[Node, NodeInfo] = defaultdict(NodeInfo)
141 self._mlx_graph: Optional[MLXGraph] = None
142 # Map from SymInt symbol names (e.g., "s77") to the FX Node that produces them.
143 # This is used to resolve symbolic tensor dimensions to Vid references.
144 self._symint_to_node: Dict[str, Node] = {}
145 # Maps for remapping local slot indices to global Tid/Vid indices during build
146 self._tid_slot_map: List[Tuple[Tid, Slot]] = []
147 self._vid_slot_map: List[Tuple[Vid, Slot]] = []
148 # Prefix for named_data_store keys and named_slots to avoid collisions
149 # in multi-method programs where different methods may have lifted tensor
150 # constants with the same auto-generated name.
151 self._named_data_key_prefix: str = named_data_key_prefix
152 # Unprefixed canonical-name → Slot for constants, populated by _build_io_maps().
153 # Used by get_named_data_store() to look up tensors without prefix interference.
154 self._constant_name_to_slot: Dict[str, Slot] = {}
155
156 def _prefix_key(self, name: str) -> str:
157 """Apply the named-data key prefix for the .pte namespace.
158
159 This is the single point where canonical (unprefixed) names are
160 transformed into the external keys used in the .pte's ``named_data``
161 section and the FlatBuffer ``named_slots`` field.
162 """
163 if self._named_data_key_prefix:
164 return f"{self._named_data_key_prefix}/{name}"
165 return name
166
167 def emit(self, op: OpNodeUnion) -> None:
168 self._chains[self._current_chain].append(Instruction(op=op))
169
170 def emit_init(self, op: OpNodeUnion) -> None:
171 if self.init_chain_idx == -1:
172 self.init_chain_idx = len(self._chains)
173 self._chains.append([])
174 self._chains[self.init_chain_idx].append(Instruction(op=op))
175
176 @contextmanager
177 def new_chain(self):
178 """Context manager that creates a new instruction chain and redirects emit() to it.
179
180 Usage:
181 with P.new_chain() as chain_idx:
182 P.emit(MulNode(...)) # goes to the new chain

Callers 3

preprocessMethod · 0.90
__init__Method · 0.90
ops_to_not_decomposeMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected