Repository navigation
Replies: 3 comments
|
With this feature implemented, we can even ask agents to do more like:
|
0 replies
|
Lets use dataloaders and other pytorch infra to make this a bit simpler to use. |
0 replies
|
The overall proposal of the pipeline looks good and makes sense from users' perspective.
In the long term, we could target it as a Torch-TensorRT Compiler Specialist Agent or TRT compiler Specialist Agent that could take many different front ends of models and compile it to SOL perf on various platform and beat the other agents who only does some normal optimization. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Summary
As an increasing number of people start vibe coding and as agents/tooling start driving optimization workflows, we need a stable, machine-readable compilation surface and a safe out-of-process execution path so optimization, validation, and benchmarking can be automated reliably and without fragile log-parsing or accidental unsafe execution.
This RFC proposes making Torch-TensorRT an agent-ready optimization system that agents can understand, inspect before compilation, execute, verify, and explain through stable, structured interfaces.
The implementation has two layers:
The initial scope is exclusively local. Remote servers, network APIs, distributed workers, multi-user authorization, and remote artifact storage are out of scope of this RFC, but could be considered in the future.
Motivation
Compiler information often reaches callers through stdout, stderr, or Python exceptions. Agents need a more reliable interface to determine:
Structured interfaces should support both local agents and conventional Python tooling without requiring log parsing or MCP-specific compiler logic.
Goals
Non-Goals
Architecture
The proposed initial transport is stdio: the local MCP client launches the server as a subprocess. No network listener is required.
The server runs in an explicitly configured Python environment and uses the local GPU and filesystem. It remains a thin adapter over Torch-TensorRT capabilities rather than a separate compilation implementation.
1. Structured Compiler Interfaces
1.1 Versioned Compilation Reports
Each compilation invocation should produce a structured report, including unsuccessful invocations.
Required information:
Coverage must have an explicit definition, including its denominator and excluded nodes. It must not be presented as a performance estimate.
1.2 Structured Failures
Failures should contain:
{ "schema_version": "1.0", "status": "failed", "failure": { "category": "unsupported_operator", "stage": "lowering", "operator": "aten.some_op.default", "node_id": "node_47", "message": "No Dynamo converter is registered for this operator.", "retryable": false, "suggested_actions": [ "Enable PyTorch fallback for this operator", "Provide a custom converter", "Rewrite the graph to avoid this operator" ] } }Initial taxonomy:
Retry guidance should distinguish retrying an unchanged request from retrying after modifying configuration or the environment.
1.3 Preflight Analysis
Provide an
analyze()interface for inspecting a request before engine building.It should report:
Analysis must distinguish confirmed findings from predictions. It should also disclose whether a check requires model execution rather than purely static inspection.
1.4 Events and Diagnostic Packages
Provide structured events alongside human-readable logs:
Events should identify the job, stage, timestamp, and ordering. Examples include:
Emit progress percentages only when meaningful underlying measurements exist.
Persist diagnostic packages locally with structured reports, raw logs, and relevant graph artifacts. The MCP Server should expose current status and bounded diagnostic summaries without requiring agents to read entire logs.
2. Correctness Validation
Provide a validation harness with explicit input generation, metrics, and tolerances.
Illustrative API:
Reports should include:
The protocol must define output matching and relative-error behavior near zero. Passing validation demonstrates agreement for the tested inputs only.
3. Reproducible Benchmarking
Provide a benchmark harness that compares baseline and compiled execution under a declared protocol.
Illustrative API:
Reports should record:
Device execution time and end-to-end latency must remain distinct. Reports should record known local measurement conditions and avoid implying that the GPU was isolated unless isolation was established.
4. Local Artifact Manifests
Store artifacts and supporting evidence in a local output directory.
Illustrative layout:
Artifact names and formats depend on compilation mode. Validation and benchmark reports are included only when those stages run; their absence does not imply success.
The manifest should record:
The local MCP Server should use artifact IDs associated with these manifests rather than requiring agents to infer artifact identity from filenames.
5. Local MCP Tool Surface
The following names are proposed interfaces, not claims about existing APIs.
collect_environmentanalyzecompileget_job_statuscancel_jobvalidatebenchmarkget_reportget_artifact_manifestLong-running operations should return a job ID. Status queries should distinguish queued, running, succeeded, failed, cancellation-requested, and cancelled states.
Use a local worker subprocess for execution where appropriate. Define termination and cleanup behavior explicitly; requesting cancellation must not be reported as completed cancellation until the worker has stopped.
6. Local Execution Boundaries
Local-only operation does not mean unrestricted execution. The initial server should enforce:
Model loading and model execution should be treated as execution-sensitive operations. The initial implementation should accept only developer-approved local models or entry points, rather than treating every file inside the workspace as trusted.
Remote credentials, network authorization, and remote artifact-transfer policies are outside this RFC.
7. Repository Location and Packaging
Decision: The local MCP adapter will live in the main Torch-TensorRT repository but will be distributed as a separate, optional Python package.
Repository location and packaging are independent choices: the repository determines how development is coordinated, while packaging determines what users install. Co-location allows a single change to update core contracts, the adapter, tests, and documentation while those contracts are still evolving. Separate packaging keeps MCP dependencies out of the core compiler installation.
torch-tensorrt; compiler-owned contractstorch-tensorrt-mcppackage (proposed name)Proposed layout:
Boundaries
torch-tensorrt-mcpdepends on public Torch-TensorRT APIs;torch-tensorrtnever depends on MCP. The adapter translates MCP requests into core API calls and returns their structured results. It must not duplicate operator analysis, rely on compiler internals, or reconstruct reports by parsing logs.Future Repository Split
A separate repository may be considered once the adapter has independent maintainers, a different release cadence, or support for multiple optimization backends. Keeping a clean package boundary now preserves that option.
8. User Workflow Example
This section illustrates the intended end-to-end experience after the capabilities in this RFC are implemented. All commands, tool names, and outputs are proposed designs, not existing interfaces.
8.1 One-Time Setup
Install the optional adapter into an existing Torch-TensorRT environment:
Register the local server with an MCP client using stdio transport (no network listener):
{ "mcpServers": { "torch-tensorrt": { "command": "/home/alice/miniconda3/envs/trt-env/bin/torch-tensorrt-mcp", "args": [ "--workspace", "/home/alice/projects/detector", "--output-root", "/home/alice/projects/detector/trt-jobs", "--allowed-entrypoint", "models/build.py:build_model" ] } } }The configuration explicitly defines the Python environment, the readable and writable directories, and the approved model entry point.
8.2 Example: Optimizing a Detection Model with FP16
The user asks the coding agent:
The agent then performs the following steps.
Step 1: Inspect the environment.
collect_environmentreturns the GPU (L4, compute capability 8.9) and the CUDA, TensorRT, and PyTorch versions. An incompatible environment returnsenvironment_incompatiblebefore any compilation work starts.Step 2: Run preflight analysis.
analyze(entrypoint, input_spec, precision="fp16")returns:{ "status": "warnings", "unsupported_ops": [ {"operator": "aten.nonzero.default", "node_id": "node_312", "confirmed": true, "reason": "data-dependent output shape"} ], "predicted_partitions": {"trt": 2, "fallback": 1}, "suggested_actions": ["Allow PyTorch fallback for aten.nonzero.default"] }The agent explains that
nonzeroin post-processing will fall back to PyTorch, producing two TensorRT segments and one PyTorch segment, and asks the user whether this fallback is acceptable.Step 3: Start compilation as a local job. After user approval,
compile(...)immediately returns ajob_id. The agent pollsget_job_statusand observes structured events:The agent can report precisely that it is building the second TensorRT engine. The user may request
cancel_jobat any time.Step 4: Validate correctness.
validate(job_id, tolerances={"max_rel_error": 1e-3})returns:{"status": "pass", "samples": 200, "metrics": {"max_rel_error": 0.00064}, "nan_or_inf_detected": false}The agent states that the result demonstrates agreement on the 200 tested inputs only.
Step 5: Benchmark.
benchmark(job_id, iterations=5000, timing="cuda_events")reports p95 latency decreasing from 23.9 ms to 9.6 ms (about 2.5x p95 speedup), excluding transfers and preprocessing.Step 6: Deliver the artifact. After
get_artifact_manifest(job_id), the agent summarizes:8.3 Failure Handling
If engine building runs out of memory,
get_job_statusreturns:{"status": "failed", "failure": {"category": "out_of_memory", "stage": "engine_build", "retryable": true, "suggested_actions": ["Reduce workspace size", "Reduce max batch in shape profile"]}}Based on the category, the agent determines that an unchanged retry is not useful, adjusts the configuration (for example, reducing workspace size), recompiles, and reports the change to the user without reading raw logs.
8.4 Resulting Change in User Experience
The entire workflow runs locally. The same
analyze,validate, andbenchmarkinterfaces remain usable directly from Python scripts and CI without MCP.Delivery Plan
Phase 1: Structured Core Capabilities
Implement compilation reports, error taxonomy, preflight analysis, events, and diagnostic packages.
Phase 2: Verification and Artifact Evidence
Implement validation, benchmarking, reproducibility metadata, and local manifests.
Phase 3: Local MCP Adapter
Implement a stdio-based server as the optional
torch-tensorrt-mcppackage in the main repository, starting with environment inspection, analysis, and report retrieval. Add local compilation, validation, benchmarking, and cancellation after the execution contract is defined.Success Criteria
torch-tensorrtnever pulls in MCP dependencies.All reactions