Buckets:
| <meta charset="utf-8" /><meta name="hf:doc:metadata" content="{"title":"Exporters","local":"exporters","sections":[{"title":"Installation","local":"installation","sections":[],"depth":2},{"title":"Export a model","local":"export-a-model","sections":[],"depth":2},{"title":"Run an export","local":"run-an-export","sections":[],"depth":2},{"title":"Dynamic shapes","local":"dynamic-shapes","sections":[],"depth":2},{"title":"Generative models","local":"generative-models","sections":[{"title":"How export_for_generation works","local":"how-exportforgeneration-works","sections":[],"depth":3},{"title":"Multi-token decode","local":"multi-token-decode","sections":[],"depth":3},{"title":"Static KV cache","local":"static-kv-cache","sections":[{"title":"Zero-copy in-place updates","local":"zero-copy-in-place-updates","sections":[],"depth":4}],"depth":3}],"depth":2},{"title":"ONNX Runtime fusions","local":"onnx-runtime-fusions","sections":[],"depth":2},{"title":"Quantization","local":"quantization","sections":[],"depth":2},{"title":"Limitations and workarounds","local":"limitations-and-workarounds","sections":[],"depth":2},{"title":"Next steps","local":"next-steps","sections":[],"depth":2}],"depth":1}"/> | |
| <link href="/docs/transformers/main/en/_app/immutable/entry/start.BJfF-MbH.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/D-_6EVXG.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/f7YVACrW.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/entry/app.Doo6SJy-.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/BHXybN3M.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/DOLBYqcr.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/DsnmJJEf.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/MtqDA42Q.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/nodes/0.CwEJf3gf.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/CkAoja1z.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/nodes/2.DB6fykOY.js" rel="modulepreload"> | |
| <link href="/docs/transformers/main/en/_app/immutable/chunks/i8vErmkY.js" rel="modulepreload"> | |
| <!--qdwh4p--><meta name="hf:doc:metadata" content="{"title":"Exporters","local":"exporters","sections":[{"title":"Installation","local":"installation","sections":[],"depth":2},{"title":"Export a model","local":"export-a-model","sections":[],"depth":2},{"title":"Run an export","local":"run-an-export","sections":[],"depth":2},{"title":"Dynamic shapes","local":"dynamic-shapes","sections":[],"depth":2},{"title":"Generative models","local":"generative-models","sections":[{"title":"How export_for_generation works","local":"how-exportforgeneration-works","sections":[],"depth":3},{"title":"Multi-token decode","local":"multi-token-decode","sections":[],"depth":3},{"title":"Static KV cache","local":"static-kv-cache","sections":[{"title":"Zero-copy in-place updates","local":"zero-copy-in-place-updates","sections":[],"depth":4}],"depth":3}],"depth":2},{"title":"ONNX Runtime fusions","local":"onnx-runtime-fusions","sections":[],"depth":2},{"title":"Quantization","local":"quantization","sections":[],"depth":2},{"title":"Limitations and workarounds","local":"limitations-and-workarounds","sections":[],"depth":2},{"title":"Next steps","local":"next-steps","sections":[],"depth":2}],"depth":1}"/><!----> | |
| <link href="/docs/transformers/main/en/_app/immutable/assets/0.tn0RQdqM.css" rel="modulepreload"> <!--[--><!--[0--><!--[--><!--[0--><!--[--><p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: inline-end; margin-inline-start: 10px; display: inline-flex; position: relative; z-index: 10;"><div dir="ltr" class="inline-flex rounded-md max-sm:rounded-sm"><button class="inline-flex items-center gap-1 h-7 max-sm:h-7 px-2 max-sm:px-1.5 text-sm font-medium text-gray-800 border border-r-0 rounded-l-md max-sm:rounded-l-sm border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-live="polite"><span class="inline-flex items-center justify-center rounded-md p-0.5 max-sm:p-0 hover:text-gray-800 dark:hover:text-gray-200"><svg class="sm:size-3.5 size-3" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----></span> <span dir="auto">Copy page</span></button> <button class="inline-flex items-center justify-center w-6 max-sm:w-5 h-7 max-sm:h-7 disabled:pointer-events-none text-sm text-gray-500 hover:text-gray-700 dark:hover:text-white rounded-r-md max-sm:rounded-r-sm border border-l transition border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-haspopup="menu" aria-expanded="false" aria-label="Open copy menu"><svg class="transition-transform text-gray-400 overflow-visible sm:size-3.5 size-3 rotate-0" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg><!----></button></div> <!--[-1--><!--]--></div><!----> <!--[0--><h1 class="relative group"><a id="exporters" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#exporters"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Exporters<!----></span></h1><!--]--><!----> <p>Export any <a href="/docs/transformers/pr_51549/en/main_classes/model#transformers.PreTrainedModel">PreTrainedModel</a> to ONNX, ExecuTorch, or a standalone PyTorch program, regardless of the target runtime.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!---->exporter = DynamoExporter() <span class="hljs-comment"># or OnnxExporter, ExecutorchExporter</span> | |
| config = DynamoConfig(dynamic=<span class="hljs-literal">True</span>) | |
| exported = exporter.export(model, inputs, config=config)<!----></pre></div><!----> <p>The exporters live inside Transformers instead of a downstream library, so architecture changes, | |
| new attention patterns, and custom cache types are supported at export time as soon as they land | |
| in the modeling code.</p> <blockquote class="warning"><p>The exporters are experimental. Many of the patches in this module work around specific upstream bugs (Torch, ONNX Script, ONNX Runtime, ExecuTorch) and will be removed as soon as the fix lands upstream. Until the API stabilizes, treat the patches as tied to the versions used in the test suite. Pin those versions in production tooling, and expect new patches to appear and old ones to disappear as upstream changes land.</p></blockquote> <table><thead><tr><th>Exporter</th><th>Program (<code>.program</code>)</th><th>Saved as</th><th>Runtime</th></tr></thead><tbody><tr><td><code>DynamoExporter</code></td><td><code>ExportedProgram</code></td><td><code>model.pt2</code></td><td>Any PyTorch runtime, AOT compilation</td></tr><tr><td><code>OnnxExporter</code></td><td><code>onnx_ir.Model</code></td><td><code>model.onnx</code></td><td>Any ONNX runtime (ORT, TensorRT, OpenVINO)</td></tr><tr><td><code>ExecutorchExporter</code></td><td><code>ExecutorchProgramManager</code></td><td><code>model.pte</code></td><td>Mobile and edge devices (ExecuTorch)</td></tr><tr><td><code>OpenVINOExporter</code></td><td><code>openvino.Model</code></td><td><code>openvino_model.xml</code> + <code>.bin</code></td><td>OpenVINO runtime (Intel CPU/GPU/NPU)</td></tr></tbody></table> <p>Every export returns an <code>ExportedModel</code>, whose <code>components</code> map names to <code>ExportedComponent</code>s. A | |
| component holds the backend’s program (<code>.program</code>) and the <code>ExportMetadata</code> recorded while tracing it | |
| (input and output names, precision, traced input shapes, export config). <code>~HfExporter.export</code> produces a single <code>"model"</code> component, so its program is directly <code>exported.program</code>. <code>~ExportedModel.save_pretrained</code> writes one | |
| file per component, an <code>export.json</code> manifest with each component’s file and metadata, and the model config.</p> <p><code>~ExportedModel.from_pretrained</code> loads it back, from a local directory or a Hub repo, with the same download kwargs | |
| as <a href="/docs/transformers/pr_51549/en/main_classes/model#transformers.PreTrainedModel.from_pretrained">from_pretrained()</a>. Pass <code>subfolder</code> for an export kept next to the model’s weights; only the | |
| export’s own files are downloaded. Dynamo, ONNX, and OpenVINO | |
| programs load as the type the export returned. A loaded ONNX graph leaves its weights in <code>model.onnx.data</code> until they | |
| are read. An ExecuTorch <code>.pte</code> loads as an <code>executorch.runtime.Program</code>, since the <code>ExecutorchProgramManager</code> can’t be rebuilt from the file.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> ExportedModel | |
| exported.program <span class="hljs-comment"># the backend's program</span> | |
| exported.save_pretrained(<span class="hljs-string">"exported-model"</span>) <span class="hljs-comment"># model.<suffix>, export.json, config.json</span> | |
| loaded = ExportedModel.from_pretrained(<span class="hljs-string">"exported-model"</span>, trust_remote_code=<span class="hljs-literal">True</span>) <span class="hljs-comment"># a Dynamo .pt2, see below</span><!----></pre></div><!----> <blockquote class="warning"><p>A Dynamo <code>.pt2</code> is a pickle, so loading one runs code from it. <code>~ExportedModel.from_pretrained</code> refuses it, from | |
| the Hub or a local directory, unless you pass <code>trust_remote_code=True</code>. Only pass it for an export you trust, as | |
| you would for a model with custom code. ONNX, OpenVINO and ExecuTorch programs load without it.</p></blockquote> <p>A directory holds one export, since <code>export.json</code> and <code>config.json</code> have fixed names. Keep exports to several | |
| formats in their own subfolders (<code>onnx/</code>, <code>openvino/</code>) and load them with <code>subfolder="onnx"</code>.</p> <p><code>AutoHfExporter</code> picks the right exporter from a config, and <code>AutoExportConfig</code> picks the | |
| right config class from a dict. Both follow the same auto-class pattern in Transformers, which | |
| is useful when the backend is selected at runtime instead of hardcoded at the call site.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> AutoExportConfig, AutoHfExporter | |
| export_config_dict = {<span class="hljs-string">"export_format"</span>: <span class="hljs-string">"onnx"</span>, <span class="hljs-string">"dynamic"</span>: <span class="hljs-literal">True</span>} | |
| config = AutoExportConfig.from_dict(export_config_dict) | |
| exporter = AutoHfExporter.from_config(config) | |
| exported = exporter.export(model, inputs, config=config)<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="installation" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#installation"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Installation<!----></span></h2><!--]--><!----> <p>Install the dependencies for the backend you plan to export to.</p> <blockquote class="tip"><p>The versions below are the ones the exporter test suite is pinned against. Newer or older | |
| releases often work, but the exporter patches target a specific API surface, so for production | |
| tooling pin these and expect <code>HfExporter</code> to log a warning when it detects drift.</p></blockquote> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">Dynamo</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ONNX</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ExecuTorch XNNPACK</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ExecuTorch MLX</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">OpenVINO</div><!--]--></div> <div class="language-select"><div><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-bash "><!---->pip install transformers <span class="hljs-string">"torch==2.12.0"</span><!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-bash "><!---->pip install transformers <span class="hljs-string">"torch==2.12.0"</span> <span class="hljs-string">"onnx==1.21.0"</span> <span class="hljs-string">"onnxscript==0.7.0"</span> onnxruntime<!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-bash "><!---->pip install transformers <span class="hljs-string">"torch==2.12.0"</span> <span class="hljs-string">"executorch==1.3.1"</span><!----></pre></div><!----></div><!----> <div hidden=""><p>Requires macOS 14 or later on Apple Silicon. MLX is included in the macOS ARM64 ExecuTorch | |
| nightly wheels; it is not a separate package or extra. The following nightly pair was validated | |
| with the MLX exporter tests. Install it from the standard ExecuTorch nightly registry:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-bash "><!---->pip install transformers | |
| pip install \ | |
| <span class="hljs-string">"executorch==1.6.0.dev20260924"</span> \ | |
| <span class="hljs-string">"torch==2.15.0.dev20260924"</span> \ | |
| --extra-index-url https://download.pytorch.org/whl/nightly/cpu<!----></pre></div><!----> <p>Install <code>torch</code> explicitly because nightly ExecuTorch wheels do not declare it as a dependency. | |
| For source builds, see the <a href="https://docs.pytorch.org/executorch/main/backends/mlx/mlx-overview.html" rel="nofollow">MLX installation guide</a>.</p><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-bash "><!---->pip install transformers <span class="hljs-string">"torch==2.12.0"</span> <span class="hljs-string">"openvino==2026.3.1"</span><!----></pre></div><!----></div><!----><!----></div><!----> <!--[1--><h2 class="relative group"><a id="export-a-model" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#export-a-model"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Export a model<!----></span></h2><!--]--><!----> <p>All exporters share the same interface. Create an exporter with a config, and call <a href="/docs/transformers/pr_51549/en/main_classes/exporters#transformers.exporters.HfExporter.export">export()</a>.</p> <p>Switch between runtimes by swapping the exporter class.</p> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">Dynamo</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ONNX</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ExecuTorch</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">OpenVINO</div><!--]--></div> <div class="language-select"><div><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> DynamoExporter, DynamoConfig | |
| model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| inputs = tokenizer(<span class="hljs-string">"Hello, world!"</span>, return_tensors=<span class="hljs-string">"pt"</span>) | |
| exporter = DynamoExporter() | |
| config = DynamoConfig(dynamic=<span class="hljs-literal">True</span>) | |
| exported = exporter.export(model, inputs, config=config) | |
| <span class="hljs-comment"># run the exported graph directly</span> | |
| outputs = exported(**inputs)<!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> OnnxExporter, OnnxConfig | |
| model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| inputs = tokenizer(<span class="hljs-string">"Hello, world!"</span>, return_tensors=<span class="hljs-string">"pt"</span>) | |
| exporter = OnnxExporter() | |
| config = OnnxConfig(dynamic=<span class="hljs-literal">True</span>) | |
| exported = exporter.export(model, inputs, config=config) | |
| <span class="hljs-comment"># save, then load and run on ONNX Runtime</span> | |
| exported.save_pretrained(<span class="hljs-string">"qwen3-onnx"</span>) | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> ExportedModel | |
| outputs = ExportedModel.from_pretrained(<span class="hljs-string">"qwen3-onnx"</span>)(**inputs)<!----></pre></div><!----></div><!----> <div hidden=""><p><a href="/docs/transformers/pr_51549/en/main_classes/exporters#transformers.exporters.ExecutorchConfig.backend">backend</a> selects the target: <code>xnnpack</code> (the default) for CPU, <code>mlx</code> for Apple Silicon GPU, or <code>cuda</code> for a CUDA-enabled GPU. Choose the corresponding <a href="#installation">installation option</a>. MLX execution requires the MLX delegate and its Metal libraries; | |
| requesting CUDA without a CUDA-enabled environment raises a <code>RuntimeError</code>.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> ExecutorchExporter, ExecutorchConfig | |
| model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| inputs = tokenizer(<span class="hljs-string">"Hello, world!"</span>, return_tensors=<span class="hljs-string">"pt"</span>) | |
| exporter = ExecutorchExporter() | |
| config = ExecutorchConfig(backend=<span class="hljs-string">"xnnpack"</span>, dynamic=<span class="hljs-literal">True</span>) <span class="hljs-comment"># Use "mlx" on Apple Silicon.</span> | |
| exported = exporter.export(model, inputs, config=config) | |
| <span class="hljs-comment"># save for on-device deployment</span> | |
| exported.save_pretrained(<span class="hljs-string">"qwen3-executorch"</span>) | |
| <span class="hljs-comment"># load and run on the ExecuTorch runtime</span> | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> ExportedModel | |
| outputs = ExportedModel.from_pretrained(<span class="hljs-string">"qwen3-executorch"</span>)(**inputs)<!----></pre></div><!----><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> OpenVINOExporter, OpenVINOConfig | |
| model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| inputs = tokenizer(<span class="hljs-string">"Hello, world!"</span>, return_tensors=<span class="hljs-string">"pt"</span>) | |
| exporter = OpenVINOExporter() | |
| config = OpenVINOConfig(dynamic=<span class="hljs-literal">True</span>) | |
| exported = exporter.export(model, inputs, config=config) | |
| exported.save_pretrained(<span class="hljs-string">"qwen3-openvino"</span>) | |
| <span class="hljs-comment"># run on CPU (or "xpu" for an Intel GPU)</span> | |
| outputs = exported.to(<span class="hljs-string">"cpu"</span>)(**inputs)<!----></pre></div><!----></div><!----><!----></div><!----> <!--[1--><h2 class="relative group"><a id="run-an-export" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#run-an-export"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Run an export<!----></span></h2><!--]--><!----> <p>An <code>ExportedModel</code> runs an export on its backend’s runtime (<code>torch.export</code>’s module, ONNX Runtime, OpenVINO, or the | |
| ExecuTorch runtime) and is called like the model it came from: same kwargs, same <a href="/docs/transformers/pr_51549/en/main_classes/output#transformers.utils.ModelOutput">ModelOutput</a> class. The | |
| compute runs in the backend, which is often faster than eager PyTorch (OpenVINO on CPU, ONNX Runtime on CUDA), and | |
| quantized exports run the same way. Inputs the export wasn’t traced with are dropped, so a processor’s whole output | |
| can be passed.</p> <p>A fresh export runs on first call (on the backend’s default device, or the one <code>~ExportedModel.to</code> picks), and <code>ExportedModel.from_pretrained</code> loads a saved one from a local directory or the Hub, ready to run.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> ExportedModel | |
| outputs = exported(**inputs) | |
| exported.save_pretrained(<span class="hljs-string">"qwen3-onnx"</span>) | |
| model = ExportedModel.from_pretrained(<span class="hljs-string">"qwen3-onnx"</span>, device=<span class="hljs-string">"cuda"</span>) | |
| logits = model(**inputs).logits<!----></pre></div><!----> <p><code>device</code> picks where it runs: an ONNX Runtime provider (<code>"cpu"</code>, <code>"cuda"</code>), an OpenVINO device (<code>"cpu"</code>, <code>"xpu"</code> for an | |
| Intel GPU, or <code>AUTO</code> by default), or where a <code>torch.export</code> module is moved. An ExecuTorch program runs where it was | |
| lowered for. Exports with several components (generation) don’t run yet.</p> <!--[1--><h2 class="relative group"><a id="dynamic-shapes" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#dynamic-shapes"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Dynamic shapes<!----></span></h2><!--]--><!----> <p>Passing <code>dynamic=True</code> marks every tensor | |
| dimension as dynamic so the exported graph accepts inputs of any size at runtime without | |
| retracing.</p> <p>For fine-grained control over which dimensions are dynamic, pass explicit <code>dynamic_shapes</code> instead, which is forwarded directly to <a href="https://pytorch.org/docs/stable/export.html" rel="nofollow">torch.export.export</a>.</p> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">Dynamo</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ONNX</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ExecuTorch</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">OpenVINO</div><!--]--></div> <div class="language-select"><div><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> DynamoExporter, DynamoConfig | |
| model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| inputs = tokenizer([<span class="hljs-string">"Hello, world!"</span>, <span class="hljs-string">"Hi"</span>], padding=<span class="hljs-literal">True</span>, return_tensors=<span class="hljs-string">"pt"</span>) | |
| batch = torch.export.Dim(<span class="hljs-string">"batch"</span>, <span class="hljs-built_in">min</span>=<span class="hljs-number">1</span>, <span class="hljs-built_in">max</span>=<span class="hljs-number">32</span>) | |
| seq = torch.export.Dim(<span class="hljs-string">"seq"</span>, <span class="hljs-built_in">min</span>=<span class="hljs-number">1</span>, <span class="hljs-built_in">max</span>=<span class="hljs-number">2048</span>) | |
| exporter = DynamoExporter() | |
| config = DynamoConfig( | |
| dynamic_shapes={<span class="hljs-string">"input_ids"</span>: {<span class="hljs-number">0</span>: batch, <span class="hljs-number">1</span>: seq}, <span class="hljs-string">"attention_mask"</span>: {<span class="hljs-number">0</span>: batch, <span class="hljs-number">1</span>: seq}}, | |
| <span class="hljs-comment"># Emit data-dependent shape guards as runtime asserts instead of failing the export when a</span> | |
| <span class="hljs-comment"># guard wouldn't hold across the explicit symbolic range. Most LLMs need this under fine-grained</span> | |
| <span class="hljs-comment"># ``Dim(min=, max=)`` bounds. Not needed with ``dynamic=True`` / ``Dim.AUTO``, where torch.export</span> | |
| <span class="hljs-comment"># infers shape relations instead of verifying them against user-stated bounds.</span> | |
| prefer_deferred_runtime_asserts_over_guards=<span class="hljs-literal">True</span>, | |
| ) | |
| exported = exporter.export(model, inputs, config=config)<!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> OnnxExporter, OnnxConfig | |
| model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| inputs = tokenizer([<span class="hljs-string">"Hello, world!"</span>, <span class="hljs-string">"Hi"</span>], padding=<span class="hljs-literal">True</span>, return_tensors=<span class="hljs-string">"pt"</span>) | |
| batch = torch.export.Dim(<span class="hljs-string">"batch"</span>, <span class="hljs-built_in">min</span>=<span class="hljs-number">1</span>, <span class="hljs-built_in">max</span>=<span class="hljs-number">32</span>) | |
| seq = torch.export.Dim(<span class="hljs-string">"seq"</span>, <span class="hljs-built_in">min</span>=<span class="hljs-number">1</span>, <span class="hljs-built_in">max</span>=<span class="hljs-number">2048</span>) | |
| exporter = OnnxExporter() | |
| config = OnnxConfig( | |
| dynamic_shapes={<span class="hljs-string">"input_ids"</span>: {<span class="hljs-number">0</span>: batch, <span class="hljs-number">1</span>: seq}, <span class="hljs-string">"attention_mask"</span>: {<span class="hljs-number">0</span>: batch, <span class="hljs-number">1</span>: seq}}, | |
| <span class="hljs-comment"># Emit data-dependent shape guards as runtime asserts instead of failing the export when a</span> | |
| <span class="hljs-comment"># guard wouldn't hold across the explicit symbolic range. Most LLMs need this under fine-grained</span> | |
| <span class="hljs-comment"># ``Dim(min=, max=)`` bounds. Not needed with ``dynamic=True`` / ``Dim.AUTO``, where torch.export</span> | |
| <span class="hljs-comment"># infers shape relations instead of verifying them against user-stated bounds.</span> | |
| prefer_deferred_runtime_asserts_over_guards=<span class="hljs-literal">True</span>, | |
| ) | |
| exported = exporter.export(model, inputs, config=config)<!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> ExecutorchExporter, ExecutorchConfig | |
| model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| inputs = tokenizer([<span class="hljs-string">"Hello, world!"</span>, <span class="hljs-string">"Hi"</span>], padding=<span class="hljs-literal">True</span>, return_tensors=<span class="hljs-string">"pt"</span>) | |
| batch = torch.export.Dim(<span class="hljs-string">"batch"</span>, <span class="hljs-built_in">min</span>=<span class="hljs-number">1</span>, <span class="hljs-built_in">max</span>=<span class="hljs-number">32</span>) | |
| seq = torch.export.Dim(<span class="hljs-string">"seq"</span>, <span class="hljs-built_in">min</span>=<span class="hljs-number">1</span>, <span class="hljs-built_in">max</span>=<span class="hljs-number">2048</span>) | |
| exporter = ExecutorchExporter() | |
| config = ExecutorchConfig( | |
| backend=<span class="hljs-string">"xnnpack"</span>, <span class="hljs-comment"># Use "mlx" on Apple Silicon.</span> | |
| dynamic_shapes={<span class="hljs-string">"input_ids"</span>: {<span class="hljs-number">0</span>: batch, <span class="hljs-number">1</span>: seq}, <span class="hljs-string">"attention_mask"</span>: {<span class="hljs-number">0</span>: batch, <span class="hljs-number">1</span>: seq}}, | |
| <span class="hljs-comment"># Emit data-dependent shape guards as runtime asserts instead of failing the export when a</span> | |
| <span class="hljs-comment"># guard wouldn't hold across the explicit symbolic range. Most LLMs need this under fine-grained</span> | |
| <span class="hljs-comment"># ``Dim(min=, max=)`` bounds. Not needed with ``dynamic=True`` / ``Dim.AUTO``, where torch.export</span> | |
| <span class="hljs-comment"># infers shape relations instead of verifying them against user-stated bounds.</span> | |
| prefer_deferred_runtime_asserts_over_guards=<span class="hljs-literal">True</span>, | |
| ) | |
| exported = exporter.export(model, inputs, config=config)<!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForCausalLM, AutoTokenizer | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> OpenVINOExporter, OpenVINOConfig | |
| model = AutoModelForCausalLM.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| tokenizer = AutoTokenizer.from_pretrained(<span class="hljs-string">"Qwen/Qwen3-0.6B"</span>) | |
| inputs = tokenizer([<span class="hljs-string">"Hello, world!"</span>, <span class="hljs-string">"Hi"</span>], padding=<span class="hljs-literal">True</span>, return_tensors=<span class="hljs-string">"pt"</span>) | |
| batch = torch.export.Dim(<span class="hljs-string">"batch"</span>, <span class="hljs-built_in">min</span>=<span class="hljs-number">1</span>, <span class="hljs-built_in">max</span>=<span class="hljs-number">32</span>) | |
| seq = torch.export.Dim(<span class="hljs-string">"seq"</span>, <span class="hljs-built_in">min</span>=<span class="hljs-number">1</span>, <span class="hljs-built_in">max</span>=<span class="hljs-number">2048</span>) | |
| exporter = OpenVINOExporter() | |
| config = OpenVINOConfig( | |
| dynamic_shapes={<span class="hljs-string">"input_ids"</span>: {<span class="hljs-number">0</span>: batch, <span class="hljs-number">1</span>: seq}, <span class="hljs-string">"attention_mask"</span>: {<span class="hljs-number">0</span>: batch, <span class="hljs-number">1</span>: seq}}, | |
| <span class="hljs-comment"># Emit data-dependent shape guards as runtime asserts instead of failing the export when a</span> | |
| <span class="hljs-comment"># guard wouldn't hold across the explicit symbolic range — most LLMs need this under fine-grained</span> | |
| <span class="hljs-comment"># ``Dim(min=, max=)`` bounds. Not needed with ``dynamic=True`` / ``Dim.AUTO``, where torch.export</span> | |
| <span class="hljs-comment"># infers shape relations instead of verifying them against user-stated bounds.</span> | |
| prefer_deferred_runtime_asserts_over_guards=<span class="hljs-literal">True</span>, | |
| ) | |
| exported = exporter.export(model, inputs, config=config)<!----></pre></div><!----></div><!----><!----></div><!----> <!--[1--><h2 class="relative group"><a id="generative-models" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#generative-models"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Generative models<!----></span></h2><!--]--><!----> <p>For autoregressive generation, the model’s <code>forward</code> has different shapes at the prefill step | |
| (full prompt, no KV cache) versus the decode step (single token, populated KV cache). Exporters | |
| expose <code>~HfExporter.export_for_generation</code>, which splits both stages and exports each.</p> <p>For multi-modal generative models, the prefill additionally splits into an image or audio | |
| encoder, the language model, and <code>lm_head</code>. Encoder and language-model discovery uses <a href="/docs/transformers/pr_51549/en/main_classes/model#transformers.PreTrainedModel.get_encoder">get_encoder()</a> (<code>modality="image"</code> or <code>"audio"</code>) and <a href="/docs/transformers/pr_51549/en/main_classes/model#transformers.PreTrainedModel.get_decoder">get_decoder()</a> accessors, so any new architecture using these | |
| work out of the box.</p> <p>A projector component appears only when the model exposes one | |
| under an attribute name (<code>multi_modal_projector</code>, <code>connector</code>, <code>embed_vision</code>, <code>embed_audio</code>). Qwen2-VL below folds its projector into the vision tower, so its component dict | |
| has no separate <code>multi_modal_projector</code> key. New architectures must align their projector | |
| attribute to one of these names instead of growing the list.</p> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">Dynamo</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ONNX</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ExecuTorch</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">OpenVINO</div><!--]--></div> <div class="language-select"><div><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForImageTextToText, AutoProcessor | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> DynamoExporter, DynamoConfig | |
| model = AutoModelForImageTextToText.from_pretrained(<span class="hljs-string">"Qwen/Qwen2-VL-2B-Instruct"</span>) | |
| processor = AutoProcessor.from_pretrained(<span class="hljs-string">"Qwen/Qwen2-VL-2B-Instruct"</span>) | |
| messages = [{<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: [{<span class="hljs-string">"type"</span>: <span class="hljs-string">"image"</span>, <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"</span>}, {<span class="hljs-string">"type"</span>: <span class="hljs-string">"text"</span>, <span class="hljs-string">"text"</span>: <span class="hljs-string">"Describe this image."</span>}]}] | |
| text = processor.apply_chat_template(messages, add_generation_prompt=<span class="hljs-literal">True</span>, tokenize=<span class="hljs-literal">False</span>) | |
| inputs = processor(text=text, images=messages[<span class="hljs-number">0</span>][<span class="hljs-string">"content"</span>][<span class="hljs-number">0</span>][<span class="hljs-string">"url"</span>], return_tensors=<span class="hljs-string">"pt"</span>).to(model.device) | |
| exporter = DynamoExporter() | |
| config = DynamoConfig(dynamic=<span class="hljs-literal">True</span>) | |
| exported = exporter.export_for_generation(model, inputs, config=config) | |
| <span class="hljs-comment"># exported: ExportedModel with "image_encoder", "language_model", "lm_head" and "decode",</span> | |
| <span class="hljs-comment"># each an ExportedComponent whose `.program` is an ExportedProgram</span><!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForImageTextToText, AutoProcessor | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> OnnxExporter, OnnxConfig | |
| model = AutoModelForImageTextToText.from_pretrained(<span class="hljs-string">"Qwen/Qwen2-VL-2B-Instruct"</span>) | |
| processor = AutoProcessor.from_pretrained(<span class="hljs-string">"Qwen/Qwen2-VL-2B-Instruct"</span>) | |
| messages = [{<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: [{<span class="hljs-string">"type"</span>: <span class="hljs-string">"image"</span>, <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"</span>}, {<span class="hljs-string">"type"</span>: <span class="hljs-string">"text"</span>, <span class="hljs-string">"text"</span>: <span class="hljs-string">"Describe this image."</span>}]}] | |
| text = processor.apply_chat_template(messages, add_generation_prompt=<span class="hljs-literal">True</span>, tokenize=<span class="hljs-literal">False</span>) | |
| inputs = processor(text=text, images=messages[<span class="hljs-number">0</span>][<span class="hljs-string">"content"</span>][<span class="hljs-number">0</span>][<span class="hljs-string">"url"</span>], return_tensors=<span class="hljs-string">"pt"</span>).to(model.device) | |
| exporter = OnnxExporter() | |
| config = OnnxConfig(dynamic=<span class="hljs-literal">True</span>) | |
| exported = exporter.export_for_generation(model, inputs, config=config) | |
| <span class="hljs-comment"># exported: ExportedModel with "image_encoder", "language_model", "lm_head" and "decode",</span> | |
| <span class="hljs-comment"># each an ExportedComponent whose `.program` is an onnx_ir.Model</span><!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForImageTextToText, AutoProcessor | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> ExecutorchExporter, ExecutorchConfig | |
| model = AutoModelForImageTextToText.from_pretrained(<span class="hljs-string">"Qwen/Qwen2-VL-2B-Instruct"</span>) | |
| processor = AutoProcessor.from_pretrained(<span class="hljs-string">"Qwen/Qwen2-VL-2B-Instruct"</span>) | |
| messages = [{<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: [{<span class="hljs-string">"type"</span>: <span class="hljs-string">"image"</span>, <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"</span>}, {<span class="hljs-string">"type"</span>: <span class="hljs-string">"text"</span>, <span class="hljs-string">"text"</span>: <span class="hljs-string">"Describe this image."</span>}]}] | |
| text = processor.apply_chat_template(messages, add_generation_prompt=<span class="hljs-literal">True</span>, tokenize=<span class="hljs-literal">False</span>) | |
| inputs = processor(text=text, images=messages[<span class="hljs-number">0</span>][<span class="hljs-string">"content"</span>][<span class="hljs-number">0</span>][<span class="hljs-string">"url"</span>], return_tensors=<span class="hljs-string">"pt"</span>).to(model.device) | |
| exporter = ExecutorchExporter() | |
| config = ExecutorchConfig(backend=<span class="hljs-string">"xnnpack"</span>, dynamic=<span class="hljs-literal">True</span>) <span class="hljs-comment"># Use "mlx" on Apple Silicon.</span> | |
| exported = exporter.export_for_generation(model, inputs, config=config) | |
| <span class="hljs-comment"># exported: ExportedModel with "image_encoder", "language_model", "lm_head" and "decode",</span> | |
| <span class="hljs-comment"># each an ExportedComponent whose `.program` is an ExecutorchProgramManager</span><!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoModelForImageTextToText, AutoProcessor | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> OpenVINOExporter, OpenVINOConfig | |
| model = AutoModelForImageTextToText.from_pretrained(<span class="hljs-string">"Qwen/Qwen2-VL-2B-Instruct"</span>) | |
| processor = AutoProcessor.from_pretrained(<span class="hljs-string">"Qwen/Qwen2-VL-2B-Instruct"</span>) | |
| messages = [{<span class="hljs-string">"role"</span>: <span class="hljs-string">"user"</span>, <span class="hljs-string">"content"</span>: [{<span class="hljs-string">"type"</span>: <span class="hljs-string">"image"</span>, <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"</span>}, {<span class="hljs-string">"type"</span>: <span class="hljs-string">"text"</span>, <span class="hljs-string">"text"</span>: <span class="hljs-string">"Describe this image."</span>}]}] | |
| text = processor.apply_chat_template(messages, add_generation_prompt=<span class="hljs-literal">True</span>, tokenize=<span class="hljs-literal">False</span>) | |
| inputs = processor(text=text, images=messages[<span class="hljs-number">0</span>][<span class="hljs-string">"content"</span>][<span class="hljs-number">0</span>][<span class="hljs-string">"url"</span>], return_tensors=<span class="hljs-string">"pt"</span>).to(model.device) | |
| exporter = OpenVINOExporter() | |
| config = OpenVINOConfig(dynamic=<span class="hljs-literal">True</span>) | |
| exported = exporter.export_for_generation(model, inputs, config=config) | |
| <span class="hljs-comment"># exported: ExportedModel with "image_encoder", "language_model", "lm_head" and "decode",</span> | |
| <span class="hljs-comment"># each an ExportedComponent whose `.program` is an openvino.Model</span><!----></pre></div><!----> <p><code>exported.save_pretrained(directory)</code> writes one file per component (<code>decode.onnx</code>, <code>lm_head.onnx</code>, …), | |
| the manifest, the model config, and the generation config passed to <code>export_for_generation</code>.</p><!----></div><!----><!----></div><!----> <blockquote class="warning"><p>The exported components are independent graphs, not a ready-to-run inference pipeline. The | |
| caller is responsible for running each encoder, projecting embeddings, and orchestrating the | |
| generation loop.</p></blockquote> <!--[2--><h3 class="relative group"><a id="how-exportforgeneration-works" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#how-exportforgeneration-works"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->How export_for_generation works<!----></span></h3><!--]--><!----> <p><a href="/docs/transformers/pr_51549/en/main_classes/exporters#transformers.exporters.utils.decompose_for_generation">decompose_for_generation()</a> runs <code>model.generate(**inputs, max_new_tokens=2)</code> once and hooks <code>model.forward</code> to capture the real prefill and decode kwargs (and the | |
| per-submodule kwargs via hooks on each encoder/projector/language model if the model is | |
| multi-modal). That’s why it works for any architecture, including decoder-only, SSM, | |
| encoder-decoder, and multi-modal models, without per-model glue. <code>export_for_generation</code> is a | |
| one-liner over it.</p> <p>The capture runs the model eagerly on <code>inputs</code>, so pass small but representative values, such as a | |
| short prompt, a single small image, or a few audio frames. The exported program isn’t tied to | |
| those sizes (dynamic shapes still flow through), but smaller capture inputs make <code>decompose_for_generation</code> cheaper and keep symbolic-shape inference tractable.</p> <p>Call <code>decompose_for_generation</code> directly to act between decomposing and exporting, such as | |
| running an eager forward for verification, swapping a submodule’s inputs, or skipping a stage.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers.exporters.utils <span class="hljs-keyword">import</span> decompose_for_generation | |
| components = decompose_for_generation(model, inputs) | |
| <span class="hljs-comment"># {"image_encoder": (submodel, fwd_kwargs), "language_model": (...), ..., "decode": (...)}</span> | |
| exported = {} | |
| <span class="hljs-keyword">for</span> name, (submodel, subinputs) <span class="hljs-keyword">in</span> components.items(): | |
| eager_outputs = submodel(**subinputs) <span class="hljs-comment"># sanity-check the eager forward before exporting</span> | |
| exported[name] = exporter.export(submodel, subinputs, config=config)<!----></pre></div><!----> <!--[2--><h3 class="relative group"><a id="multi-token-decode" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#multi-token-decode"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Multi-token decode<!----></span></h3><!--]--><!----> <p>By default the <code>decode</code> component is a <strong>single-token</strong> step — one query token against the KV cache — | |
| so <code>torch.export</code> specializes its query-sequence axis to 1. Pass <code>multi_token_decode=True</code> to capture <code>decode</code> as a <strong>multi-token</strong> decode instead: <a href="/docs/transformers/pr_51549/en/main_classes/exporters#transformers.exporters.utils.decompose_for_generation">decompose_for_generation()</a> merges two | |
| consecutive decode steps (it captures with <code>max_new_tokens=3</code>) into one forward, so that axis stays | |
| symbolic. A single graph then serves every query length — one token (ordinary decoding), many tokens | |
| at once (continuation-from-past, e.g. accepting a chunk of speculative tokens), and a plain prefill | |
| when the cache is empty.</p> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">Dynamo</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ONNX</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ExecuTorch</div><!--]--></div> <div class="language-select"><div><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> DynamoExporter, DynamoConfig | |
| exporter = DynamoExporter() | |
| config = DynamoConfig(dynamic=<span class="hljs-literal">True</span>) | |
| exported = exporter.export_for_generation(model, inputs, config=config, multi_token_decode=<span class="hljs-literal">True</span>) | |
| <span class="hljs-comment"># exported.components["decode"] now accepts a variable number of query tokens</span><!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> OnnxExporter, OnnxConfig | |
| exporter = OnnxExporter() | |
| config = OnnxConfig(dynamic=<span class="hljs-literal">True</span>) | |
| exported = exporter.export_for_generation(model, inputs, config=config, multi_token_decode=<span class="hljs-literal">True</span>) | |
| <span class="hljs-comment"># exported.components["decode"] now accepts a variable number of query tokens</span><!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> ExecutorchExporter, ExecutorchConfig | |
| exporter = ExecutorchExporter() | |
| config = ExecutorchConfig(backend=<span class="hljs-string">"xnnpack"</span>, dynamic=<span class="hljs-literal">True</span>) <span class="hljs-comment"># Use "mlx" on Apple Silicon.</span> | |
| exported = exporter.export_for_generation(model, inputs, config=config, multi_token_decode=<span class="hljs-literal">True</span>) | |
| <span class="hljs-comment"># exported.components["decode"] now accepts a variable number of query tokens</span><!----></pre></div><!----></div><!----><!----></div><!----> <p>The query axis only stays symbolic under a dynamic-shape export (<code>dynamic=True</code>); a static export | |
| freezes it at the captured length, giving a fixed multi-token graph. It composes with the static KV | |
| cache below — the merged decode writes each step’s tokens into the fixed-size cache in place, and the | |
| cache handles where they land internally.</p> <!--[2--><h3 class="relative group"><a id="static-kv-cache" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#static-kv-cache"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Static KV cache<!----></span></h3><!--]--><!----> <blockquote class="note"><p>The ExecuTorch examples in this section, including zero-copy updates and the decode loop, | |
| are <strong>XNNPACK-only</strong>. The MLX exporter rejects <code>StaticCache</code>; use <code>DynamicCache</code> with MLX.</p></blockquote> <p><code>generate()</code> grows a <code>DynamicCache</code> by default, reallocating as the sequence extends — a moving target | |
| for an exported graph. A <strong>static</strong> cache is a fixed-size buffer, allocated once and written in place at | |
| the current position each step. Combined with a <a href="#multi-token-decode">multi-token decode</a> it collapses | |
| generation into a single exported graph: the <code>decode</code> graph takes a fixed-size cache and a <em>variable</em> number of query tokens, so one graph serves both the prompt (empty cache → prefill) and each generated | |
| token (populated cache → decode). Export it by forwarding a <code>GenerationConfig</code> with <code>cache_implementation="static"</code> (and a <code>max_cache_len</code>) alongside <code>multi_token_decode=True</code>:</p> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">Dynamo</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ONNX</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ExecuTorch XNNPACK</div><!--]--></div> <div class="language-select"><div><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> GenerationConfig | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> DynamoExporter, DynamoConfig | |
| exporter = DynamoExporter() | |
| gen_config = GenerationConfig(cache_implementation=<span class="hljs-string">"static"</span>, max_cache_len=<span class="hljs-number">2048</span>) | |
| exported = exporter.export_for_generation( | |
| model, inputs, config=DynamoConfig(dynamic=<span class="hljs-literal">True</span>), generation_config=gen_config, multi_token_decode=<span class="hljs-literal">True</span> | |
| ) | |
| exported.save_pretrained(<span class="hljs-string">"qwen3-static"</span>)<!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> GenerationConfig | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> OnnxExporter, OnnxConfig | |
| exporter = OnnxExporter() | |
| gen_config = GenerationConfig(cache_implementation=<span class="hljs-string">"static"</span>, max_cache_len=<span class="hljs-number">2048</span>) | |
| exported = exporter.export_for_generation( | |
| model, inputs, config=OnnxConfig(dynamic=<span class="hljs-literal">True</span>), generation_config=gen_config, multi_token_decode=<span class="hljs-literal">True</span> | |
| )<!----></pre></div><!----></div><!----> <div hidden=""><div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> GenerationConfig | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> ExecutorchExporter, ExecutorchConfig | |
| exporter = ExecutorchExporter() | |
| gen_config = GenerationConfig(cache_implementation=<span class="hljs-string">"static"</span>, max_cache_len=<span class="hljs-number">2048</span>) | |
| exported = exporter.export_for_generation( | |
| model, inputs, config=ExecutorchConfig(backend=<span class="hljs-string">"xnnpack"</span>, dynamic=<span class="hljs-literal">True</span>), generation_config=gen_config, multi_token_decode=<span class="hljs-literal">True</span> | |
| )<!----></pre></div><!----></div><!----><!----></div><!----> <p>The <code>decode</code> graph now has two symbolic axes — the query length (how many tokens you feed) and the cache | |
| length (<code>max_cache_len</code>, resizable at load time). <code>dynamic=True</code> marks these (and every other axis) <code>Dim.AUTO</code>, so the exported graph accepts any prompt length and cache size at load time.</p> <!--[3--><h4 class="relative group"><a id="zero-copy-in-place-updates" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#zero-copy-in-place-updates"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Zero-copy in-place updates<!----></span></h4><!--]--><!----> <p>The static cache is passed in and mutated in place, so one buffer carries state across decode steps | |
| with no host copies — as long as the runtime binds the caller’s buffers rather than copying through its | |
| own arena. What that takes is the only per-backend part left:</p> <ul><li><p><strong>Dynamo</strong> — the exported program models the cache write as a <code>USER_INPUT_MUTATION</code>, so calling <code>exported.runners["decode"](...)</code> updates the cache tensors you pass in directly. Reuse the same | |
| tensors each step; nothing to configure.</p></li> <li><p><strong>ONNX Runtime</strong> — the decode graph exposes the cache as matched <code>input.<name></code> / <code>output.<name></code> pairs. ORT’s <code>CudaSession.set_buffer_sharing</code> (<code>onnxruntime.transformers.io_binding_helper</code>) binds | |
| each pair to one device buffer, so the cache is read and updated in place across the loop with no host | |
| round-trips.</p></li> <li><p><strong>ExecuTorch (XNNPACK)</strong> — turn off the memory-planning allocations on <code>ExecutorchConfig</code> so the in-place | |
| write can land in the caller’s own tensor (see the reference for what each flag does):</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!---->config = ExecutorchConfig( | |
| backend=<span class="hljs-string">"xnnpack"</span>, | |
| dynamic=<span class="hljs-literal">True</span>, | |
| alloc_graph_input=<span class="hljs-literal">False</span>, | |
| alloc_graph_output=<span class="hljs-literal">False</span>, | |
| alloc_mutable_buffers=<span class="hljs-literal">False</span>, | |
| )<!----></pre></div><!----> <blockquote class="note"><p>The zero-copy in-place write also needs the caller to bind output buffers at runtime via <code>Method::set_output_data_ptr</code> — <strong>not surfaced by the Python runtime</strong> (<code>executorch.runtime.Method</code> exposes only <code>execute</code>/<code>set_inputs</code>/<code>get_outputs</code>). The flags above set it up, but the in-place | |
| write is a <strong>C++-only</strong> path (see the ExecuTorch decode-loop example below). From Python, read the | |
| updated cache back from the method outputs each step.</p></blockquote></li></ul> <details><summary>Decode-loop inference examples</summary> <p>The loop is the same shape on every backend — it’s the <em>same</em> graph throughout. Start from an empty | |
| fixed-size cache, feed the whole prompt once (empty cache → prefill), then one token at a time | |
| (populated cache → decode). Each call passes <code>input_ids</code>, a causal <code>attention_mask</code>, and <code>position_ids</code> (advanced by the number of new tokens each step), plus the cache, and gets back logits for every query | |
| position. Where each token lands in the cache is tracked internally by the static cache, so there’s | |
| nothing extra to thread through the call. How the cache is set up differs per runtime (a <code>StaticCache</code> object for Dynamo, raw device buffers for ONNX Runtime, caller arrays in C++ for ExecuTorch), so each | |
| tab builds its own below. The Dynamo and ONNX Runtime tabs update the cache in place; ExecuTorch’s | |
| in-place path is C++ (its Python runtime can’t, as noted above).</p> <div class="flex space-x-2 items-center my-1.5 mr-8 h-7 !pl-0 -mx-3 md:mx-0"><!--[--><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd border-gray-800 bg-black dark:bg-gray-700 text-white">Dynamo</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ONNX Runtime</div><div class="flex items-center border rounded-lg px-1.5 py-1 leading-none select-none text-smd text-gray-500 cursor-pointer opacity-90 hover:text-gray-700 dark:hover:text-gray-200 hover:shadow-sm">ExecuTorch XNNPACK</div><!--]--></div> <div class="language-select"><div><p>torch.export records the static-cache write as a <code>USER_INPUT_MUTATION</code>, so the <code>decode</code> runner updates the <code>StaticCache</code> you pass in <strong>directly</strong> — one cache carries state across the whole loop with nothing to bind or | |
| thread back out. The cache has to be <strong>initialized up front</strong> (torch.export bakes the allocated K/V into the | |
| input spec, so a lazy blank cache won’t match) — but the saved program carries its own <code>example_inputs</code>, so reuse | |
| that already-initialized <code>StaticCache</code> template, reset to empty:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> copy | |
| <span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">from</span> transformers.exporters <span class="hljs-keyword">import</span> ExportedModel | |
| exported = ExportedModel.from_pretrained(<span class="hljs-string">"qwen3-static"</span>, device=<span class="hljs-string">"cuda"</span>) | |
| decode = exported.runners[<span class="hljs-string">"decode"</span>] | |
| <span class="hljs-comment"># the program carries an initialized StaticCache template — reuse it (reset to empty)</span> | |
| _, example_kwargs = exported.components[<span class="hljs-string">"decode"</span>].program.example_inputs | |
| cache = copy.deepcopy(example_kwargs[<span class="hljs-string">"cache"</span>]) | |
| cache.reset() | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">causal_mask</span>(<span class="hljs-params">positions, cache_len</span>): <span class="hljs-comment"># [1, 1, len(positions), cache_len]</span> | |
| <span class="hljs-keyword">return</span> (torch.arange(cache_len, device=<span class="hljs-string">"cuda"</span>)[<span class="hljs-literal">None</span>, :] <= positions[:, <span class="hljs-literal">None</span>])[<span class="hljs-literal">None</span>, <span class="hljs-literal">None</span>] | |
| <span class="hljs-comment"># prefill: the whole prompt in one call</span> | |
| positions = torch.arange(prompt_len, device=<span class="hljs-string">"cuda"</span>) | |
| logits = decode(input_ids=prompt_ids, attention_mask=causal_mask(positions, max_cache_len), | |
| position_ids=positions[<span class="hljs-literal">None</span>], cache=cache).logits | |
| next_token = logits[:, -<span class="hljs-number">1</span>:].argmax(-<span class="hljs-number">1</span>) | |
| <span class="hljs-comment"># decode: query=1 buffers reused in place</span> | |
| input_ids = torch.empty((<span class="hljs-number">1</span>, <span class="hljs-number">1</span>), dtype=torch.long, device=<span class="hljs-string">"cuda"</span>) | |
| position_ids = torch.empty((<span class="hljs-number">1</span>, <span class="hljs-number">1</span>), dtype=torch.long, device=<span class="hljs-string">"cuda"</span>) | |
| attention_mask = torch.empty((<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, max_cache_len), dtype=torch.<span class="hljs-built_in">bool</span>, device=<span class="hljs-string">"cuda"</span>) | |
| slots = torch.arange(max_cache_len, device=<span class="hljs-string">"cuda"</span>) | |
| <span class="hljs-keyword">for</span> position <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(prompt_len, max_cache_len): | |
| input_ids.copy_(next_token) | |
| position_ids.fill_(position) | |
| attention_mask[<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>].copy_(slots <= position) | |
| logits = decode(input_ids=input_ids, attention_mask=attention_mask, | |
| position_ids=position_ids, cache=cache).logits | |
| next_token = logits[:, -<span class="hljs-number">1</span>:].argmax(-<span class="hljs-number">1</span>)<!----></pre></div><!----><!----></div><!----> <div hidden=""><p>ONNX Runtime runs the graph as-is; the in-place cache update is done with ORT’s <code>CudaSession</code> (<code>onnxruntime.transformers.io_binding_helper</code>), a thin wrapper over ORT io-binding. <code>set_buffer_sharing</code> binds a cache <code>input.<name></code> and its matching <code>output.<name></code> to <strong>one</strong> device buffer, so the mutated | |
| K/V/counter are written straight back into the input; <code>allocate_buffers</code> allocates the remaining | |
| (non-shared) outputs — here just <code>logits</code>; and <code>infer(feed_dict)</code> binds your CUDA tensors by pointer | |
| and runs. The cache buffers come straight from the graph’s own input metadata (<code>get_inputs()</code> shape and | |
| type), so no model config is needed — the one symbolic axis (cache length) becomes <code>max_cache_len</code>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-keyword">import</span> torch | |
| <span class="hljs-keyword">import</span> onnxruntime <span class="hljs-keyword">as</span> ort | |
| <span class="hljs-keyword">from</span> onnxruntime.transformers.io_binding_helper <span class="hljs-keyword">import</span> CudaSession, TypeHelper | |
| <span class="hljs-keyword">def</span> <span class="hljs-title function_">causal_mask</span>(<span class="hljs-params">positions, cache_len</span>): | |
| <span class="hljs-keyword">return</span> (torch.arange(cache_len, device=<span class="hljs-string">"cuda"</span>)[<span class="hljs-literal">None</span>, :] <= positions[:, <span class="hljs-literal">None</span>])[<span class="hljs-literal">None</span>, <span class="hljs-literal">None</span>] | |
| session = ort.InferenceSession(<span class="hljs-string">"decode.onnx"</span>, providers=[<span class="hljs-string">"CUDAExecutionProvider"</span>]) | |
| cuda = CudaSession(session, torch.device(<span class="hljs-string">"cuda"</span>)) | |
| <span class="hljs-comment"># fresh device cache buffers built from each cache input's own shape/dtype; share each</span> | |
| <span class="hljs-comment"># input.<name>/output.<name> pair on one buffer so the update lands in place</span> | |
| cache = {} | |
| <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> session.get_inputs(): | |
| <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> i.name.startswith(<span class="hljs-string">"input."</span>): | |
| <span class="hljs-keyword">continue</span> | |
| name = i.name[<span class="hljs-built_in">len</span>(<span class="hljs-string">"input."</span>) :] | |
| dims = [max_cache_len <span class="hljs-keyword">if</span> <span class="hljs-built_in">isinstance</span>(d, <span class="hljs-built_in">str</span>) <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> d.isdigit() <span class="hljs-keyword">else</span> <span class="hljs-built_in">int</span>(d) <span class="hljs-keyword">for</span> d <span class="hljs-keyword">in</span> i.shape] | |
| cache[name] = torch.zeros(dims, dtype=TypeHelper.ort_type_to_torch_type(i.<span class="hljs-built_in">type</span>), device=<span class="hljs-string">"cuda"</span>) | |
| cuda.set_buffer_sharing(<span class="hljs-string">f"input.<span class="hljs-subst">{name}</span>"</span>, <span class="hljs-string">f"output.<span class="hljs-subst">{name}</span>"</span>) | |
| cache_feed = {<span class="hljs-string">f"input.<span class="hljs-subst">{name}</span>"</span>: buf <span class="hljs-keyword">for</span> name, buf <span class="hljs-keyword">in</span> cache.items()} | |
| vocab_size = <span class="hljs-built_in">next</span>(o.shape[-<span class="hljs-number">1</span>] <span class="hljs-keyword">for</span> o <span class="hljs-keyword">in</span> session.get_outputs() <span class="hljs-keyword">if</span> o.name.endswith(<span class="hljs-string">"logits"</span>)) | |
| <span class="hljs-comment"># prefill: the whole prompt in one call</span> | |
| positions = torch.arange(prompt_len, device=<span class="hljs-string">"cuda"</span>) | |
| cuda.allocate_buffers({<span class="hljs-string">"logits"</span>: (<span class="hljs-number">1</span>, prompt_len, vocab_size)}) | |
| out = cuda.infer({<span class="hljs-string">"input_ids"</span>: prompt_ids, <span class="hljs-string">"attention_mask"</span>: causal_mask(positions, max_cache_len), | |
| <span class="hljs-string">"position_ids"</span>: positions[<span class="hljs-literal">None</span>], **cache_feed}) | |
| next_token = out[<span class="hljs-string">"logits"</span>][:, -<span class="hljs-number">1</span>:].argmax(-<span class="hljs-number">1</span>) | |
| <span class="hljs-comment"># decode: query=1 buffers reused in place</span> | |
| cuda.allocate_buffers({<span class="hljs-string">"logits"</span>: (<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, vocab_size)}) | |
| input_ids = torch.empty((<span class="hljs-number">1</span>, <span class="hljs-number">1</span>), dtype=torch.long, device=<span class="hljs-string">"cuda"</span>) | |
| position_ids = torch.empty((<span class="hljs-number">1</span>, <span class="hljs-number">1</span>), dtype=torch.long, device=<span class="hljs-string">"cuda"</span>) | |
| attention_mask = torch.empty((<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, max_cache_len), dtype=torch.<span class="hljs-built_in">bool</span>, device=<span class="hljs-string">"cuda"</span>) | |
| slots = torch.arange(max_cache_len, device=<span class="hljs-string">"cuda"</span>) | |
| <span class="hljs-keyword">for</span> position <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(prompt_len, max_cache_len): | |
| input_ids.copy_(next_token) | |
| position_ids.fill_(position) | |
| attention_mask[<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>].copy_(slots <= position) | |
| out = cuda.infer({<span class="hljs-string">"input_ids"</span>: input_ids, <span class="hljs-string">"attention_mask"</span>: attention_mask, | |
| <span class="hljs-string">"position_ids"</span>: position_ids, **cache_feed}) | |
| next_token = out[<span class="hljs-string">"logits"</span>][:, -<span class="hljs-number">1</span>:].argmax(-<span class="hljs-number">1</span>)<!----></pre></div><!----><!----></div><!----> <div hidden=""><p>ExecuTorch’s on-device runtime is C++, and the in-place cache update relies on <code>Method::set_output_data_ptr</code> — <strong>not surfaced by the Python runtime</strong> (<code>executorch.runtime.Method</code> exposes only <code>execute</code>/<code>set_inputs</code>/<code>get_outputs</code>), so the zero-copy decode is a C++-only path. Bind | |
| each mutated-cache <strong>output</strong> onto its matching cache <strong>input</strong> buffer, and the new K/V/counter land in | |
| the caller’s <code>StaticCache</code> buffers with no copies. As in the other tabs the shapes and sizes come from the | |
| artifact itself — here the program’s <code>method_meta</code> (<code>input_tensor_meta</code>/<code>output_tensor_meta</code> → <code>TensorInfo::nbytes()</code>), the C++ has no Python runtime to query:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-cpp "><!----><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><executorch/extension/data_loader/file_data_loader.h></span></span> | |
| <span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><executorch/extension/tensor/tensor_ptr.h></span></span> | |
| <span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><executorch/runtime/executor/method.h></span></span> | |
| <span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><executorch/runtime/executor/program.h></span></span> | |
| <span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> executorch::runtime; | |
| <span class="hljs-keyword">using</span> executorch::extension::FileDataLoader; | |
| <span class="hljs-keyword">using</span> executorch::extension::make_tensor_ptr; | |
| <span class="hljs-comment">// load the exported decode and its `forward` method (Result error-checks elided for brevity)</span> | |
| <span class="hljs-keyword">auto</span> loader = FileDataLoader::<span class="hljs-built_in">from</span>(<span class="hljs-string">"decode.pte"</span>); | |
| <span class="hljs-keyword">auto</span> program = Program::<span class="hljs-built_in">load</span>(&loader.<span class="hljs-built_in">get</span>()); | |
| <span class="hljs-comment">// method-execution memory: a fixed arena for bookkeeping + one buffer per the method's memory plan</span> | |
| std::array<<span class="hljs-type">uint8_t</span>, 4 * 1024 * 1024> arena; | |
| <span class="hljs-function">MemoryAllocator <span class="hljs-title">method_allocator</span><span class="hljs-params">(arena.size(), arena.data())</span></span>; | |
| <span class="hljs-keyword">auto</span> meta = program-><span class="hljs-built_in">method_meta</span>(<span class="hljs-string">"forward"</span>); | |
| std::vector<std::vector<<span class="hljs-type">uint8_t</span>>> <span class="hljs-built_in">planned</span>(meta-><span class="hljs-built_in">num_memory_planned_buffers</span>()); | |
| std::vector<Span<<span class="hljs-type">uint8_t</span>>> planned_spans; | |
| <span class="hljs-keyword">for</span> (<span class="hljs-type">size_t</span> i = <span class="hljs-number">0</span>; i < planned.<span class="hljs-built_in">size</span>(); ++i) { | |
| planned[i].<span class="hljs-built_in">resize</span>(meta-><span class="hljs-built_in">memory_planned_buffer_size</span>(i).<span class="hljs-built_in">get</span>()); | |
| planned_spans.<span class="hljs-built_in">push_back</span>({planned[i].<span class="hljs-built_in">data</span>(), planned[i].<span class="hljs-built_in">size</span>()}); | |
| } | |
| <span class="hljs-function">HierarchicalAllocator <span class="hljs-title">planned_allocator</span><span class="hljs-params">({planned_spans.data(), planned_spans.size()})</span></span>; | |
| <span class="hljs-function">MemoryManager <span class="hljs-title">memory_manager</span><span class="hljs-params">(&method_allocator, &planned_allocator)</span></span>; | |
| <span class="hljs-keyword">auto</span> decode = std::<span class="hljs-built_in">move</span>(program-><span class="hljs-built_in">load_method</span>(<span class="hljs-string">"forward"</span>, &memory_manager).<span class="hljs-built_in">get</span>()); | |
| <span class="hljs-comment">// shapes and sizes come from method_meta — no external config. Inputs are [ids, mask, position_ids,</span> | |
| <span class="hljs-comment">// cache×N]; outputs are [returned cache×N, logits, mutated cache×N].</span> | |
| <span class="hljs-type">const</span> <span class="hljs-type">size_t</span> num_cache_tensors = meta-><span class="hljs-built_in">num_inputs</span>() - <span class="hljs-number">3</span>; | |
| <span class="hljs-type">const</span> <span class="hljs-type">size_t</span> logits_out_idx = num_cache_tensors; | |
| <span class="hljs-function">std::vector<<span class="hljs-type">size_t</span>> <span class="hljs-title">cache_nbytes</span><span class="hljs-params">(num_cache_tensors)</span>, <span class="hljs-title">cache_out_idx</span><span class="hljs-params">(num_cache_tensors)</span></span>; | |
| <span class="hljs-keyword">for</span> (<span class="hljs-type">size_t</span> i = <span class="hljs-number">0</span>; i < num_cache_tensors; ++i) { | |
| cache_nbytes[i] = meta-><span class="hljs-built_in">input_tensor_meta</span>(<span class="hljs-number">3</span> + i)-><span class="hljs-built_in">nbytes</span>(); | |
| cache_out_idx[i] = num_cache_tensors + <span class="hljs-number">1</span> + i; <span class="hljs-comment">// mutated cache = the last N outputs</span> | |
| } | |
| <span class="hljs-type">const</span> <span class="hljs-type">size_t</span> logits_nbytes = meta-><span class="hljs-built_in">output_tensor_meta</span>(logits_out_idx)-><span class="hljs-built_in">nbytes</span>(); | |
| <span class="hljs-comment">// one set of StaticCache buffers (K/V + per-layer counters) is reused across steps, bound in place each call</span> | |
| <span class="hljs-keyword">auto</span> forward = [&](<span class="hljs-type">const</span> TensorPtr& input_ids, <span class="hljs-type">const</span> TensorPtr& mask, <span class="hljs-type">const</span> TensorPtr& position_ids) { | |
| decode.<span class="hljs-built_in">set_input</span>(<span class="hljs-built_in">EValue</span>(*input_ids), <span class="hljs-number">0</span>); | |
| decode.<span class="hljs-built_in">set_input</span>(<span class="hljs-built_in">EValue</span>(*mask), <span class="hljs-number">1</span>); | |
| decode.<span class="hljs-built_in">set_input</span>(<span class="hljs-built_in">EValue</span>(*position_ids), <span class="hljs-number">2</span>); | |
| <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i < num_cache_tensors; ++i) | |
| decode.<span class="hljs-built_in">set_input</span>(<span class="hljs-built_in">EValue</span>(*cache_tensor[i]), <span class="hljs-number">3</span> + i); | |
| <span class="hljs-comment">// bind each mutated-cache output onto that same input tensor's data → the write lands in place, zero copies</span> | |
| <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i < num_cache_tensors; ++i) | |
| decode.<span class="hljs-built_in">set_output_data_ptr</span>(cache_tensor[i]-><span class="hljs-built_in">mutable_data_ptr</span>(), cache_nbytes[i], cache_out_idx[i]); | |
| decode.<span class="hljs-built_in">set_output_data_ptr</span>(logits_data, logits_nbytes, logits_out_idx); | |
| decode.<span class="hljs-built_in">execute</span>(); <span class="hljs-comment">// cache updated in place; logits written to logits_data</span> | |
| <span class="hljs-keyword">return</span> <span class="hljs-built_in">argmax_last</span>(logits_data); <span class="hljs-comment">// greedy pick</span> | |
| }; | |
| <span class="hljs-comment">// prefill the whole prompt, then decode one token per step — the cache carries in place across all calls</span> | |
| <span class="hljs-type">int64_t</span> next_token = forward(prompt_ids, prompt_mask, prompt_positions); | |
| <span class="hljs-keyword">for</span> (<span class="hljs-type">int64_t</span> position = prompt_len; position < max_cache_len; ++position) { | |
| next_token = forward(<span class="hljs-built_in">make_tensor_ptr</span>({<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}, &next_token, ScalarType::Long), | |
| <span class="hljs-built_in">causal_mask</span>(position), <span class="hljs-comment">// [1, 1, 1, max_cache_len] bool</span> | |
| <span class="hljs-built_in">make_tensor_ptr</span>({<span class="hljs-number">1</span>, <span class="hljs-number">1</span>}, &position, ScalarType::Long)); | |
| }<!----></pre></div><!----><!----></div><!----><!----></div><!----></details> <!--[1--><h2 class="relative group"><a id="onnx-runtime-fusions" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#onnx-runtime-fusions"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->ONNX Runtime fusions<!----></span></h2><!--]--><!----> <p>Set <code>ort_fusions</code> to rewrite an ONNX export into ONNX Runtime’s fused transformer ops before it’s saved. ONNX Runtime | |
| runs the fused graph much faster than the plain one. The fusions cover RMS and layer norms, attention | |
| (<code>MultiHeadAttention</code>, or <code>GroupQueryAttention</code> when there’s a key-value cache), rotary embeddings, GELU, and | |
| projections that share an input. Each fusion gives the same result as the ops it replaces.</p> <p>Set <code>ort_fusions</code> to the execution provider the graph will run on. Each provider gets the fused ops it supports.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Copied</div><!----></button><!----></div> <pre class="language-python "><!---->config = OnnxConfig(ort_fusions=<span class="hljs-string">"cpu"</span>) | |
| config = OnnxConfig(ort_fusions=<span class="hljs-string">"cuda"</span>) | |
| config = OnnxConfig(ort_fusions=<span class="hljs-string">"webgpu"</span>) | |
| config = OnnxConfig(ort_fusions=<span class="hljs-string">"dml"</span>)<!----></pre></div><!----> <table><thead><tr><th></th><th><code>"cpu"</code></th><th><code>"cuda"</code></th><th><code>"webgpu"</code></th><th><code>"dml"</code></th></tr></thead><tbody><tr><td>Attention with a key-value cache</td><td><code>GroupQueryAttention</code>, rotary included</td><td><code>GroupQueryAttention</code> with its query and key norms; the prefill keeps <code>MultiHeadAttention</code> for now (slower)</td><td><code>GroupQueryAttention</code>, rotary as its own <code>RotaryEmbedding</code></td><td><code>MultiHeadAttention</code>, rotary as its own <code>RotaryEmbedding</code></td></tr><tr><td>Other attention</td><td>plain ops for now (slower)</td><td><code>MultiHeadAttention</code></td><td><code>MultiHeadAttention</code></td><td><code>MultiHeadAttention</code></td></tr><tr><td>Mixture of experts</td><td>unfused</td><td><code>MoE</code></td><td>unfused</td><td>unfused</td></tr><tr><td>CUDA graphs</td><td>—</td><td>static exports can replay</td><td>—</td><td>—</td></tr></tbody></table> <p>A <code>"cuda"</code> graph with <code>MoE</code> doesn’t run on CPU, since ONNX Runtime’s <code>MoE</code> only exists for CUDA. A <code>"webgpu"</code> graph runs | |
| in the browser with onnxruntime-web, or natively with onnxruntime-webgpu. A <code>"dml"</code> graph runs on Windows with | |
| onnxruntime-directml.</p> <p>The fused ops aren’t standard ONNX, so other ONNX consumers such as TensorRT or OpenVINO can’t read them. The default | |
| is <code>ort_fusions=None</code>, which keeps the graph standard. If you need the model on several runtimes, export it once for | |
| each.</p> <p>The fusions run before <a href="/docs/transformers/pr_51549/en/main_classes/exporters#transformers.exporters.OnnxRuntimeQuantizer">OnnxRuntimeQuantizer</a> quantizes the graph, as ONNX Runtime recommends. They’re | |
| skipped when the model is quantized before export, and they require <code>optimize=True</code> (the default). The <code>"cuda"</code> fusions | |
| need onnxruntime 1.28 or later.</p> <!--[1--><h2 class="relative group"><a id="quantization" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#quantization"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Quantization<!----></span></h2><!--]--><!----> <p>Every export config takes a <code>quantizer</code> that quantizes the model during the export, on the <code>torch.export</code> FX graph | |
| (PT2E or NNCF, for every backend) or on the converted ONNX or OpenVINO model (ONNX Runtime or NNCF). See <a href="./exporters_quantization">Quantizing exports</a> for the quantizers, their backends, calibration, and how to add one.</p> <!--[1--><h2 class="relative group"><a id="limitations-and-workarounds" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#limitations-and-workarounds"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Limitations and workarounds<!----></span></h2><!--]--><!----> <p><code>torch.export</code>, <code>torch.onnx.export</code>, and ExecuTorch each have rough edges around specific | |
| PyTorch patterns. The exporters work around these with a small set of reversible patches | |
| and FX-level fixes applied at well-defined points in the export flow. None of this is | |
| visible from the public <code>export</code> API, but the most common things to know:</p> <ul><li>FlashAttention and FlexAttention are not exportable on any backend. <code>sdpa</code> is the preferred | |
| setting and <code>eager</code> also works (slower). Set one of them on the model before calling <code>export</code> if it’s using something else.</li> <li><code>grouped_mm</code> traces fine through <code>DynamoExporter</code> and is auto-translated for <code>OnnxExporter</code>. | |
| For <code>ExecutorchExporter</code> with either XNNPACK or MLX, the exporter swaps MoE experts to <code>batched_mm</code> before export.</li> <li>Sliding-window layers (Mistral, Gemma 3) export with a full key-value cache; the sliding mask still applies the window.</li></ul> <!--[1--><h2 class="relative group"><a id="next-steps" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#next-steps"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Next steps<!----></span></h2><!--]--><!----> <ul><li>Add export support for a new architecture or backend with the patch and fix registries in <a href="./exporters_extend">Extending the exporters</a>.</li> <li>Quantize an export, or add a quantizer, in <a href="./exporters_quantization">Quantizing exports</a>.</li></ul> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/transformers/blob/main/docs/source/en/exporters.md" target="_blank"><svg class="mr-1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M31,16l-7,7l-1.41-1.41L28.17,16l-5.58-5.59L24,9l7,7z"></path><path d="M1,16l7-7l1.41,1.41L3.83,16l5.58,5.59L8,23l-7-7z"></path><path d="M12.419,25.484L17.639,6.552l1.932,0.518L14.351,26.002z"></path></svg><!----> <span><span class="underline">Update</span> on GitHub</span></a><!----> <p></p><!--]--><!----><!--]--><!--]--><!--]--> <!--[-1--><!--]--><!--]--> | |
| <script> | |
| { | |
| __sveltekit_1y1dc8m = { | |
| base: "/docs/transformers/main/en", | |
| assets: "/docs/transformers/main/en" | |
| }; | |
| const element = document.currentScript.parentElement; | |
| Promise.all([ | |
| import("/docs/transformers/main/en/_app/immutable/entry/start.BJfF-MbH.js"), | |
| import("/docs/transformers/main/en/_app/immutable/entry/app.Doo6SJy-.js") | |
| ]).then(([kit, app]) => { | |
| kit.start(app, element, { | |
| node_ids: [0, 2], | |
| data: [null,null], | |
| form: null, | |
| error: null | |
| }); | |
| }); | |
| } | |
| </script> | |
Xet Storage Details
- Size:
- 141 kB
- Xet hash:
- 9bd03e92e4c00f26c5209fd9d6932dd678b18e2b0c5a9eff3b75cadfabc1986d
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.