Skip to content

[inductor] Expose torchbind constants from AOTIModelPackageLoader - #182149

Closed
shoumikhin wants to merge 8 commits into
pytorch:mainfrom
shoumikhin:expose-aoti-custom-objs
Closed

shoumikhin wants to merge 8 commits into
pytorch:mainfrom
shoumikhin:expose-aoti-custom-objs

Conversation

@shoumikhin

@shoumikhin shoumikhin commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a public C++ accessor get_custom_objs() on torch::aot_inductor::ProxyExecutor, torch::inductor::AOTIModelContainerRunner, and torch::inductor::AOTIModelPackageLoader (plus a Python binding on the loader) that returns a snapshot of the torchbind custom-class constants embedded in a loaded .pt2 model.

The IValue payloads alias the live entries inside the proxy executor's custom_objs_ map (the existing private storage already populated during OSSProxyExecutor construction by pickle_load_obj). Downcasting to a CustomClassHolder subclass and mutating its state — e.g. binding a stream, attaching a communicator, toggling profiling — affects subsequent run() invocations.

Motivation

Backends that store live state on torchbind constants embedded in .pt2 packages cannot reach those objects after load via any public PyTorch API. The constants live in OSSProxyExecutor::custom_objs_ (private, std::unordered_map<std::string, c10::IValue>) and the loader/runner only expose tensor-typed constant accessors (get_constant_fqns, extract_constants_map, etc.).

Concrete user: torch-tensorrt (pytorch/TensorRT#4232) needs to bind a CUDA Green Context stream onto each TRTEngine torchbind embedded in a torch-tensorrt .pt2 model loaded via AOTIModelPackageLoader. The ExportedProgram path already works (Python walks named_modules() and binds each engine), but the AOTI path has no equivalent because the engines never become attributes of an nn.Module — they live only inside the proxy executor's private map.

This is a purely additive change: the new methods are optional to call, have a no-op default on the base ProxyExecutor, and do not change any existing semantics.

API

// torch/csrc/inductor/aoti_torch/proxy_executor.h
class ProxyExecutor {
  // ...
  virtual std::unordered_map<std::string, c10::IValue> get_custom_objs() const {
    return {};
  }
};

// torch/csrc/inductor/aoti_torch/oss_proxy_executor.h
class OSSProxyExecutor : public ProxyExecutor {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const override {
    return custom_objs_;
  }
};

// torch/csrc/inductor/aoti_runner/model_container_runner.h
class TORCH_API AOTIModelContainerRunner {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};

// torch/csrc/inductor/aoti_package/model_package_loader.h
class TORCH_API AOTIModelPackageLoader {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};

Python:

loader = torch._C._aoti.AOTIModelPackageLoader("model.pt2", "model")
custom_objs = loader.get_custom_objs()  # Dict[str, ScriptObject]

Usage example (from torch-tensorrt)

torch::inductor::AOTIModelPackageLoader loader("model.pt2");

for (auto& [name, ivalue] : loader.get_custom_objs()) {
  if (ivalue.isCustomClass()) {
    if (auto engine = ivalue.toCustomClass<torch_tensorrt::TRTEngine>()) {
      engine->set_external_stream(reinterpret_cast<int64_t>(my_green_stream));
    }
  }
}

auto outputs = loader.run(inputs);  // each engine now uses its bound stream

API design rationale

Three options were considered:

Option Pros Cons Picked
Return const std::unordered_map<std::string, c10::IValue>& Zero copy Leaks STL container layout; ABI-fragile if custom_objs_ is renamed/reshaped ❌
Visitor: for_each_custom_obj(std::function<...>) Hides container Cumbersome, no random access by name ❌
Return std::unordered_map<std::string, c10::IValue> by value ABI-safe; copy is cheap (single-digit entries × pointer-sized IValue); IValue copies share intrusive_ptr so callers still affect live state One copy of the map ✅

We deliberately do not filter by torchbind type or otherwise interpret the constants — the c10::IValue interface is the right abstraction; backend filtering is the caller's job.

Compatibility

  • Source compatibility: additive only. Existing callers of ProxyExecutor, AOTIModelContainerRunner, and AOTIModelPackageLoader are unaffected.
  • Binary compatibility: adds a new virtual to ProxyExecutor, which changes its vtable layout. Downstream subclasses of ProxyExecutor that were compiled against the old header will need a rebuild — but the default implementation handles them transparently if recompiled. No method removed or signature changed.
  • API stability: returns by value (no internal-layout exposure). The map type is part of the public API; if we ever change the executor's storage type we'd convert at the boundary.

Tests

test/inductor/test_aoti_torchbind_constants.py (new):

  • Compile a model with a _TorchScriptTesting._Foo torchbind attribute via aoti_compile_and_package.
  • Load via torch._C._aoti.AOTIModelPackageLoader.
  • Assert get_custom_objs() returns the expected non-empty map.
  • Negative test: model without torchbind constants returns an empty map.

Suggested reviewers

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @ezyang @bdhirsh @malfet

Adds get_custom_objs() accessor on ProxyExecutor (default empty),
OSSProxyExecutor (override), AOTIModelContainerRunner (passthrough),
and AOTIModelPackageLoader (passthrough). Returns the torchbind
custom-class constants embedded in a loaded .pt2 model. The IValue
payloads share intrusive_ptr ownership with the live entries inside
OSSProxyExecutor::custom_objs_, so downcasting and mutating state
(e.g. binding a CUDA stream) affects subsequent run() invocations.

Motivation: torch-tensorrt (pytorch/TensorRT#4232) needs to bind a
CUDA Green Context stream onto each TRTEngine torchbind embedded in
an AOTI .pt2 for SM partitioning on Jetson. The ExportedProgram path
works (Python walks named_modules()), but the AOTI path has no
equivalent because the engines never become module attributes --
they live only inside the proxy executor's private map.

Purely additive: new methods are optional, default to empty on the
base ProxyExecutor, no existing semantics change.
@pytorch-bot

pytorch-bot Bot commented May 1, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/182149

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

❌ 1 New Failure, 1 Unrelated Failure

As of commit 7aed829 with merge base 5b0375b (image):

NEW FAILURE - The following job has failed:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@ezyang
ezyang requested a review from desertfire May 3, 2026 14:24
@shoumikhin

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label May 8, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 4 checks: pull / dynamo-cpython-test / test (dynamo_cpython, 1, 1, linux.c7i.2xlarge), pull / linux-docs / build-docs-python-false, inductor / unit-test / inductor-build / build, inductor / inductor-build / build

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-jammy-cuda13.0-py3.10-gcc11-no-ops / build

Details for Dev Infra team Raised by workflow job

@shoumikhin

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

dsashidh pushed a commit to dsashidh/pytorch that referenced this pull request May 13, 2026
…torch#182149)

## Summary

Adds a public C++ accessor `get_custom_objs()` on `torch::aot_inductor::ProxyExecutor`, `torch::inductor::AOTIModelContainerRunner`, and `torch::inductor::AOTIModelPackageLoader` (plus a Python binding on the loader) that returns a snapshot of the torchbind custom-class constants embedded in a loaded `.pt2` model.

The `IValue` payloads alias the live entries inside the proxy executor's `custom_objs_` map (the existing private storage already populated during `OSSProxyExecutor` construction by `pickle_load_obj`). Downcasting to a `CustomClassHolder` subclass and mutating its state — e.g. binding a stream, attaching a communicator, toggling profiling — affects subsequent `run()` invocations.

## Motivation

Backends that store live state on torchbind constants embedded in `.pt2` packages cannot reach those objects after load via any public PyTorch API. The constants live in `OSSProxyExecutor::custom_objs_` (private, `std::unordered_map<std::string, c10::IValue>`) and the loader/runner only expose tensor-typed constant accessors (`get_constant_fqns`, `extract_constants_map`, etc.).

Concrete user: **torch-tensorrt** ([pytorch/TensorRT#4232](pytorch/TensorRT#4232)) needs to bind a CUDA Green Context stream onto each `TRTEngine` torchbind embedded in a torch-tensorrt `.pt2` model loaded via `AOTIModelPackageLoader`. The `ExportedProgram` path already works (Python walks `named_modules()` and binds each engine), but the AOTI path has no equivalent because the engines never become attributes of an `nn.Module` — they live only inside the proxy executor's private map.

This is a **purely additive** change: the new methods are optional to call, have a no-op default on the base `ProxyExecutor`, and do not change any existing semantics.

## API

```cpp
// torch/csrc/inductor/aoti_torch/proxy_executor.h
class ProxyExecutor {
  // ...
  virtual std::unordered_map<std::string, c10::IValue> get_custom_objs() const {
    return {};
  }
};

// torch/csrc/inductor/aoti_torch/oss_proxy_executor.h
class OSSProxyExecutor : public ProxyExecutor {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const override {
    return custom_objs_;
  }
};

// torch/csrc/inductor/aoti_runner/model_container_runner.h
class TORCH_API AOTIModelContainerRunner {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};

// torch/csrc/inductor/aoti_package/model_package_loader.h
class TORCH_API AOTIModelPackageLoader {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};
```

Python:

```python
loader = torch._C._aoti.AOTIModelPackageLoader("model.pt2", "model")
custom_objs = loader.get_custom_objs()  # Dict[str, ScriptObject]
```

## Usage example (from torch-tensorrt)

```cpp
torch::inductor::AOTIModelPackageLoader loader("model.pt2");

for (auto& [name, ivalue] : loader.get_custom_objs()) {
  if (ivalue.isCustomClass()) {
    if (auto engine = ivalue.toCustomClass<torch_tensorrt::TRTEngine>()) {
      engine->set_external_stream(reinterpret_cast<int64_t>(my_green_stream));
    }
  }
}

auto outputs = loader.run(inputs);  // each engine now uses its bound stream
```

## API design rationale

Three options were considered:

| Option | Pros | Cons | Picked |
|---|---|---|---|
| Return `const std::unordered_map<std::string, c10::IValue>&` | Zero copy | Leaks STL container layout; ABI-fragile if `custom_objs_` is renamed/reshaped | ❌ |
| Visitor: `for_each_custom_obj(std::function<...>)` | Hides container | Cumbersome, no random access by name | ❌ |
| **Return `std::unordered_map<std::string, c10::IValue>` by value** | ABI-safe; copy is cheap (single-digit entries × pointer-sized IValue); IValue copies share intrusive_ptr so callers still affect live state | One copy of the map | ✅ |

We deliberately do **not** filter by torchbind type or otherwise interpret the constants — the `c10::IValue` interface is the right abstraction; backend filtering is the caller's job.

## Compatibility

- **Source compatibility**: additive only. Existing callers of `ProxyExecutor`, `AOTIModelContainerRunner`, and `AOTIModelPackageLoader` are unaffected.
- **Binary compatibility**: adds a new virtual to `ProxyExecutor`, which changes its vtable layout. Downstream subclasses of `ProxyExecutor` that were compiled against the old header will need a rebuild — but the default implementation handles them transparently if recompiled. No method removed or signature changed.
- **API stability**: returns by value (no internal-layout exposure). The map type is part of the public API; if we ever change the executor's storage type we'd convert at the boundary.

## Tests

`test/inductor/test_aoti_torchbind_constants.py` (new):
- Compile a model with a `_TorchScriptTesting._Foo` torchbind attribute via `aoti_compile_and_package`.
- Load via `torch._C._aoti.AOTIModelPackageLoader`.
- Assert `get_custom_objs()` returns the expected non-empty map.
- Negative test: model without torchbind constants returns an empty map.

## Suggested reviewers

- @desertfire — AOTI runner / package loader owner
- @chenyang78 — proxy executor / OSS proxy executor
- @angelayi — `.pt2` package format

Pull Request resolved: pytorch#182149
Approved by: https://github.com/desertfire
Alokksinha00 pushed a commit to Alokksinha00/pytorch that referenced this pull request May 15, 2026
…torch#182149)

## Summary

Adds a public C++ accessor `get_custom_objs()` on `torch::aot_inductor::ProxyExecutor`, `torch::inductor::AOTIModelContainerRunner`, and `torch::inductor::AOTIModelPackageLoader` (plus a Python binding on the loader) that returns a snapshot of the torchbind custom-class constants embedded in a loaded `.pt2` model.

The `IValue` payloads alias the live entries inside the proxy executor's `custom_objs_` map (the existing private storage already populated during `OSSProxyExecutor` construction by `pickle_load_obj`). Downcasting to a `CustomClassHolder` subclass and mutating its state — e.g. binding a stream, attaching a communicator, toggling profiling — affects subsequent `run()` invocations.

## Motivation

Backends that store live state on torchbind constants embedded in `.pt2` packages cannot reach those objects after load via any public PyTorch API. The constants live in `OSSProxyExecutor::custom_objs_` (private, `std::unordered_map<std::string, c10::IValue>`) and the loader/runner only expose tensor-typed constant accessors (`get_constant_fqns`, `extract_constants_map`, etc.).

Concrete user: **torch-tensorrt** ([pytorch/TensorRT#4232](pytorch/TensorRT#4232)) needs to bind a CUDA Green Context stream onto each `TRTEngine` torchbind embedded in a torch-tensorrt `.pt2` model loaded via `AOTIModelPackageLoader`. The `ExportedProgram` path already works (Python walks `named_modules()` and binds each engine), but the AOTI path has no equivalent because the engines never become attributes of an `nn.Module` — they live only inside the proxy executor's private map.

This is a **purely additive** change: the new methods are optional to call, have a no-op default on the base `ProxyExecutor`, and do not change any existing semantics.

## API

```cpp
// torch/csrc/inductor/aoti_torch/proxy_executor.h
class ProxyExecutor {
  // ...
  virtual std::unordered_map<std::string, c10::IValue> get_custom_objs() const {
    return {};
  }
};

// torch/csrc/inductor/aoti_torch/oss_proxy_executor.h
class OSSProxyExecutor : public ProxyExecutor {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const override {
    return custom_objs_;
  }
};

// torch/csrc/inductor/aoti_runner/model_container_runner.h
class TORCH_API AOTIModelContainerRunner {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};

// torch/csrc/inductor/aoti_package/model_package_loader.h
class TORCH_API AOTIModelPackageLoader {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};
```

Python:

```python
loader = torch._C._aoti.AOTIModelPackageLoader("model.pt2", "model")
custom_objs = loader.get_custom_objs()  # Dict[str, ScriptObject]
```

## Usage example (from torch-tensorrt)

```cpp
torch::inductor::AOTIModelPackageLoader loader("model.pt2");

for (auto& [name, ivalue] : loader.get_custom_objs()) {
  if (ivalue.isCustomClass()) {
    if (auto engine = ivalue.toCustomClass<torch_tensorrt::TRTEngine>()) {
      engine->set_external_stream(reinterpret_cast<int64_t>(my_green_stream));
    }
  }
}

auto outputs = loader.run(inputs);  // each engine now uses its bound stream
```

## API design rationale

Three options were considered:

| Option | Pros | Cons | Picked |
|---|---|---|---|
| Return `const std::unordered_map<std::string, c10::IValue>&` | Zero copy | Leaks STL container layout; ABI-fragile if `custom_objs_` is renamed/reshaped | ❌ |
| Visitor: `for_each_custom_obj(std::function<...>)` | Hides container | Cumbersome, no random access by name | ❌ |
| **Return `std::unordered_map<std::string, c10::IValue>` by value** | ABI-safe; copy is cheap (single-digit entries × pointer-sized IValue); IValue copies share intrusive_ptr so callers still affect live state | One copy of the map | ✅ |

We deliberately do **not** filter by torchbind type or otherwise interpret the constants — the `c10::IValue` interface is the right abstraction; backend filtering is the caller's job.

## Compatibility

- **Source compatibility**: additive only. Existing callers of `ProxyExecutor`, `AOTIModelContainerRunner`, and `AOTIModelPackageLoader` are unaffected.
- **Binary compatibility**: adds a new virtual to `ProxyExecutor`, which changes its vtable layout. Downstream subclasses of `ProxyExecutor` that were compiled against the old header will need a rebuild — but the default implementation handles them transparently if recompiled. No method removed or signature changed.
- **API stability**: returns by value (no internal-layout exposure). The map type is part of the public API; if we ever change the executor's storage type we'd convert at the boundary.

## Tests

`test/inductor/test_aoti_torchbind_constants.py` (new):
- Compile a model with a `_TorchScriptTesting._Foo` torchbind attribute via `aoti_compile_and_package`.
- Load via `torch._C._aoti.AOTIModelPackageLoader`.
- Assert `get_custom_objs()` returns the expected non-empty map.
- Negative test: model without torchbind constants returns an empty map.

## Suggested reviewers

- @desertfire — AOTI runner / package loader owner
- @chenyang78 — proxy executor / OSS proxy executor
- @angelayi — `.pt2` package format

Pull Request resolved: pytorch#182149
Approved by: https://github.com/desertfire
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
…torch#182149)

## Summary

Adds a public C++ accessor `get_custom_objs()` on `torch::aot_inductor::ProxyExecutor`, `torch::inductor::AOTIModelContainerRunner`, and `torch::inductor::AOTIModelPackageLoader` (plus a Python binding on the loader) that returns a snapshot of the torchbind custom-class constants embedded in a loaded `.pt2` model.

The `IValue` payloads alias the live entries inside the proxy executor's `custom_objs_` map (the existing private storage already populated during `OSSProxyExecutor` construction by `pickle_load_obj`). Downcasting to a `CustomClassHolder` subclass and mutating its state — e.g. binding a stream, attaching a communicator, toggling profiling — affects subsequent `run()` invocations.

## Motivation

Backends that store live state on torchbind constants embedded in `.pt2` packages cannot reach those objects after load via any public PyTorch API. The constants live in `OSSProxyExecutor::custom_objs_` (private, `std::unordered_map<std::string, c10::IValue>`) and the loader/runner only expose tensor-typed constant accessors (`get_constant_fqns`, `extract_constants_map`, etc.).

Concrete user: **torch-tensorrt** ([pytorch/TensorRT#4232](pytorch/TensorRT#4232)) needs to bind a CUDA Green Context stream onto each `TRTEngine` torchbind embedded in a torch-tensorrt `.pt2` model loaded via `AOTIModelPackageLoader`. The `ExportedProgram` path already works (Python walks `named_modules()` and binds each engine), but the AOTI path has no equivalent because the engines never become attributes of an `nn.Module` — they live only inside the proxy executor's private map.

This is a **purely additive** change: the new methods are optional to call, have a no-op default on the base `ProxyExecutor`, and do not change any existing semantics.

## API

```cpp
// torch/csrc/inductor/aoti_torch/proxy_executor.h
class ProxyExecutor {
  // ...
  virtual std::unordered_map<std::string, c10::IValue> get_custom_objs() const {
    return {};
  }
};

// torch/csrc/inductor/aoti_torch/oss_proxy_executor.h
class OSSProxyExecutor : public ProxyExecutor {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const override {
    return custom_objs_;
  }
};

// torch/csrc/inductor/aoti_runner/model_container_runner.h
class TORCH_API AOTIModelContainerRunner {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};

// torch/csrc/inductor/aoti_package/model_package_loader.h
class TORCH_API AOTIModelPackageLoader {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};
```

Python:

```python
loader = torch._C._aoti.AOTIModelPackageLoader("model.pt2", "model")
custom_objs = loader.get_custom_objs()  # Dict[str, ScriptObject]
```

## Usage example (from torch-tensorrt)

```cpp
torch::inductor::AOTIModelPackageLoader loader("model.pt2");

for (auto& [name, ivalue] : loader.get_custom_objs()) {
  if (ivalue.isCustomClass()) {
    if (auto engine = ivalue.toCustomClass<torch_tensorrt::TRTEngine>()) {
      engine->set_external_stream(reinterpret_cast<int64_t>(my_green_stream));
    }
  }
}

auto outputs = loader.run(inputs);  // each engine now uses its bound stream
```

## API design rationale

Three options were considered:

| Option | Pros | Cons | Picked |
|---|---|---|---|
| Return `const std::unordered_map<std::string, c10::IValue>&` | Zero copy | Leaks STL container layout; ABI-fragile if `custom_objs_` is renamed/reshaped | ❌ |
| Visitor: `for_each_custom_obj(std::function<...>)` | Hides container | Cumbersome, no random access by name | ❌ |
| **Return `std::unordered_map<std::string, c10::IValue>` by value** | ABI-safe; copy is cheap (single-digit entries × pointer-sized IValue); IValue copies share intrusive_ptr so callers still affect live state | One copy of the map | ✅ |

We deliberately do **not** filter by torchbind type or otherwise interpret the constants — the `c10::IValue` interface is the right abstraction; backend filtering is the caller's job.

## Compatibility

- **Source compatibility**: additive only. Existing callers of `ProxyExecutor`, `AOTIModelContainerRunner`, and `AOTIModelPackageLoader` are unaffected.
- **Binary compatibility**: adds a new virtual to `ProxyExecutor`, which changes its vtable layout. Downstream subclasses of `ProxyExecutor` that were compiled against the old header will need a rebuild — but the default implementation handles them transparently if recompiled. No method removed or signature changed.
- **API stability**: returns by value (no internal-layout exposure). The map type is part of the public API; if we ever change the executor's storage type we'd convert at the boundary.

## Tests

`test/inductor/test_aoti_torchbind_constants.py` (new):
- Compile a model with a `_TorchScriptTesting._Foo` torchbind attribute via `aoti_compile_and_package`.
- Load via `torch._C._aoti.AOTIModelPackageLoader`.
- Assert `get_custom_objs()` returns the expected non-empty map.
- Negative test: model without torchbind constants returns an empty map.

## Suggested reviewers

- @desertfire — AOTI runner / package loader owner
- @chenyang78 — proxy executor / OSS proxy executor
- @angelayi — `.pt2` package format

Pull Request resolved: pytorch#182149
Approved by: https://github.com/desertfire
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…torch#182149)

## Summary

Adds a public C++ accessor `get_custom_objs()` on `torch::aot_inductor::ProxyExecutor`, `torch::inductor::AOTIModelContainerRunner`, and `torch::inductor::AOTIModelPackageLoader` (plus a Python binding on the loader) that returns a snapshot of the torchbind custom-class constants embedded in a loaded `.pt2` model.

The `IValue` payloads alias the live entries inside the proxy executor's `custom_objs_` map (the existing private storage already populated during `OSSProxyExecutor` construction by `pickle_load_obj`). Downcasting to a `CustomClassHolder` subclass and mutating its state — e.g. binding a stream, attaching a communicator, toggling profiling — affects subsequent `run()` invocations.

## Motivation

Backends that store live state on torchbind constants embedded in `.pt2` packages cannot reach those objects after load via any public PyTorch API. The constants live in `OSSProxyExecutor::custom_objs_` (private, `std::unordered_map<std::string, c10::IValue>`) and the loader/runner only expose tensor-typed constant accessors (`get_constant_fqns`, `extract_constants_map`, etc.).

Concrete user: **torch-tensorrt** ([pytorch/TensorRT#4232](pytorch/TensorRT#4232)) needs to bind a CUDA Green Context stream onto each `TRTEngine` torchbind embedded in a torch-tensorrt `.pt2` model loaded via `AOTIModelPackageLoader`. The `ExportedProgram` path already works (Python walks `named_modules()` and binds each engine), but the AOTI path has no equivalent because the engines never become attributes of an `nn.Module` — they live only inside the proxy executor's private map.

This is a **purely additive** change: the new methods are optional to call, have a no-op default on the base `ProxyExecutor`, and do not change any existing semantics.

## API

```cpp
// torch/csrc/inductor/aoti_torch/proxy_executor.h
class ProxyExecutor {
  // ...
  virtual std::unordered_map<std::string, c10::IValue> get_custom_objs() const {
    return {};
  }
};

// torch/csrc/inductor/aoti_torch/oss_proxy_executor.h
class OSSProxyExecutor : public ProxyExecutor {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const override {
    return custom_objs_;
  }
};

// torch/csrc/inductor/aoti_runner/model_container_runner.h
class TORCH_API AOTIModelContainerRunner {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};

// torch/csrc/inductor/aoti_package/model_package_loader.h
class TORCH_API AOTIModelPackageLoader {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};
```

Python:

```python
loader = torch._C._aoti.AOTIModelPackageLoader("model.pt2", "model")
custom_objs = loader.get_custom_objs()  # Dict[str, ScriptObject]
```

## Usage example (from torch-tensorrt)

```cpp
torch::inductor::AOTIModelPackageLoader loader("model.pt2");

for (auto& [name, ivalue] : loader.get_custom_objs()) {
  if (ivalue.isCustomClass()) {
    if (auto engine = ivalue.toCustomClass<torch_tensorrt::TRTEngine>()) {
      engine->set_external_stream(reinterpret_cast<int64_t>(my_green_stream));
    }
  }
}

auto outputs = loader.run(inputs);  // each engine now uses its bound stream
```

## API design rationale

Three options were considered:

| Option | Pros | Cons | Picked |
|---|---|---|---|
| Return `const std::unordered_map<std::string, c10::IValue>&` | Zero copy | Leaks STL container layout; ABI-fragile if `custom_objs_` is renamed/reshaped | ❌ |
| Visitor: `for_each_custom_obj(std::function<...>)` | Hides container | Cumbersome, no random access by name | ❌ |
| **Return `std::unordered_map<std::string, c10::IValue>` by value** | ABI-safe; copy is cheap (single-digit entries × pointer-sized IValue); IValue copies share intrusive_ptr so callers still affect live state | One copy of the map | ✅ |

We deliberately do **not** filter by torchbind type or otherwise interpret the constants — the `c10::IValue` interface is the right abstraction; backend filtering is the caller's job.

## Compatibility

- **Source compatibility**: additive only. Existing callers of `ProxyExecutor`, `AOTIModelContainerRunner`, and `AOTIModelPackageLoader` are unaffected.
- **Binary compatibility**: adds a new virtual to `ProxyExecutor`, which changes its vtable layout. Downstream subclasses of `ProxyExecutor` that were compiled against the old header will need a rebuild — but the default implementation handles them transparently if recompiled. No method removed or signature changed.
- **API stability**: returns by value (no internal-layout exposure). The map type is part of the public API; if we ever change the executor's storage type we'd convert at the boundary.

## Tests

`test/inductor/test_aoti_torchbind_constants.py` (new):
- Compile a model with a `_TorchScriptTesting._Foo` torchbind attribute via `aoti_compile_and_package`.
- Load via `torch._C._aoti.AOTIModelPackageLoader`.
- Assert `get_custom_objs()` returns the expected non-empty map.
- Negative test: model without torchbind constants returns an empty map.

## Suggested reviewers

- @desertfire — AOTI runner / package loader owner
- @chenyang78 — proxy executor / OSS proxy executor
- @angelayi — `.pt2` package format

Pull Request resolved: pytorch#182149
Approved by: https://github.com/desertfire
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…torch#182149)

## Summary

Adds a public C++ accessor `get_custom_objs()` on `torch::aot_inductor::ProxyExecutor`, `torch::inductor::AOTIModelContainerRunner`, and `torch::inductor::AOTIModelPackageLoader` (plus a Python binding on the loader) that returns a snapshot of the torchbind custom-class constants embedded in a loaded `.pt2` model.

The `IValue` payloads alias the live entries inside the proxy executor's `custom_objs_` map (the existing private storage already populated during `OSSProxyExecutor` construction by `pickle_load_obj`). Downcasting to a `CustomClassHolder` subclass and mutating its state — e.g. binding a stream, attaching a communicator, toggling profiling — affects subsequent `run()` invocations.

## Motivation

Backends that store live state on torchbind constants embedded in `.pt2` packages cannot reach those objects after load via any public PyTorch API. The constants live in `OSSProxyExecutor::custom_objs_` (private, `std::unordered_map<std::string, c10::IValue>`) and the loader/runner only expose tensor-typed constant accessors (`get_constant_fqns`, `extract_constants_map`, etc.).

Concrete user: **torch-tensorrt** ([pytorch/TensorRT#4232](pytorch/TensorRT#4232)) needs to bind a CUDA Green Context stream onto each `TRTEngine` torchbind embedded in a torch-tensorrt `.pt2` model loaded via `AOTIModelPackageLoader`. The `ExportedProgram` path already works (Python walks `named_modules()` and binds each engine), but the AOTI path has no equivalent because the engines never become attributes of an `nn.Module` — they live only inside the proxy executor's private map.

This is a **purely additive** change: the new methods are optional to call, have a no-op default on the base `ProxyExecutor`, and do not change any existing semantics.

## API

```cpp
// torch/csrc/inductor/aoti_torch/proxy_executor.h
class ProxyExecutor {
  // ...
  virtual std::unordered_map<std::string, c10::IValue> get_custom_objs() const {
    return {};
  }
};

// torch/csrc/inductor/aoti_torch/oss_proxy_executor.h
class OSSProxyExecutor : public ProxyExecutor {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const override {
    return custom_objs_;
  }
};

// torch/csrc/inductor/aoti_runner/model_container_runner.h
class TORCH_API AOTIModelContainerRunner {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};

// torch/csrc/inductor/aoti_package/model_package_loader.h
class TORCH_API AOTIModelPackageLoader {
  // ...
  std::unordered_map<std::string, c10::IValue> get_custom_objs() const;
};
```

Python:

```python
loader = torch._C._aoti.AOTIModelPackageLoader("model.pt2", "model")
custom_objs = loader.get_custom_objs()  # Dict[str, ScriptObject]
```

## Usage example (from torch-tensorrt)

```cpp
torch::inductor::AOTIModelPackageLoader loader("model.pt2");

for (auto& [name, ivalue] : loader.get_custom_objs()) {
  if (ivalue.isCustomClass()) {
    if (auto engine = ivalue.toCustomClass<torch_tensorrt::TRTEngine>()) {
      engine->set_external_stream(reinterpret_cast<int64_t>(my_green_stream));
    }
  }
}

auto outputs = loader.run(inputs);  // each engine now uses its bound stream
```

## API design rationale

Three options were considered:

| Option | Pros | Cons | Picked |
|---|---|---|---|
| Return `const std::unordered_map<std::string, c10::IValue>&` | Zero copy | Leaks STL container layout; ABI-fragile if `custom_objs_` is renamed/reshaped | ❌ |
| Visitor: `for_each_custom_obj(std::function<...>)` | Hides container | Cumbersome, no random access by name | ❌ |
| **Return `std::unordered_map<std::string, c10::IValue>` by value** | ABI-safe; copy is cheap (single-digit entries × pointer-sized IValue); IValue copies share intrusive_ptr so callers still affect live state | One copy of the map | ✅ |

We deliberately do **not** filter by torchbind type or otherwise interpret the constants — the `c10::IValue` interface is the right abstraction; backend filtering is the caller's job.

## Compatibility

- **Source compatibility**: additive only. Existing callers of `ProxyExecutor`, `AOTIModelContainerRunner`, and `AOTIModelPackageLoader` are unaffected.
- **Binary compatibility**: adds a new virtual to `ProxyExecutor`, which changes its vtable layout. Downstream subclasses of `ProxyExecutor` that were compiled against the old header will need a rebuild — but the default implementation handles them transparently if recompiled. No method removed or signature changed.
- **API stability**: returns by value (no internal-layout exposure). The map type is part of the public API; if we ever change the executor's storage type we'd convert at the boundary.

## Tests

`test/inductor/test_aoti_torchbind_constants.py` (new):
- Compile a model with a `_TorchScriptTesting._Foo` torchbind attribute via `aoti_compile_and_package`.
- Load via `torch._C._aoti.AOTIModelPackageLoader`.
- Assert `get_custom_objs()` returns the expected non-empty map.
- Negative test: model without torchbind constants returns an empty map.

## Suggested reviewers

- @desertfire — AOTI runner / package loader owner
- @chenyang78 — proxy executor / OSS proxy executor
- @angelayi — `.pt2` package format

Pull Request resolved: pytorch#182149
Approved by: https://github.com/desertfire
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants