-
Notifications
You must be signed in to change notification settings - Fork 217
Add support for torch.export exported models #1499
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,63 @@ | ||
| // Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information. | ||
| #include "THSExport.h" | ||
|
|
||
| // torch.export support via AOTInductor | ||
| // This uses torch::inductor::AOTIModelPackageLoader which is INFERENCE-ONLY | ||
| // Models must be compiled with torch._inductor.aoti_compile_and_package() in Python | ||
|
|
||
| ExportedProgramModule THSExport_load(const char* filename) | ||
| { | ||
| CATCH( | ||
| // Load .pt2 file using AOTIModelPackageLoader | ||
| // This requires models to be compiled with aoti_compile_and_package() | ||
| auto* loader = new torch::inductor::AOTIModelPackageLoader(filename); | ||
| return loader; | ||
| ); | ||
|
|
||
| return nullptr; | ||
| } | ||
|
|
||
| void THSExport_Module_dispose(const ExportedProgramModule module) | ||
| { | ||
| delete module; | ||
| } | ||
|
|
||
| void THSExport_Module_run( | ||
| const ExportedProgramModule module, | ||
| const Tensor* input_tensors, | ||
| const int input_length, | ||
| Tensor** result_tensors, | ||
| int64_t* result_length) | ||
| { | ||
| *result_tensors = nullptr; | ||
| *result_length = 0; | ||
|
|
||
| CATCH( | ||
| // Convert input tensor pointers to std::vector<torch::Tensor> | ||
| std::vector<torch::Tensor> inputs; | ||
| inputs.reserve(input_length); | ||
| for (int i = 0; i < input_length; i++) { | ||
| inputs.push_back(*input_tensors[i]); | ||
| } | ||
|
|
||
| // Run inference | ||
| std::vector<torch::Tensor> outputs = module->run(inputs); | ||
|
|
||
| // Allocate output array and copy results | ||
| auto count = outputs.size(); | ||
| auto* tensors = new Tensor[count]; | ||
|
|
||
|
Comment on lines
+46
to
+49
|
||
| for (size_t i = 0; i < count; i++) { | ||
| tensors[i] = new torch::Tensor(outputs[i]); | ||
| } | ||
|
|
||
| // Only expose to caller after full success | ||
| *result_tensors = tensors; | ||
| *result_length = static_cast<int64_t>(count); | ||
| ); | ||
| } | ||
|
|
||
| void THSExport_Module_run_free_results(Tensor* result_tensors) | ||
| { | ||
| delete[] result_tensors; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| // Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information. | ||
| #pragma once | ||
|
|
||
| #include "../Stdafx.h" | ||
|
|
||
| #include "torch/torch.h" | ||
| #include "torch/csrc/inductor/aoti_package/model_package_loader.h" | ||
|
|
||
| #include "Utils.h" | ||
|
|
||
| // torch.export ExportedProgram module via AOTInductor | ||
| // Note: Uses torch::inductor::AOTIModelPackageLoader for inference-only execution | ||
| typedef torch::inductor::AOTIModelPackageLoader* ExportedProgramModule; | ||
|
|
||
| // torch.export support via AOTInductor - Load and execute PyTorch ExportedProgram models (.pt2 files) | ||
| // ExportedProgram is PyTorch 2.x's recommended way to export models for production deployment | ||
| // | ||
| // IMPORTANT: This implementation uses torch::inductor::AOTIModelPackageLoader which is | ||
| // INFERENCE-ONLY. Training, parameter updates, and device movement are not supported. | ||
| // Models must be compiled with torch._inductor.aoti_compile_and_package() in Python. | ||
|
|
||
| // Load an AOTInductor-compiled model package from a .pt2 file | ||
| EXPORT_API(ExportedProgramModule) THSExport_load(const char* filename); | ||
|
|
||
| // Dispose of an ExportedProgram module | ||
| EXPORT_API(void) THSExport_Module_dispose(const ExportedProgramModule module); | ||
|
|
||
| // Execute the ExportedProgram's forward method (inference only) | ||
| // Input: Array of tensors | ||
| // Output: Array of result tensors (caller must free with THSExport_Module_run_free_results) | ||
| EXPORT_API(void) THSExport_Module_run( | ||
| const ExportedProgramModule module, | ||
| const Tensor* input_tensors, | ||
| const int input_length, | ||
| Tensor** result_tensors, | ||
| int64_t* result_length); | ||
|
|
||
| // Free the result tensor array allocated by THSExport_Module_run | ||
| EXPORT_API(void) THSExport_Module_run_free_results(Tensor* result_tensors); |
| Original file line number | Diff line number | Diff line change | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,238 @@ | ||||||||||||||||
| // Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information. | ||||||||||||||||
|
|
||||||||||||||||
| using System; | ||||||||||||||||
| using System.Runtime.InteropServices; | ||||||||||||||||
| using static TorchSharp.PInvoke.NativeMethods; | ||||||||||||||||
|
|
||||||||||||||||
| namespace TorchSharp | ||||||||||||||||
| { | ||||||||||||||||
| public static partial class torch | ||||||||||||||||
| { | ||||||||||||||||
| public static partial class export | ||||||||||||||||
| { | ||||||||||||||||
| /// <summary> | ||||||||||||||||
| /// Load a PyTorch ExportedProgram from a .pt2 file compiled with AOTInductor. | ||||||||||||||||
| /// </summary> | ||||||||||||||||
| /// <param name="filename">Path to the .pt2 file</param> | ||||||||||||||||
| /// <returns>ExportedProgram model for inference</returns> | ||||||||||||||||
| /// <remarks> | ||||||||||||||||
| /// IMPORTANT: The .pt2 file must be compiled with torch._inductor.aoti_compile_and_package() in Python. | ||||||||||||||||
| /// Models saved with torch.export.save() alone will NOT work - they require AOTInductor compilation. | ||||||||||||||||
| /// | ||||||||||||||||
| /// This implementation is INFERENCE-ONLY. Training, parameter updates, and device movement | ||||||||||||||||
| /// are not supported. The model is compiled for a specific device (CPU/CUDA) at compile time. | ||||||||||||||||
| /// | ||||||||||||||||
| /// Example Python code to create compatible .pt2 files: | ||||||||||||||||
| /// <code> | ||||||||||||||||
| /// import torch | ||||||||||||||||
| /// import torch._inductor | ||||||||||||||||
| /// | ||||||||||||||||
| /// # Export the model | ||||||||||||||||
| /// exported = torch.export.export(model, example_inputs) | ||||||||||||||||
| /// | ||||||||||||||||
| /// # Compile with AOTInductor (required for C++ loading) | ||||||||||||||||
| /// torch._inductor.aoti_compile_and_package( | ||||||||||||||||
| /// exported, | ||||||||||||||||
| /// package_path="model.pt2" | ||||||||||||||||
| /// ) | ||||||||||||||||
| /// </code> | ||||||||||||||||
| /// </remarks> | ||||||||||||||||
| public static ExportedProgram load(string filename) | ||||||||||||||||
| { | ||||||||||||||||
| return new ExportedProgram(filename); | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| /// <summary> | ||||||||||||||||
| /// Load a PyTorch ExportedProgram with typed output. | ||||||||||||||||
| /// </summary> | ||||||||||||||||
| public static ExportedProgram<TResult> load<TResult>(string filename) | ||||||||||||||||
| { | ||||||||||||||||
| return new ExportedProgram<TResult>(filename); | ||||||||||||||||
| } | ||||||||||||||||
| } | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| /// <summary> | ||||||||||||||||
| /// Represents a PyTorch ExportedProgram loaded from an AOTInductor-compiled .pt2 file. | ||||||||||||||||
| /// This is an INFERENCE-ONLY implementation - training and parameter updates are not supported. | ||||||||||||||||
| /// </summary> | ||||||||||||||||
| /// <remarks> | ||||||||||||||||
| /// Unlike TorchScript models, ExportedProgram models are ahead-of-time (AOT) compiled for | ||||||||||||||||
| /// a specific device and are optimized for inference performance. They provide 30-40% better | ||||||||||||||||
| /// latency compared to TorchScript in many cases. | ||||||||||||||||
| /// | ||||||||||||||||
| /// Key limitations: | ||||||||||||||||
| /// - Inference only (no training, no gradients) | ||||||||||||||||
| /// - No parameter access or updates | ||||||||||||||||
| /// - No device movement (compiled for specific device) | ||||||||||||||||
| /// - No dynamic model structure changes | ||||||||||||||||
| /// | ||||||||||||||||
| /// Use torch.jit for models that require training or dynamic behavior. | ||||||||||||||||
| /// </remarks> | ||||||||||||||||
| public class ExportedProgram : IDisposable | ||||||||||||||||
| { | ||||||||||||||||
| private IntPtr handle; | ||||||||||||||||
| private bool _disposed = false; | ||||||||||||||||
|
|
||||||||||||||||
| internal ExportedProgram(string filename) | ||||||||||||||||
| { | ||||||||||||||||
| handle = THSExport_load(filename); | ||||||||||||||||
| if (handle == IntPtr.Zero) | ||||||||||||||||
| torch.CheckForErrors(); | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| /// <summary> | ||||||||||||||||
| /// Run inference on the model with the given input tensors. | ||||||||||||||||
| /// </summary> | ||||||||||||||||
| /// <param name="inputs">Input tensors for the model</param> | ||||||||||||||||
| /// <returns>Array of output tensors</returns> | ||||||||||||||||
| /// <remarks> | ||||||||||||||||
| /// The number and shapes of inputs must match what the model was exported with. | ||||||||||||||||
| /// All inputs must be on the same device that the model was compiled for. | ||||||||||||||||
| /// </remarks> | ||||||||||||||||
| public torch.Tensor[] run(params torch.Tensor[] inputs) | ||||||||||||||||
| { | ||||||||||||||||
| if (_disposed) | ||||||||||||||||
| throw new ObjectDisposedException(nameof(ExportedProgram)); | ||||||||||||||||
|
|
||||||||||||||||
| // Convert managed tensors to IntPtr array | ||||||||||||||||
| IntPtr[] input_handles = new IntPtr[inputs.Length]; | ||||||||||||||||
| for (int i = 0; i < inputs.Length; i++) | ||||||||||||||||
| { | ||||||||||||||||
| input_handles[i] = inputs[i].Handle; | ||||||||||||||||
| } | ||||||||||||||||
|
|
||||||||||||||||
| // Call native run method | ||||||||||||||||
| THSExport_Module_run(handle, input_handles, inputs.Length, out IntPtr result_ptr, out long result_length); | ||||||||||||||||
| torch.CheckForErrors(); | ||||||||||||||||
|
|
||||||||||||||||
| // Marshal result array | ||||||||||||||||
|
||||||||||||||||
| // Marshal result array | |
| // Marshal result array | |
| if (result_length < 0 || result_length > int.MaxValue) | |
| { | |
| throw new InvalidOperationException( | |
| $"Native export run returned an out-of-range result length: {result_length}."); | |
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed — added range check before casting.
Uh oh!
There was an error while loading. Please reload this page.