Skip to content

Commit 1ea2266

Browse files
authored
[DOCS ]Add annotated partitioning documentation (#27972)
This pull request introduces a new documentation page, `PartitioningWithAnnotationsAndMemoryConstraints.md`, which explains advanced ONNX Runtime features for partitioning model graphs across devices with explicit control. The doc covers how to annotate model layers for device assignment, collect per-node memory statistics, and enforce GPU memory budgets during partitioning. These features enable precise control over device placement and memory usage for large models. The most important changes are: **New Documentation: Advanced Partitioning Features** * Adds a comprehensive guide (`PartitioningWithAnnotationsAndMemoryConstraints.md`) describing how to use ONNX Runtime’s layer annotation and memory constraint features for graph partitioning. **Layer Assignment via Annotations** * Explains how to annotate ONNX model nodes with `layer_ann` metadata, including manual annotation and automated annotation using Olive’s `CaptureLayerAnnotations` pass. * Provides configuration examples for mapping annotation patterns to devices at runtime using the `session.layer_assignment_settings` session option. **Capacity-Aware Partitioning** * Details a two-phase workflow for profiling per-node memory usage and then enforcing a memory budget with the `session.resource_cuda_partitioning_settings` session option. * Covers both profiling-based and ad-hoc (estimation-only) approaches for memory-constrained partitioning. ([docs/annotated_partitioning/PartitioningWithAnnotationsAndMemoryConstraints.mdR1-R267](diffhunk://#diff-10b3051b9e36eccfc7ca0f2d44ce78a9980ca573cde0f931ffd1456da2c681daR1-R267) This is a follow up for #27595
1 parent c86a05a commit 1ea2266

1 file changed

Lines changed: 308 additions & 0 deletions

File tree

Lines changed: 308 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,308 @@
1+
# Graph Partitioning with Annotations and Memory Constraints
2+
3+
ONNX Runtime automatically partitions a model graph across the execution providers (EPs) registered with a session. This page describes the advanced partitioning features introduced for controlling how nodes are assigned to devices and how GPU memory consumption is managed during partitioning.
4+
5+
## Overview
6+
7+
Large models may exceed the memory capacity of a single accelerator (e.g., a CUDA GPU). These features allow you to:
8+
1. Annotate model layers so that specific parts of the model are directed to specific devices (CPU, GPU, NPU).
9+
2. Collect per-node memory statistics during a profiling run.
10+
3. Set a memory budget for an EP so that ONNX Runtime only places nodes on the accelerator until the budget is exhausted; remaining nodes are then eligible for assignment by the subsequent EPs in the session's provider list (often CPU, but not necessarily).
11+
12+
Together, these form a two-phase workflow: profile the model once to collect memory data, then partition it in production using that data and a memory limit.
13+
14+
## Layer Assignment Annotations
15+
16+
### Concept
17+
18+
Each node in an ONNX model can carry a metadata property called `layer_ann` (layering annotation). This is a free-form string that identifies which logical layer or group the node belongs to. At session creation time, you provide a configuration that maps annotation patterns to target devices. ONNX Runtime then uses these mappings to pre-assign nodes to the corresponding EPs before the normal capability-based partitioning runs.
19+
20+
### Annotating the Model
21+
22+
Annotations are stored in each ONNX `NodeProto`'s `metadata_props` field with the key `layer_ann`. You can add them manually using the ONNX Python API:
23+
24+
```python
25+
import onnx
26+
model = onnx.load("model.onnx")
27+
for node in model.graph.node:
28+
# Assign a layer annotation based on your own logic
29+
entry = next((prop for prop in node.metadata_props if prop.key == "layer_ann"), None)
30+
if entry is None:
31+
entry = node.metadata_props.add()
32+
entry.key = "layer_ann"
33+
entry.value = "encoder_layer_0" # your annotation string
34+
35+
onnx.save(model, "model_annotated.onnx")
36+
```
37+
38+
### Annotating with Olive
39+
40+
Olive provides built-in support for adding layer annotations during ONNX conversion via the `CaptureLayerAnnotations` pass (added in [PR #2361](https://github.com/microsoft/Olive/pull/2361)). You supply a `layer_annotations` dictionary where each **key** is the annotation string to write into `layer_ann`, and each **value** is a list of node-name substrings. During ONNX export, every node whose name contains one of the substrings receives the corresponding `layer_ann` metadata property. If multiple substrings match, the first one in iteration order wins.
41+
42+
Many exported transformer models use consistent node naming patterns. For example, node names often include recurring substrings such as `embed_tokens`, `self_attn`, `mlp`, or `norm`. Because `CaptureLayerAnnotations` matches node-name substrings, these patterns can be used to group related nodes into logical layers and write the corresponding `layer_ann` values during export. Adjust the substrings to match the naming conventions in your own model.
43+
44+
#### Step 1 — Create the workflow config file
45+
46+
Save the following as `annotate_model.json`:
47+
48+
```json
49+
{
50+
"input_model": {
51+
"type": "HfModel",
52+
"model_path": "microsoft/Phi-3.5-mini-instruct"
53+
},
54+
"passes": {
55+
"capture_annotations": {
56+
"type": "CaptureLayerAnnotations",
57+
"layer_annotations": {
58+
"embedding_layer": ["embed_tokens"],
59+
"attention_layer": ["self_attn", "q_proj", "k_proj", "v_proj", "o_proj"],
60+
"mlp_layer": ["mlp", "gate_proj", "up_proj", "down_proj"],
61+
"norm_layer": ["norm", "layernorm"]
62+
}
63+
},
64+
"conversion": {
65+
"type": "OnnxConversion",
66+
"target_opset": 16,
67+
"save_as_external_data": true,
68+
"all_tensors_to_one_file": true
69+
}
70+
},
71+
"log_severity_level": 1,
72+
"output_dir": "models/annotated_phi3"
73+
}
74+
```
75+
76+
The `layer_annotations` dictionary maps annotation names to node-name substring patterns:
77+
- Any node whose name contains `"embed_tokens"` → annotated as `"embedding_layer"`
78+
- Any node whose name contains `"self_attn"`, `"q_proj"`, etc. → annotated as `"attention_layer"`
79+
- And so on for `"mlp_layer"` and `"norm_layer"`.
80+
81+
You can also use `ModelBuilder` instead of `OnnxConversion` — both paths apply the annotations automatically:
82+
83+
```json
84+
"conversion": {
85+
"type": "ModelBuilder",
86+
"precision": "int4"
87+
}
88+
```
89+
90+
#### Step 2 — Run the workflow
91+
92+
```bash
93+
pip install 'olive-ai[auto-opt]'
94+
olive run --config annotate_model.json
95+
```
96+
97+
This will:
98+
1. Download the model from Hugging Face.
99+
2. Store the `layer_annotations` mapping inside `model_attributes` (via `CaptureLayerAnnotations`).
100+
3. Convert to ONNX and stamp every matching node with `metadata_props["layer_ann"]` set to the corresponding annotation name.
101+
4. Write the annotated ONNX model to `models/annotated_phi3/`.
102+
103+
#### Verifying the annotations
104+
105+
You can verify that the annotations were applied:
106+
107+
```python
108+
import onnx
109+
110+
model = onnx.load("models/annotated_phi3/model.onnx", load_external_data=False)
111+
for node in model.graph.node:
112+
for prop in node.metadata_props:
113+
if prop.key == "layer_ann":
114+
print(f"{node.name}: {prop.value}")
115+
```
116+
117+
The annotated model is now ready for use with the ORT session options described below.
118+
119+
### Configuring Layer Assignment at Runtime
120+
121+
Use the session option `session.layer_assignment_settings` to tell ONNX Runtime how to map annotations to devices.
122+
123+
```
124+
device1(annotation1, annotation2, ...); device2(=annotation3, annotation4, ...)
125+
```
126+
127+
- `device`: a recognized device designator, matched against the execution providers registered in the session. The supported designators are:
128+
129+
| Device Designator | Meaning | Examples of EPs That May Bind |
130+
|:------------------|:--------|:-----------------------------|
131+
| `cpu` | Any CPU device | CPUExecutionProvider |
132+
| `gpu` | Anything discovered and designated as `OrtHardwareDeviceType_GPU` | CUDA EP, ROCm EP, DirectML EP running on discrete or integrated GPUs |
133+
| `cuda` | NVIDIA CUDA GPU. A device that is `OrtHardwareDeviceType_GPU` and NVIDIA is a vendor. Same as `gpu:nvidia`. | CUDAExecutionProvider |
134+
| `dml` | DirectX-compatible GPU | DMLExecutionProvider |
135+
| `npu` | Neural processing unit | Qualcomm QNN EP, Intel NPU EP |
136+
| `fpga` | FPGA-backed accelerators | Custom plugin EPs |
137+
| `accelerator` | Catch-all for any non-CPU device | Any vendor EP |
138+
| `gpu:<vendor>` | Vendor specialization | `gpu:nvidia`, `gpu:amd`, `gpu:intel` |
139+
| `gpu:<index>` | Specific device index | GPU 0, GPU 1 |
140+
141+
- `annotation`: string to match against the `layer_ann` value on each node.
142+
- `=` prefix: denotes an exact match. Without `=`, the annotation is treated as a prefix match (any node whose `layer_ann` starts with the string will match).
143+
- Prefix rules have higher priority than exact-match rules. Within the same match type, priority is left-to-right.
144+
- Multiple device rules are separated by `;`.
145+
146+
```python
147+
import onnxruntime as ort
148+
149+
opts = ort.SessionOptions()
150+
151+
# Nodes annotated with layer_ann starting with "encoder" go to GPU,
152+
# nodes with exact annotation "final_output" go to CPU.
153+
opts.add_session_config_entry(
154+
"session.layer_assignment_settings",
155+
"gpu(encoder); cpu(=final_output)"
156+
)
157+
158+
session = ort.InferenceSession("model_annotated.onnx", opts,
159+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
160+
```
161+
162+
#### Targeting a Specific GPU
163+
164+
On a machine with multiple GPUs, use `gpu:<index>` to direct annotations to a particular device:
165+
166+
```python
167+
opts.add_session_config_entry(
168+
"session.layer_assignment_settings",
169+
"gpu:1(encoder, decoder); cpu(=postprocess)"
170+
)
171+
```
172+
173+
> **Note:** ONNX Runtime currently allows only one instance of a given EP type per session, so you cannot split annotations across multiple GPUs in a single session. The `gpu:<index>` designator selects *which* GPU the single registered EP targets.
174+
175+
Nodes that do not match any rule fall through to the normal EP capability-based assignment.
176+
177+
> **Unmatched device designators:** If a device designator in the settings does not match any EP registered in the session, ONNX Runtime logs a warning and skips that rule. Nodes covered by the skipped rule are not pre-assigned and fall through to the normal capability-based partitioning.
178+
179+
> **Note — Annotations vs. actual placement:** An annotation expresses a *preference*, not a guarantee. If the target EP does not have a registered kernel for a node (for example, a particular data-type / opset-version combination is not implemented in the CUDA EP), that node will not be placed on the requested device. Instead it falls through to the next EP in the provider list that can handle it.
180+
181+
## Capacity-Aware Partitioning (implemented for CUDA)
182+
183+
When running models on a CUDA GPU with limited memory, you can set a memory budget so ONNX Runtime stops assigning nodes to the CUDA EP once the estimated memory consumption reaches the limit. Nodes are considered in topological order and assignment halts at the first node that would exceed the budget — ONNX Runtime does not search ahead for smaller nodes that might still fit. Remaining nodes are then eligible for assignment by the subsequent EPs in the session's provider list (often CPU, but not necessarily).
184+
185+
### Step 1: Collect Memory Statistics (Profiling Run)
186+
187+
Run the model once with memory statistics collection enabled. This records per-node allocation data to a CSV file.
188+
189+
```python
190+
import onnxruntime as ort
191+
import numpy as np
192+
193+
opts = ort.SessionOptions()
194+
# Disable memory patterns for accurate per-node measurement
195+
opts.enable_mem_pattern = False
196+
opts.add_session_config_entry(
197+
"session.collect_node_memory_stats_to_file",
198+
"node_memory_stats.csv"
199+
)
200+
201+
session = ort.InferenceSession("model.onnx", opts,
202+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
203+
204+
def make_concrete_shape(shape, default_dim=1):
205+
"""ORT input shapes may contain symbolic dims or None (e.g. batch size).
206+
Replace those with a small concrete value for profiling.
207+
208+
For the most accurate memory statistics, use the largest input shapes
209+
your production workload will encounter. For example, if your service
210+
runs with a maximum batch size of 8, pass default_dim=8 so the profiled
211+
allocations reflect that peak usage."""
212+
return tuple(
213+
dim if isinstance(dim, int) and dim > 0 else default_dim
214+
for dim in shape
215+
)
216+
217+
# Run inference at least once to collect statistics.
218+
# For models with dynamic inputs, prefer real sample inputs or model-appropriate
219+
# concrete shapes instead of relying on the declared ORT input shape directly.
220+
input_data = {
221+
inp.name: np.zeros(make_concrete_shape(inp.shape), dtype=np.float32)
222+
for inp in session.get_inputs()
223+
}
224+
session.run(None, input_data)
225+
```
226+
227+
This produces a CSV file with columns:
228+
`#name,input_sizes,initializers_sizes,total_dynamic_sizes,total_temp_allocations`
229+
230+
In this example, `node_memory_stats.csv` is a relative path. Relative paths are resolved against the model's directory when the model was loaded from a filesystem path. If you provide an absolute path, that path is used as-is. If the model was not loaded from a filesystem path (for example, it was loaded from bytes), the output file is written relative to the current working directory.
231+
232+
Multiple `session.run()` calls update the stats with the maximum values observed per node.
233+
234+
> **What if the GPU cannot hold the entire model?** The profiling run itself requires the model to fit in GPU memory because the CUDA EP must execute each node to record its actual allocations. If the model exceeds GPU capacity during profiling, reduce the input dimensions (e.g., use a smaller batch size) so that the run completes. The resulting per-node statistics will still be representative of relative node costs and can be used to set the memory budget for subsequent production sessions.
235+
236+
### Step 2: Partition with a Memory Budget
237+
238+
In a subsequent session, provide the memory limit and the stats file to enable capacity-aware partitioning.
239+
240+
```python
241+
import onnxruntime as ort
242+
243+
opts = ort.SessionOptions()
244+
245+
# Format: "memory_limit_in_kb,stats_filename"
246+
# Set a 4 GB limit and use the stats from the profiling run
247+
opts.add_session_config_entry(
248+
"session.resource_cuda_partitioning_settings",
249+
"4194304,node_memory_stats.csv"
250+
)
251+
252+
session = ort.InferenceSession("model.onnx", opts,
253+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
254+
```
255+
256+
ONNX Runtime processes nodes in topological order, accumulating estimated memory. When the cumulative cost exceeds the budget, assignment to the CUDA EP halts immediately — remaining nodes are not considered even if they would individually fit within the budget. Those nodes are eligible for assignment by the subsequent EPs in the session's provider list.
257+
258+
Because assignment follows topological order, groups of nodes that you would prefer to offload (for example, MoE expert blocks) may appear at arbitrary positions in the graph. If you want specific node groups to have the lowest priority for device placement, combine the memory budget with layer annotations: annotate the nodes you want to offload to CPU explicitly, and let the capacity-aware partitioner handle the rest.
259+
260+
### Ad-Hoc Mode (No Stats File)
261+
262+
If you do not have pre-recorded statistics, you can specify only a memory limit. ONNX Runtime will estimate per-node cost from initializer sizes and static output shapes, applying a 1.5x safety multiplier.
263+
264+
This mode is less accurate than using pre-recorded stats but provides a quick way to constrain GPU memory without a profiling run.
265+
266+
```python
267+
# Memory limit only, no stats file (note the trailing comma)
268+
opts.add_session_config_entry(
269+
"session.resource_cuda_partitioning_settings",
270+
"4194304,"
271+
)
272+
```
273+
274+
### Setting Format Summary
275+
The value of `session.resource_cuda_partitioning_settings` is a comma-separated pair:
276+
277+
| Format | Meaning |
278+
|:------|:-------|
279+
| `<limit_kb>,<stats_file>` | Use both memory limit and pre-recorded stats |
280+
| `<limit_kb>,` | Memory limit only (ad-hoc estimation) |
281+
| `,<stats_file>` | Stats only (no explicit limit) |
282+
| `,` | Neither (EP attempts auto-detection) |
283+
284+
The stats file path follows the same resolution rules described above: relative paths are resolved against the model's directory, absolute paths are used as-is.
285+
286+
## Combining Both Features
287+
Layer annotations and capacity-aware partitioning can be used together. When both are configured:
288+
- Layer annotations provide the initial node-to-device mapping.
289+
- The capacity-aware partitioner enforces the memory budget, potentially overriding assignments that would exceed the GPU memory limit.
290+
291+
This combination gives you fine-grained control: use annotations to express logical model structure, and let the memory budget act as a safety net.
292+
293+
```python
294+
opts = ort.SessionOptions()
295+
296+
opts.add_session_config_entry(
297+
"session.layer_assignment_settings",
298+
"gpu(encoder, decoder); cpu(=postprocess)"
299+
)
300+
301+
opts.add_session_config_entry(
302+
"session.resource_cuda_partitioning_settings",
303+
"4194304,node_memory_stats.csv"
304+
)
305+
306+
session = ort.InferenceSession("model_annotated.onnx", opts,
307+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
308+
```

0 commit comments

Comments
 (0)