Skip to content

Feat/madlad trt rtx fp16 - #421

Merged
tonythethompson merged 12 commits into
mainfrom
feat/madlad-trt-rtx-fp16
Oct 10, 2026
Merged

tonythethompson merged 12 commits into
mainfrom
feat/madlad-trt-rtx-fp16

Conversation

@tonythethompson

@tonythethompson tonythethompson commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Linked issue

  • Closes #

Scope

  • Single-responsibility change
  • No unrelated refactors included

Testing

  • dotnet build Trackdub.slnx -m:1
  • dotnet test Trackdub.slnx -m:1
  • Targeted tests only
  • Not run, with justification below

Test notes

Architecture review

  • No layer dependency violation introduced
  • No inference code added to Trackdub.App
  • No persistence added to view models
  • No pipeline truth moved into UI state
  • No state mutation added from model wrappers

License/model impact

  • No new third-party dependency
  • No new model or model asset
  • New dependency/model documented
  • Manifest/license requirements reviewed
  • Commercial-safe mode impact reviewed

Risk and rollback

  • Low-risk change
  • Rollback is straightforward
  • Follow-up work required, noted below

Milestone notes

Agent notes


Summary by cubic

MADLAD, previously excluded from TensorRT RTX, now runs on it through a new trt-fp16 model variant with a static-shape greedy decoder that pads inputs to length buckets so the JIT compiles kernels once per bucket. First-time engine builds for large graphs are captured as EP-context artifacts, so later processes deserialize engines instead of rebuilding them.

  • MADLAD planning order is now TensorRT RTX → CPU → DirectML; a TRT RTX session failure falls back to CPU unless the provider is hard-pinned.
  • Source encoding now appends </s>, fixing MADLAD outputs that repeated, paraphrased, or invented clauses.
  • Graphs ≥256 MB without a current artifact are built with EP-context generation and published next to the model; engines over protobuf's 2 GB limit come out as separate files recorded in the stamp.
  • Artifact publication is transactional: a failed or interrupted capture leaves the previous stamp and artifact intact, with the original publication error preserved even when rollback fails, and the session retries plainly; backup files are filtered when resolving existing artifacts.
  • RunWithRetry can fetch only named outputs, so the no-cache decoder stops copying every present.* cache back each step.
  • The worker no longer caches a failed Kokoro construction, so one transient error doesn't fail every later TTS request, and native runtime selection falls back gracefully when the process cannot list its modules.

Written for commit 0d9afa0. Summary will update on new commits.

View guided diff

Summary by CodeRabbit

  • New Features
    • MADLAD translation can now run on TensorRT RTX with a mixed-precision model, with CPU fallback when accelerator session creation fails and a compatible CPU model is available.
    • TensorRT RTX sessions can reuse or generate model artifacts to speed up later session creation.
  • Bug Fixes
    • Artifact validation now detects missing or changed engine files, and failed publication restores previous artifacts where possible.
    • MADLAD smoke tests now check supported TensorRT RTX exports while continuing to reject unsupported configurations.

tonythethompson and others added 6 commits October 7, 2026 22:48
MadladTokenizerDecoder.EncodeSourceText built the encoder input from the
SentencePiece ids alone (the tokenizer is created with
addEndOfSentence: false) and never appended the end-of-sentence token.
T5-family encoders are trained on inputs closed by </s>, so greedy
decoding ran past the sentence: it repeated it ("Bonjour, comment
allez-vous aujourd'hui ? Bonjour, comment allez-vous aujourd'hui ?"),
appended paraphrases, or invented clauses. The OPUS-MT source tokenizer
already adds EOS.

On a fixed 12-sentence en->fr fixture against madlad400-3b-mt, outputs
go from 5 of 12 repeated or hallucinated to 12 clean single
translations, and decoding gets faster because outputs stop at the
real sentence end.

Adds a fixture-gated regression test (TRACKDUB_MADLAD_FIXTURE_ROOT).
Trackdub.Inference.Tests net10.0: 1057 passed, 39 skipped, 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add a trt-fp16 MADLAD variant (the hosted mixed fp16/fp32 encoder and plain
decoder, pinned to c165d741) that only lists trt-rtx, and plan MADLAD on
TensorRT RTX first, then CPU (int4 KV-cache), then DirectML.

TensorRT RTX JIT-compiles kernels for every new input shape, so on that
provider the engine pads encoder input to length buckets, re-runs the decoder
prefix padded to a bucket, and reads the logits at the last real position.
Causal self-attention and the encoder mask keep the padding out, so the output
matches unpadded fp16 decoding (pinned by a fixture test). The TRT RTX
sessions replay a CUDA graph per bucket, and the no-cache decoder now fetches
only logits instead of copying every present.* cache back each step.

The encoder-decoder session constructs and runs under the TRT RTX EP ABI plugin
on both the ORT 1.24 Windows ML root and ORT 1.30, so MADLAD leaves the fatal
TensorRT smoke guard (opus-mt stays). A TRT RTX session failure falls back to
CPU unless the provider was hard-pinned.

Warm one-segment clip, translation stage, RTX 5070: 2.1 s on TensorRT RTX vs
7.9 s for int4 on CPU. The sessions hold ~8 GB of VRAM.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
TRT RTX sessions rebuilt every engine from the source graph in each new
process; the runtime cache only keeps JIT kernels. EP-context artifacts were
produced only by the manual warm pass, and broke for models whose engines
exceed protobuf's 2 GB limit.

- A TRT RTX session for a graph of at least 256 MB without a current artifact
  now builds with EP-context generation on and publishes the artifact next to
  the model, so the next process deserializes engines instead of building them.
  The capture reuses the build the session performs anyway. It is skipped when
  the volume lacks room, and a capture failure retries the session plainly.
- Engines too large to embed are published as separate files. The stamp
  records their names and sizes, and a missing or truncated engine invalidates
  the artifact. Replacing an artifact removes the previous stamp first, then
  its recorded files.
- The embed decision and the stamp now count Optimum's <model>.onnx_data
  external weights, not only <model>.onnx.data.
- The non-pooled encoder-decoder factories (used by smoke probes) go through
  CreateSession, so they load artifacts instead of rebuilding from source.

MADLAD-400 3B fp16 on an RTX 5070, fresh process, translation stage:
83.4 s before, 29.6-40.5 s after. That includes a smoke-probe pair and the
pooled pair; each EP-context load takes 5-13 s for the encoder and 7-21 s for
the decoder, against ~50 s or more to build each from source.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copilot AI balanced review requested due to automatic review settings October 10, 2026 06:06
@cursor

cursor Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • queue - adds this PR to the back of the merge queue
  • fast - for urgent changes, fast-track this PR to the front of the merge queue

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-10T06:11:25.400663Z 3519a58 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 46 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c886b868-05b3-4eba-a92e-8ebd58abfd2d

📥 Commits

Reviewing files that changed from the base of the PR and between 76d0740 and 0d9afa0.


📒 Files selected for processing (2)
  • src/Trackdub.Inference.Onnx/Runtime/GenAiNativeRuntimeSelection.cs
  • src/Trackdub.InferenceWorker/Program.cs

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4f18728e-df2a-457e-8315-68c7d5c9fce7


📥 Commits

Reviewing files that changed from the base of the PR and between ff3a5a6 and 76d0740.



📒 Files selected for processing (16)
  • src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs
  • src/Trackdub.Inference.Onnx/EpContext/EpContextCompiler.cs
  • src/Trackdub.Inference.Onnx/EpContext/EpContextWarmupService.cs
  • src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs
  • src/Trackdub.Inference.Onnx/OnnxExecutionSessionFactory.cs
  • src/Trackdub.Inference.Onnx/Pool/InferenceRetryPolicy.cs
  • src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs
  • src/Trackdub.Inference.Onnx/Translation/Seq2SeqGreedyDecoder.cs
  • src/Trackdub.Inference/Runtime/ModelManifest/bundled-models.manifest.json
  • src/Trackdub.Inference/Runtime/Planning/RuntimePlanFactory.cs
  • src/Trackdub.Inference/Runtime/Planning/StageRuntimeRequirements.cs
  • tests/Trackdub.Inference.Onnx.Tests/EpContextArtifactStampTests.cs
  • tests/Trackdub.Inference.Tests/GenAiTensorRtExclusionTests.cs
  • tests/Trackdub.Inference.Tests/ModelManifestTests.cs
  • tests/Trackdub.Inference.Tests/OnnxTranscriptEnginesTests.cs
  • tests/Trackdub.Inference.Tests/RuntimePlannerTests.cs


💤 Files with no reviewable changes (1)
  • src/Trackdub.Inference/Runtime/Planning/RuntimePlanFactory.cs


Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.




📝 Walkthrough
📝 Walkthrough

Walkthrough

MADLAD translation now supports a TensorRT RTX mixed-precision variant, including provider-aware decoding and CPU replanning. TensorRT EP-context artifacts now support session-time capture, validation of associated files, and locked publication. Tests and reference documentation cover both changes.

Changes

MADLAD TensorRT RTX translation

Layer / File(s) Summary
MADLAD variants and provider selection
src/Trackdub.Inference/Runtime/ModelManifest/bundled-models.manifest.json, src/Trackdub.Inference/Runtime/Planning/*, src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs, tests/Trackdub.Inference.Tests/*, docs/reference/*
The manifest and planner add the trt-fp16 TensorRT RTX option for MADLAD. Provider ordering and smoke checks distinguish MADLAD from OPUS-MT. Tests and reference tables cover the variant, provider selection, and smoke results.
Translation sessions and greedy decoding
src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs, src/Trackdub.Inference.Onnx/Translation/Seq2SeqGreedyDecoder.cs, src/Trackdub.Inference.Onnx/Pool/InferenceRetryPolicy.cs, tests/Trackdub.Inference.Onnx.Tests/MadladFallbackTests.cs, tests/Trackdub.Inference.Tests/OnnxTranscriptEnginesTests.cs
MADLAD translation uses bucketed static shapes, provider-aware encoder and decoder execution, and a two-step smoke-test path. Eligible accelerator session failures can trigger CPU replanning; the tests cover fallback and translated output.

TensorRT EP-context artifacts

Layer / File(s) Summary
Artifact identity and publication
src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs, tests/Trackdub.Inference.Onnx.Tests/EpContextArtifactStampTests.cs, tests/Trackdub.Inference.Onnx.Tests/EpContextPublicationTests.cs
Stamps can record associated artifact files and external model data. Publication validates and moves staged files under a cross-process lock, with rollback on failure. Tests cover file validation, replacement, deletion, rollback, and overlapping publishers.
Session capture and compiler integration
src/Trackdub.Inference.Onnx/EpContext/*, src/Trackdub.Inference.Onnx/OnnxExecutionSessionFactory.cs, docs/reference/tensorrt-rtx-ep-abi-plugin.md
Session creation can capture eligible TensorRT RTX artifacts in a staging directory and retry without capture for classified capture-write failures. Compilation and warmup use shared publication. Hardware metadata and capture behavior are documented.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant RuntimePlanFactory
  participant MadladTranslationEngine
  participant OnnxExecutionSessionFactory
  participant Seq2SeqGreedyDecoder
  RuntimePlanFactory->>MadladTranslationEngine: provide translation plan
  MadladTranslationEngine->>OnnxExecutionSessionFactory: acquire encoder and decoder sessions
  OnnxExecutionSessionFactory-->>MadladTranslationEngine: return session lease
  MadladTranslationEngine->>Seq2SeqGreedyDecoder: decode with provider and static-shape settings
  Seq2SeqGreedyDecoder-->>MadladTranslationEngine: return generated token IDs
Loading
sequenceDiagram
  participant OnnxExecutionSessionFactory
  participant EpContextCapture
  participant EpContextArtifact
  OnnxExecutionSessionFactory->>EpContextCapture: create eligible TensorRT RTX session
  EpContextCapture->>EpContextCapture: capture into staging directory
  EpContextCapture->>EpContextArtifact: publish staged artifact and stamp
  EpContextCapture-->>OnnxExecutionSessionFactory: return created session
Loading


Merge Risk: ⚪ Minimal · up to 76d07

No identified issue prevents merging after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 76d07

Concurrent reuse and replacement are not fully coordinated, so one process can disrupt another process’s startup. The exposure appears limited to processes sharing writable local storage; no new remote access or privilege gain was established.

Retained concerns

  • Medium · reliability · inferred: Automatic publication expands an existing reader-generation gap. A reader can validate a complete generation, then encounter missing or replacement files when another publisher backs up and replaces that set before native opening completes. Publisher-only locking and stamp-first invalidation do not protect readers that already passed validation. The resulting startup failure or incompatible-generation load is inferred, not reproduced. Exposure requires overlapping replacement and loading in a shared model directory; no remote attacker path was established.
Security review details

Security Blast Radius

  • inferred — The demonstrated consistency exposure is bounded to consumers sharing the same writable source-model directory and publication filenames. It can affect eligible shared session-factory consumers beyond translation. Cross-tenant, service-account, or environment exposure cannot be determined without storage ownership and deployment evidence.

Trust Boundaries and Controls

  • observed — Stamp matching is a freshness and environment-compatibility control, not payload authentication. New sibling metadata checks strengthen freshness validation, but do not cryptographically bind native-deserialized bytes. The base already used metadata-based source and sidecar validation, so this limitation is not established as a newly introduced substitution vulnerability.

Resilience and Maintainability Implications

  • observed — CPU replanning is prohibited when the request requires its preferred provider. It requests CPU explicitly and fails clearly if a compatible model needs downloading. Batch leases are disposed in finally; streaming disposes the accelerator lease before CPU recovery and emits the segment only after a successful attempt, avoiding duplicate publication of that segment.

Hardening Proposals

  • proposed — Coordinate validation and native opening with replacement, or publish immutable generation-specific sets and atomically select a generation. If deletion becomes a production lifecycle operation, make it use the same generation and ownership protocol. These are proposals to strengthen consistency, not verified security findings.

Pre-merge checks | Passed 3 | Failed 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check Warning The required template sections are present, but the authored description leaves the summary, linked issue, test notes, architecture review, license/model impact, risk and rollback, milestone notes, an… Complete the required sections. Add a concise summary, linked issue or explicit justification, actual build and test results, test notes, architecture and model-impact confirmations, risk and rollback details, milestone notes, and agent not…
Docstring Coverage Warning Docstring coverage is 17.58% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 91 functions across 19 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check Passed The title clearly identifies the main change: adding MADLAD TensorRT RTX FP16 support. It is concise and related to the changeset.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.


Full details: Description check

Explanation

The required template sections are present, but the authored description leaves the summary, linked issue, test notes, architecture review, license/model impact, risk and rollback, milestone notes, and agent notes largely unfilled. The checklist does not report build or test results.

Resolution

Complete the required sections. Add a concise summary, linked issue or explicit justification, actual build and test results, test notes, architecture and model-impact confirmations, risk and rollback details, milestone notes, and agent notes. Mark checklist items accurately.



Full details: Docstring Coverage

Explanation

Docstring coverage is 17.58% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 91 functions across 19 files. (1 skipped: 1 unsupported.)




✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR





🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR


✨ Simplify code
  • Commit to this branch
  • Create a new PR



  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@amazon-q-developer

Copy link
Copy Markdown
Contributor

⚠️ Review Failed

I was unable to finalize my review because the pull request head or merge base was modified since I began my review. Please try again.

Request ID: 2d52c591-b1d3-54b1-8642-a6d269e3d4b9

@qodo-code-review

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Enable MADLAD TensorRT RTX translation and reusable engine artifacts

✨ Enhancement 🐞 Bug fix 🧪 Tests 📝 Documentation 🕐 40+ Minutes

Grey Divider

AI Description

• Add MADLAD TensorRT RTX and CPU KV-cache variants for faster translation across supported
 hardware.
• Bucket TensorRT input shapes and capture compiled engines to reduce decoding and startup costs.
• Fix missing source EOS tokens; add regression coverage and update provider guidance.
Diagram

graph TD
M["Model manifest"] --> P["Runtime planner"] --> E["MADLAD engine"] --> F["Session factory"] --> A[("EP artifacts")] --> T["TRT RTX"]
E --> D["Greedy decoder"] --> T
E --> C["CPU fallback"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Static-shape KV-cache TensorRT decoder
  • ➕ Could avoid re-running the generated prefix at every step.
  • ➖ Needs a compatible export and fixed cache shapes; adds provider-specific decoding and validation work.
2. Ahead-of-time artifact generation only
  • ➕ Avoids automatic artifact publication during session creation.
  • ➖ Leaves long source-graph rebuilds for users who have not run cache warmup.

Recommendation: Use the PR’s bucketed plain decoder and opportunistic artifact capture for the currently hosted TensorRT export. Retain the CPU KV-cache path; revisit static-shape TensorRT caching if a compatible export becomes available.

Files changed (21) +991 / -333

Enhancement (10) +653 / -278
EpContextArtifact.csTrack and publish complete EP-context artifact sets +111/-8

Track and publish complete EP-context artifact sets

• Adds stamped engine-file validation and staged publication and deletion. Recognizes Optimum '_data' weights and includes external weights when deciding artifact size and embedding.

src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs

EpContextCapture.csCapture large TensorRT engines on first session build +127/-0

Capture large TensorRT engines on first session build

• Enables EP-context generation for eligible large source models, then publishes stamped artifacts for later processes. Checks free space and retries session creation without capture when capture setup fails.

src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs

EpContextCompiler.csPublish compiled models with external engine files +18/-129

Publish compiled models with external engine files

• Routes ahead-of-time compilation through shared staged-artifact publication and returns the engine-file list for stamping. Cleans up staging directories and partial artifacts on failure.

src/Trackdub.Inference.Onnx/EpContext/EpContextCompiler.cs

EpContextWarmupService.csStamp engine files produced by cache warmup +2/-1

Stamp engine files produced by cache warmup

• Includes the compiler’s external engine-file list in warmup artifact stamps so later loads can validate the complete artifact.

src/Trackdub.Inference.Onnx/EpContext/EpContextWarmupService.cs

MadladTranslationEngine.csRoute MADLAD through provider-specific decoding +64/-120

Route MADLAD through provider-specific decoding

• Uses bucketed encoder inputs and shared static-shape greedy decoding on TensorRT RTX, with the plain decoder and CUDA graphs. Uses the shared KV-cache decoder where supported and extends eligible session-failure fallback to CPU.

src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs

OnnxExecutionSessionFactory.csReuse or capture artifacts for encoder-decoder sessions +27/-8

Reuse or capture artifacts for encoder-decoder sessions

• Loads valid EP-context artifacts or captures them while building large TensorRT RTX sessions, including smoke sessions. Exposes the selected provider kind on session leases so decoding follows the actual provider.

src/Trackdub.Inference.Onnx/OnnxExecutionSessionFactory.cs

InferenceRetryPolicy.csAllow callers to request only needed ONNX outputs +8/-3

Allow callers to request only needed ONNX outputs

• Adds an optional output-name selection to retry-backed inference runs, avoiding transfer of unused decoder cache outputs during prefix decoding.

src/Trackdub.Inference.Onnx/Pool/InferenceRetryPolicy.cs

OnnxExecutionProviderSmokeTester.csPermit MADLAD TensorRT RTX smoke tests +6/-6

Permit MADLAD TensorRT RTX smoke tests

• Removes MADLAD from the fatal TensorRT encoder-decoder guard while retaining the OPUS-MT guard.

src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs

Seq2SeqGreedyDecoder.csAdd shared cached and static-shape greedy decoding +277/-0

Add shared cached and static-shape greedy decoding

• Decodes merged models with self- and cross-attention KV caches, or re-runs bucket-padded prefixes for static-shape providers. Reads logits at the last real token and requests only logits when caches are unused.

src/Trackdub.Inference.Onnx/Translation/Seq2SeqGreedyDecoder.cs

StageRuntimeRequirements.csPrefer TensorRT RTX then CPU for MADLAD +13/-3

Prefer TensorRT RTX then CPU for MADLAD

• Adds variant preferences and permits MADLAD on TensorRT RTX without enabling classic TensorRT. Places CPU ahead of other fallback providers for this engine family.

src/Trackdub.Inference/Runtime/Planning/StageRuntimeRequirements.cs

Bug fix (1) +1 / -0
MadladTokenizerDecoder.csTerminate MADLAD source input with EOS +1/-0

Terminate MADLAD source input with EOS

• Appends the end-of-sentence token to encoded source text, addressing repeated or invented output from unterminated encoder inputs.

src/Trackdub.Inference.Onnx/Madlad/MadladTokenizerDecoder.cs

Refactor (1) +8 / -25
EpContextLoadPathResolver.csExpose probed hardware for artifact stamps +8/-25

Expose probed hardware for artifact stamps

• Caches GPU architecture and driver information as a tuple so artifact capture and load-path validation use the same hardware probe.

src/Trackdub.Inference.Onnx/EpContext/EpContextLoadPathResolver.cs

Tests (5) +214 / -22
EpContextArtifactStampTests.csTest external weights and engine-file validation +91/-0

Test external weights and engine-file validation

• Covers Optimum '_data' recognition, artifact publication and replacement, and rejection of missing or truncated engine files.

tests/Trackdub.Inference.Onnx.Tests/EpContextArtifactStampTests.cs

GenAiTensorRtExclusionTests.csTest revised MADLAD provider exclusions +13/-2

Test revised MADLAD provider exclusions

• Removes MADLAD from fatal TensorRT exclusion cases and verifies its TensorRT RTX–then-CPU order while classic TensorRT remains excluded.

tests/Trackdub.Inference.Tests/GenAiTensorRtExclusionTests.cs

ModelManifestTests.csVerify pinned MADLAD variant manifests +38/-2

Verify pinned MADLAD variant manifests

• Checks variant entry paths, provider restrictions, required external weights, pinned download URLs, and hashes.

tests/Trackdub.Inference.Tests/ModelManifestTests.cs

OnnxTranscriptEnginesTests.csCover TensorRT output parity and source EOS +58/-0

Cover TensorRT output parity and source EOS

• Adds fixture-gated integration checks for TensorRT RTX bucketed translation against fp16 reference text and for a single terminal EOS token in source input.

tests/Trackdub.Inference.Tests/OnnxTranscriptEnginesTests.cs

RuntimePlannerTests.csVerify MADLAD TensorRT-to-CPU planning +14/-18

Verify MADLAD TensorRT-to-CPU planning

• Tests that MADLAD selects TensorRT RTX when smoke passes and CPU when it fails, without selecting DirectML first.

tests/Trackdub.Inference.Tests/RuntimePlannerTests.cs

Documentation (3) +39 / -6
gpu-execution-providers.mdDocument MADLAD TensorRT RTX execution +11/-3

Document MADLAD TensorRT RTX execution

• Removes MADLAD from the TensorRT RTX exclusion list. Describes bucketed decoding, CUDA graphs, memory use, performance, and CPU fallback.

docs/reference/gpu-execution-providers.md

tensorrt-rtx-ep-abi-plugin.mdExplain EP-context artifact capture and reuse +25/-1

Explain EP-context artifact capture and reuse

• Documents automatic and ahead-of-time artifact generation, validation, external engine files, disk cost, and MADLAD load-time measurements. Removes MADLAD from the excluded-family examples.

docs/reference/tensorrt-rtx-ep-abi-plugin.md

windows-ml-stage-provider-matrix.mdRecord MADLAD provider order and smoke result +3/-2

Record MADLAD provider order and smoke result

• Updates the translation provider matrix to permit TensorRT RTX for MADLAD and records a passing 'trt-fp16' smoke result.

docs/reference/windows-ml-stage-provider-matrix.md

Other (1) +76 / -2
bundled-models.manifest.jsonPin MADLAD int4 KV and TensorRT fp16 variants +76/-2

Pin MADLAD int4 KV and TensorRT fp16 variants

• Adds provider-scoped 'int4-kv' and 'trt-fp16' variants, their model and tokenizer downloads, and pinned hashes.

src/Trackdub.Inference/Runtime/ModelManifest/bundled-models.manifest.json

@qodo-code-review

qodo-code-review Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Action required

1. Classic TensorRT smoke crashes the host ✓ Resolved
Description
ThrowIfFatalTensorRtFamily no longer rejects MADLAD for either TensorRT provider, although the
newly validated export and provider route are specific to TensorRT RTX. A MADLAD translation smoke
request for classic TensorRT bypasses the stage allow-list and reaches encoder-decoder session
construction, the fatal case this guard previously refused before native code ran.
Code

src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs[364]

+            && engineFamily.Equals("opus-mt", StringComparison.OrdinalIgnoreCase))
Relevance

●●● Strong

Direct smoke requests bypass stage allow-lists, so provider-specific fatal guards must retain
classic TensorRT protection.

PR-#380

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The smoke tester applies this guard directly to the requested provider, then dispatches translation
requests to SmokeTestTranslationAsync, which creates the encoder and decoder sessions. The MADLAD
stage override excludes classic TensorRT, but that override does not constrain a direct smoke
request; the changed guard now checks only OPUS-MT.

src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs[40-81]
src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs[355-369]
src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs[1358-1384]
src/Trackdub.Inference/Runtime/Planning/StageRuntimeRequirements.cs[123-129]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Removing MADLAD from the shared TensorRT smoke guard permits a classic TensorRT probe to reach native session construction, although only TensorRT RTX was validated.
## Fix Focus Areas
- src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs[355-369]
- src/Trackdub.Inference/Runtime/Planning/StageRuntimeRequirements.cs[123-129]
## Recommended Fix
Continue refusing MADLAD when the requested smoke provider is classic TensorRT. Permit its validated TensorRT RTX variant separately, and add a smoke-guard test for both providers.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. GPU failure can leave translation stopped ✓ Resolved
Description
The new accelerator-failure handler immediately requires ReplanForCpuAsync to return a runnable
plan, but that replan does not fetch a CPU-compatible model. When only the newly selected trt-fp16
bundle is downloaded, a TensorRT RTX failure produces a CPU DownloadRequired plan and
EnsurePlanReady throws; the same path exists in streaming translation.
Code

src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[83]

+            catch (Exception ex) when (IsAcceleratorSessionFailure(ex, effectivePlan) && CanFallBackToCpu(request, effectivePlan))
Relevance

●●● Strong

Fallback can produce DownloadRequired without fetching CPU files, affecting both normal and
streaming translation paths.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The trt-fp16 variant lists only trt-rtx. The fallback replan pins CPU while retaining the
preferred variant; the planner can retry another variant, but returns DownloadRequired if its
files are absent. Both newly broadened catches call EnsurePlanReady, which rejects that status.

src/Trackdub.Inference/Runtime/ModelManifest/bundled-models.manifest.json[4140-4156]
src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[82-92]
src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[190-201]
src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[251-266]
src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[352-363]
src/Trackdub.Inference/Runtime/Planning/RuntimePlanner.cs[169-207]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
MADLAD's new TensorRT RTX fallback cannot translate when only the TRT-only variant is cached because CPU replanning needs different model files.
## Fix Focus Areas
- src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[83-91]
- src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[191-200]
- src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[251-266]
## Recommended Fix
Arrange for a CPU-compatible variant to be available before claiming automatic CPU fallback, or route a `DownloadRequired` fallback plan through model setup rather than treating it as ready. Cover both translation modes with only the TRT variant initially cached.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. TRT smoke can run on the crash-prone MADLAD export ✓ Resolved
Description
The madlad allow-list now puts TensorRTRtx first and ThrowIfFatalTensorRtFamily no longer
refuses madlad. The manifest's legacy quantized variant has no supported_providers, and the
planner treats that as "every provider". So when the trt-fp16 files are not on disk, an NVIDIA
machine plans and smoke-tests TRT RTX on
encoder_model_quantized.onnx/decoder_model_quantized.onnx. Those are the graphs whose session
constructor overflowed the stack and killed the process, which is why madlad was excluded in the
first place.
Code

src/Trackdub.Inference/Runtime/Planning/StageRuntimeRequirements.cs[129]

+                    ["madlad"] = [ExecutionProviderKind.TensorRTRtx, .. CpuFirst(WithoutTensorRtFamilies(DefaultOnnxStageAllowedProviders))],
Relevance

●●● Strong

Provider eligibility can select legacy crash-prone graphs; recent precedent supports narrowing
provider allow-lists to proven routes.

PR-#380

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Explorer trace: RuntimeProviderTokenCompatibility.IsVariantSupportedForProvider returns true when
supported_providers is null or empty, so quantized (no field) counts as eligible for
TensorRTRtx. The GPU variant list [trt-fp16, int4-kv, merged-decoder, quantized, fp16] reaches
quantized when trt-fp16 files are missing, and the root quantized entry is also added as a
candidate (RuntimePlanFactory.cs:70-91, 576-686). Translation smoke then resolves
encoder_model_quantized.onnx and decoder_model_quantized.onnx and builds both sessions through
CreateOpusAsync (OnnxExecutionProviderSmokeTester.cs:1377-1401, 1469-1524). The PR only verified
that the new trt_rtx_mixed_fp16_fp32 export builds; the guard it removed was what kept smoke away
from the legacy graphs.

src/Trackdub.Inference/Runtime/ModelManifest/bundled-models.manifest.json[4113-4157]
src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs[355-370]
src/Trackdub.Inference/Runtime/Planning/StageRuntimeRequirements.cs[112-131]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
MADLAD now allows TensorRT RTX first. The legacy `quantized` variant has no `supported_providers`, so the planner counts it as supporting trt-rtx. When `trt-fp16` is not downloaded, it smoke-tests TRT RTX on the legacy quantized graphs, whose session constructor used to crash the process.

## Fix Focus Areas
- src/Trackdub.Inference/Runtime/ModelManifest/bundled-models.manifest.json[4113-4119]
- src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs[360-370]

## Recommended Fix
Add `"supported_providers": ["cpu", "dml", "cuda"]` to the madlad `quantized` variant, and to any other madlad variant that is not trt-fp16. Alternatively, keep `ThrowIfFatalTensorRtFamily` refusing `madlad` unless the encoder path is under `trt_rtx_mixed_fp16_fp32`. Add a planner test showing that TRT RTX is not smoked for madlad when only the quantized files exist.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

4. Disk probe catch omits intent comment ✓ Resolved
Description
HasFreeSpace catches IO and path-related exceptions and returns false without an explanatory
comment inside the catch block. When the drive-space probe fails, ShouldCapture skips artifact
capture, but the handler does not explain to a later reader that this pessimistic fallback is
intentional.
Code

src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[R122-124]

+        catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
+        {
+            return false;
Relevance

●●● Strong

Recent repository precedent explicitly accepted explanatory comments for pessimistic best-effort IO
catches.

PR-#259

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Rule 3659202 requires an explanatory comment inside best-effort catches for IO or path failures. The
newly added catch returns false without one.

Rule 3659202: Empty catch blocks for expected best-effort IO failures must include a brief explanatory comment
src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[115-125]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new best-effort disk-space catch returns a pessimistic result without explaining why the exception is safe to handle this way.

## Fix Focus Areas
- src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[122-125]

## Recommended Fix
Add a brief comment inside the catch stating that an inaccessible drive is treated as insufficient space so artifact capture is skipped.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Concurrent captures can invalidate engines ✓ Resolved
Description
EpContextCapture gives simultaneous builds separate staging directories but publishes both to the
same unstaged artifact paths without a per-source lock. When two sessions for one uncached model
build concurrently, either publisher can delete or replace the other's files between its moves and
stamp write, leaving an invalid artifact or forcing another expensive rebuild.
Code

src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[R95-98]

+        IReadOnlyList<EpContextArtifact.ArtifactFile> artifactFiles =
+            EpContextArtifact.PublishStagedArtifact(stagingDirectory, sourceModelPath);
+        (string gpuArchitecture, string? driverVersion) = EpContextLoadPathResolver.CurrentHardware;
+        EpContextArtifact.WriteStamp(
Relevance

●●● Strong

Concurrent publication mutates shared artifact paths without synchronization, creating a concrete
corruption and rebuild risk.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Capture eligibility checks only a concurrent dictionary of failed sources, not in-progress builds.
Each caller can publish and stamp independently, while PublishStagedArtifact first deletes the
same destination artifact and then replaces its constituent files one at a time.

src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[19-31]
src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[44-55]
src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[84-106]
src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[245-276]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Simultaneous EP-context captures can overwrite or delete each other's shared artifact and stamp.
## Fix Focus Areas
- src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[20-31]
- src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[84-107]
- src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[245-276]
## Recommended Fix
Use a per-source, cross-process publication lock and recheck artifact validity under that lock before replacing files. Keep staging isolated until publication and test overlapping captures.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Failed publication leaves large engines ✓ Resolved
Description
PublishStagedArtifact moves engine files before moving the EP-context model, while
DeleteArtifact can discover published engines only through an existing stamp. If a later move
fails after an engine has moved, the stamp has already been deleted, so compiler or capture cleanup
leaves that engine beside the source model, potentially consuming gigabytes.
Code

src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[R264-266]

+            long length = new FileInfo(stagedPath).Length;
+            File.Move(stagedPath, Path.Join(targetDirectory, name), overwrite: true);
+            published.Add(new ArtifactFile(name, length));
Relevance

●●● Strong

Publication failure can orphan large engines; cleanup logic demonstrably depends on the
already-deleted stamp.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Publication deletes the prior artifact and stamp, moves each engine individually, then moves the
model. DeleteArtifact only iterates stamp?.ArtifactFiles, and the compiler invokes it on
publication failure; without a stamp, previously moved engines remain.

src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[245-276]
src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[279-298]
src/Trackdub.Inference.Onnx/EpContext/EpContextCompiler.cs[152-162]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A publication failure after an engine move strands that engine because cleanup has no stamp listing the newly moved files.
## Fix Focus Areas
- src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[245-276]
- src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[279-298]
## Recommended Fix
Track destination paths during publication and remove those paths if any subsequent move fails, without relying on the deleted stamp. Add a test that forces failure after the first engine move.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View medium (2)
7. Replaced engines still pass validation ✓ Resolved
Description
MatchesArtifactFiles compares each serialized engine's name and byte length but records no
modification time or content identity. Replacing an engine with different bytes of the same length
leaves the stamp valid, so the session factory loads the changed engine rather than rebuilding it
from the source model.
Code

src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[R73-74]

+                var info = new FileInfo(Path.Join(artifactDirectory, file.Name));
+                return info.Exists && info.Length == file.LengthBytes;
Relevance

●● Moderate

Concrete cache-integrity risk, but no closely matching historical acceptance precedent was found.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The new ArtifactFile record holds only a name and length, and MatchesArtifactFiles checks only
existence and length. Successful validation returns the EP-context path, which CreateSession
substitutes for the source model.

src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[65-82]
src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[177-201]
src/Trackdub.Inference.Onnx/OnnxExecutionSessionFactory.cs[340-353]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new engine-file stamp accepts a changed engine when its replacement has the same length.
## Fix Focus Areas
- src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[65-82]
- src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs[245-266]
## Recommended Fix
Record and check at least each engine's modification timestamp alongside its length, or use a content hash if byte-level integrity is required. Test a same-length replacement.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


8. MADLAD smoke misses production settings ✓ Resolved
Description
SmokeTestTranslationAsync uses the generic unpooled decoder session with no additional TensorRT
options, whereas MADLAD production requests pooled sessions with enable_cuda_graph=1 for both
graphs. Now that MADLAD can pass this smoke gate, a passing result does not establish that the
production session configuration constructs and runs successfully, and the probe does not warm the
session production will lease.
Code

src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs[R358-359]

+    // a fatal crash cannot be caught and reported. MADLAD's trt-fp16 export constructs and runs
+    // under the TensorRT RTX EP ABI plugin, so it is smoke-tested like any other pair.
Relevance

●● Moderate

Smoke configuration differs materially from production; similar smoke-test correctness fixes were
accepted recently.

PR-#165

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
Removing the guard activates the generic translation smoke path for MADLAD. That path calls
CreateOpusAsync without additional provider options, while the production engine calls
CreatePooledOpusAsync with CUDA graphs enabled for both sessions.

src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs[355-365]
src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs[1375-1384]
src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[218-243]
src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[285-299]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The newly allowed MADLAD TensorRT RTX smoke probe omits production CUDA-graph options and pooling, so it can report readiness without exercising production sessions.
## Fix Focus Areas
- src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs[1358-1384]
- src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[218-243]
## Recommended Fix
Give MADLAD smoke a provider-specific path that acquires the same pooled sessions with the same TensorRT options as production, and exercise the bucketed inputs used for translation.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

9. A failed engine build is attempted twice ✓ Resolved
Description
EpContextCapture.CreateSession catches every OnnxRuntimeException from the capture-enabled
session build, records the source as failed, and rebuilds the same session from scratch with capture
off. A real TRT RTX build failure (for example too little free VRAM for the multi-GB MADLAD encoder)
therefore pays the ~48 s+ engine build twice before reaching the CPU fallback in
MadladTranslationEngine, and the retry's exception is the one that propagates.
Code

src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[R59-64]

+        catch (Exception ex) when (ex is OnnxRuntimeException or IOException or UnauthorizedAccessException)
+        {
+            MarkFailed(fullSource, ex.Message);
+            EpContextCompiler.TryDeleteDirectory(stagingDirectory);
+            options.AddSessionConfigEntry("ep.context_enable", "0");
+            return createSession(sourceModelPath, options);
Relevance

●●● Strong

Broad retry catches build failures and deterministically repeats expensive engine construction
before fallback.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The catch filter accepts any OnnxRuntimeException, so it cannot tell a capture-specific failure
from a general build failure, and it always calls createSession again. The engine's new
IsAcceleratorSessionFailure handles TRT OnnxRuntimeException by falling back to CPU only after
this second build also fails.

src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[50-65]
src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs[249-253]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A genuine TRT RTX build failure is retried with a full second build, which doubles the time before the CPU fallback.

## Fix Focus Areas
- src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs[59-65]

## Recommended Fix
Retry without capture only for IO/permission errors, or for ORT errors whose message mentions EP-context or file writing. Otherwise mark the source failed, delete the staging directory and rethrow, so the caller's CPU fallback runs right away.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
✅ Compliance rules (platform): 4 rules
✅ Cross-repo context — repo relationships
  Explored: repo: trackdubllc/Trackdub-gated (sha: 6520fa3e) — View relationship
✅ REVIEW.md
Review mode: Auto: 🧠 Deep: Large, bug-dense inference changes span caching, decoding, planning, manifests, and fallback paths.

Grey Divider

Tip of the day
💡 Did you know, you can copy the agent prompt from any finding and feed it to your IDE agent

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs
Comment thread src/Trackdub.Inference.Onnx/Runtime/Planning/OnnxExecutionProviderSmokeTester.cs Outdated
Comment thread src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs
Comment thread src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs Outdated
Comment thread src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs Outdated
Comment thread src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs Outdated
Comment thread src/Trackdub.Inference/Runtime/Planning/StageRuntimeRequirements.cs
Comment thread src/Trackdub.Inference.Onnx/EpContext/EpContextCapture.cs Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3519a58a3d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/Trackdub.Inference.Onnx/EpContext/EpContextCompiler.cs Outdated
Comment thread src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs Outdated
@qodo-code-review

Copy link
Copy Markdown
Contributor

Qodo Fixer

🍒 Ready to be cherry-picked — ✅ Merged (0) · ☑ Fixed (3)

Grey Divider

🔗 Fix PR: #422

This fix PR was closed automatically. Its branch is preserved so you can cherry pick the changes into the original PR.

Prompt for coding agent

This is an automated fix prepared on a separate branch (#422). It is NOT applied to this PR.
To use it: review Fix PR #422 (https://github.com/trackdubllc/Trackdub/pull/422), evaluate each change critically against your local context, and cherry-pick the changes that are correct into this branch. Do not accept them blindly.
Process — 3 fixed
  • ☑ Fixed: Classic TensorRT smoke crashes the host
  • ☑ Fixed: GPU failure can leave translation stopped
  • ☑ Fixed: TRT smoke can run on the crash-prone MADLAD export

Comment thread src/Trackdub.Inference.Onnx/Translation/Seq2SeqGreedyDecoder.cs Fixed
Comment thread src/Trackdub.Inference.Onnx/Translation/Seq2SeqGreedyDecoder.cs Fixed
Comment thread src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs Fixed

@opencode-agent opencode-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review: 2 inline finding(s); the summary follows as a comment.

Comment thread src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs Outdated
Comment thread src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs Outdated
@opencode-agent

Copy link
Copy Markdown
Contributor

Review submitted successfully. Here is the summary:


Review: pullrequestreview-5477924627

This PR enables MADLAD translation on TensorRT RTX through a new trt-fp16 variant with a static-shape greedy decoder, adds EP-context capture for large engine builds, and fixes missing EOS tokens in source encoding. The implementation is largely correct — the KV-cache lifecycle, static-shape bucketing, provider planning order, manifest entries, and retry policy's new outputNames parameter are all sound. Two findings:

# File:Line Severity Title
1 src/Trackdub.Inference.Onnx/Madlad/MadladTranslationEngine.cs:319 important provider: null on TRT RTX causes doomed retries instead of immediate propagation
2 src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs:252-265 suggestion Partial PublishStagedArtifact failure orphans engine files (no rollback)

Finding 1 — TranslateSegmentAsync passes provider: null to the new Seq2SeqGreedyDecoder.Decode. The retry policy's IsTransientMessage returns true for null on [ErrorCode:RuntimeException], so a corrupted CUDA context on TRT RTX burns ~1.05 s of backoff on 3 doomed retries instead of propagating. The policy's own documentation says to pass the provider for TRT RTX. This was unreachable before (MADLAD ran on CPU/DML) but is now live. The encoder call at line 306 has the same gap but is context (outside the diff). One-click suggestion provided.

Finding 2 — PublishStagedArtifact deletes the stamp first, then moves engine files one by one. If a File.Move fails midway, the stamp is gone, so the caller's cleanup DeleteArtifact finds an empty ArtifactFiles list and leaves the moved engine files orphaned (potentially GBs). No correctness impact (no stamp → no validation), but disk waste persists across republishes. Described the rollback fix since it's not a single-line replacement.

github run

Comment thread src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs Fixed
@opencode-agent

Copy link
Copy Markdown
Contributor

No noteworthy issues found.

This increment (review_base f61d1db → head e3404f8) addresses all previously identified findings from the prior review and other reviewers:

  • provider: null fix — TranslateSegmentAsync now passes sessionLease.SelectedProviderKind to both encoder RunWithRetry and Seq2SeqGreedyDecoder.Decode, so TRT RTX corrupted-context errors propagate instead of burning doomed retry backoff.
  • PublishStagedArtifact rollback — A backup/restore mechanism with a cross-process FileShare.None lock replaces the old delete-first approach. Moved files are tracked and deleted on failure; old files are backed up and restored in reverse order (stamp last). A concurrent-reuse check returns existing valid artifact files without republishing.
  • Classic TensorRT crash guard — ThrowIfFatalTensorRtFamily now takes variant and entryPath, rejecting MADLAD on classic TensorRT always, and on TRT RTX unless the variant is trt-fp16 in the trt_rtx_mixed_fp16_fp32 directory. Legacy quantized graphs cannot reach TRT RTX session construction.
  • CPU fallback model availability — ReplanForCpuAsync drops the variant pin (PreferredModelVariantAlias: null), checks for DownloadRequired, and throws a clear InvalidOperationException with the accelerator failure as inner exception if CPU files are absent.
  • Double build on failure — ShouldRetryWithoutCapture only retries capture I/O failures (message-based detection of ep.context/EPContext/failed to write); native engine failures (OnnxRuntimeException) mark the source failed and rethrow immediately.
  • Same-length engine tamper detection — ArtifactFile now records LastWriteUtcTicks; MatchesArtifactFiles checks both length and mtime.
  • MADLAD smoke fidelity — SmokeTestAsync uses AcquireLeaseAsync (pooled sessions with enable_cuda_graph=1 for TRT RTX) and exercises production bucketed decoding via TranslateSegmentAsync.
  • Manifest supported_providers — The quantized variant now declares ["cpu", "dml", "cuda"], preventing the planner from selecting it for TRT RTX. The trt-fp16 variant declares ["trt-rtx"] only.

The one candidate I investigated in depth (the rollback catch block's lack of per-item exception handling) was dispositioned as self-healing: the narrow TOCTOU window requires a reader to open the EP-context model between the publisher's file move and stamp write, and even then the consequence is orphaned disk (no stamp → rebuild), not data corruption. Not actionable.

github run

@opencode-agent opencode-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review: 1 inline finding(s); the summary follows as a comment.

Comment thread src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs Outdated
@opencode-agent

Copy link
Copy Markdown
Contributor

Review submitted: pullrequestreview-5478042447

This increment (review_base f61d1db → head ca3910c) addresses all previously identified findings from the prior review and other reviewers. The fixes are sound: the provider: null gap is closed, PublishStagedArtifact now uses a cross-process lock with backup/restore rollback, ThrowIfFatalTensorRtFamily guards classic TensorRT and unvalidated MADLAD exports, ReplanForCpuAsync drops the variant pin and handles DownloadRequired, ShouldRetryWithoutCapture only retries capture I/O failures, ArtifactFile records mtime, and MADLAD smoke exercises production sessions. The RuntimePlanFactory default-variant change was audited against all 48 manifest variant sections — no non-MADLAD model is affected.

One new finding:

# File:Line Severity Title
1 src/Trackdub.Inference.Onnx/EpContext/EpContextArtifact.cs:315-327 suggestion Rollback catch block masks original exception when I/O fails

github run

@opencode-agent

Copy link
Copy Markdown
Contributor

I've completed a thorough review of this increment (review_base ca3910c → head ff3a5a6). The diff is small and focused: it wraps the rollback I/O operations in PublishStagedArtifact's catch block (lines 319-334 of EpContextArtifact.cs) with an inner try-catch for IOException/UnauthorizedAccessException, and adds a regression test verifying the original publication error propagates while recovery backups are preserved.

I traced the full publication/rollback flow, verified the mayDeleteRollback flag lifecycle (false on rollback failure preserves backups; true on success cleans up), confirmed throw; rethrows the original error with stack trace intact, validated the exception filter covers all realistic file I/O failure types (DirectoryNotFoundException and FileNotFoundException both derive from IOException), and confirmed the Trace.TraceWarning pattern is consistent with existing code (TryDeleteFile at line 436). The test correctly forces a restore failure by creating a directory at the old engine's path and asserts the original exception identity, backup preservation, new-file cleanup, and stamp absence.

No noteworthy issues found.

github run

main now carries #419 (Windows ML 2.4 plus the MADLAD KV-cache work this branch builds on).
Conflicts were the shared MADLAD files; this branch's versions are kept and main's later
changes are re-applied on top: the GenAI provider list without DirectML, kokoro on CUDA,
the quantized MADLAD variant as the default with its exports out of the model-level
download list, and the updated MADLAD fallback comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@opencode-agent

Copy link
Copy Markdown
Contributor

Snapshot validation passed. Since the PR was force-pushed and the review_base (ca3910c) is from a different commit tree, the preflight cannot anchor inline comments against the PR diff. Per the skill, I'm returning a concise markdown summary with both confirmed findings.


Review: Increment ca3910c → 76d0740 (force-pushed; inline anchoring unavailable because the review base is from a prior commit tree).

This increment introduces an out-of-process ORT 1.30 inference worker, GenAI native runtime selection with SHA256 provenance, DirectML runtime probing, TTS streaming prefetch, and a Windows ML 2.4.89 package upgrade. Two confirmed findings; inline comment submission was rejected by the anchor preflight (the pinned diff comparison spans two disjoint commit trees due to the force-push), so both are reported here.

# File:Line Severity Title
1 src/Trackdub.Inference.Onnx/Runtime/GenAiNativeRuntimeSelection.cs:94–103 important LoadedPath throws Win32Exception on restricted Windows, bypassing FindCandidate fallback
2 src/Trackdub.InferenceWorker/Program.cs:17–20 important Lazy<KokoroTtsEngine> caches constructor exceptions, permanently disabling the worker without restart

Finding 1 — LoadedPath Win32Exception bypass: LoadedPath calls Process.GetCurrentProcess().Modules, which can throw Win32Exception on restricted Windows configurations. SelectPath uses LoadedPath(fileName) ?? FindCandidate(...), but ?? only handles null — if LoadedPath throws, the on-disk FindCandidate fallback is never reached and native runtime loading fails entirely. The codebase already handles this exact risk in NvidiaAfxNative.LoadedModulePaths with a try-catch for Win32Exception. Fix: wrap the Process.Modules access in a try-catch returning null on Win32Exception, matching the existing pattern.

Finding 2 — Lazy<KokoroTtsEngine> faulted state: Lazy<KokoroTtsEngine> uses the default ExecutionAndPublication mode, which caches factory exceptions. If the constructor throws once (e.g., corrupted manifest via BundledModelManifestRegistry.TryLoadDefault — whose catch filter doesn't cover JsonException or UnauthorizedAccessException — or a malformed TRACKDUB_MODEL_CACHE env var), every subsequent .Value access rethrows the cached exception. HandleAsync catches it and sends an error response, keeping the process alive. The client only restarts on process exit (Process.HasExited), so the worker is permanently stuck returning errors without recovery. Fix: replace Lazy<KokoroTtsEngine> with eager construction so a constructor failure exits the process and engages the client's MaxStarts=3 restart logic; update the two kokoro.Value / kokoro.IsValueCreated usage sites accordingly.

Out of diff: No additional summary-only findings. The InferenceWorkerClient lifecycle, TtsStreamingPrefetch concurrency, provider discovery/scoping, and protocol wire format were all investigated and found correct.

github run

…ction

- GenAiNativeRuntimeSelection.LoadedPath returns null when the process cannot list its modules (Win32Exception on restricted Windows), so SelectPath falls back to the on-disk candidate instead of failing native loading. The post-load identity check still fails closed.
- The inference worker creates its Kokoro engine lazily without caching a construction failure, so one transient error no longer fails every later TTS request for the worker's lifetime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@opencode-agent

Copy link
Copy Markdown
Contributor

Review: increment ca3910c → 0d9afa0 (force-pushed; inline anchoring unavailable because the review base is from a prior commit tree).

The two prior findings from the last review (LoadedPath Win32Exception bypass, Lazy<KokoroTtsEngine> faulted-state caching) are both resolved: LoadedPath now catches Win32Exception/NotSupportedException/InvalidOperationException and returns null (falling through to FindCandidate), and Program.cs replaces Lazy<KokoroTtsEngine> with a kokoro ??= new KokoroTtsEngine(...) pattern under a lock that does not cache construction failures. Four new findings:

# File:Line Severity Title
1 src/Trackdub.Inference.Onnx/Worker/InferenceWorkerProtocol.cs:38-43 important Non-atomic protocol write desynchronizes the IPC stream on cancellation
2 src/Trackdub.Inference.Onnx/Worker/InferenceWorkerClient.cs:194 suggestion Exited Process handle not disposed on worker restart
3 src/Trackdub.Inference.Onnx/Runtime/Planning/DirectMlRuntimeProbe.cs:19-22 suggestion Inverted guard returns "available" when DirectML is unavailable
4 src/Trackdub.Inference/Runtime/Planning/StageRuntimeRequirements.cs:50-52 suggestion Spurious ExpectedRuntimeMismatch warning for Qwen2.5 on CPU

Finding 1 — WriteAsync sends the 4-byte length header and JSON body as two separate stream.WriteAsync calls, both using the caller's CancellationToken. If cancellation fires after the header write but before the body write, only the length prefix reaches the pipe, permanently desynchronizing the protocol stream — the worker reads the header, then blocks waiting for body bytes that never arrive, and the next request's bytes are misinterpreted as the missing body. The host doesn't detect this (Process.HasExited is false), so the poisoned worker keeps running. Fix: combine header and body into a single byte[] buffer, call cancellationToken.ThrowIfCancellationRequested() before the write, and issue one stream.WriteAsync(buffer, CancellationToken.None) followed by FlushAsync(CancellationToken.None).

Finding 2 — When EnsureStartedAsync restarts after a crash, process = started overwrites the old Process without disposing it, leaking OS handles (bounded by MaxStarts = 3, so at most 2 leaked). Fix: process?.Dispose(); before the assignment.

Finding 3 — DirectMlRuntimeProbe.Probe() returns null (meaning "DirectML available" per the XML doc) when !SupportsWindowsMlRoutes, but DirectML is not available on a build lacking Windows ML routes. The logic is inverted. Currently unreachable (the sole caller in OnnxExecutionProviderDiscovery gates on SupportsWindowsMlRoutes), but any future caller would get a false "available" result. Fix: return a reason string instead of null.

Finding 4 — Excluding DirectML from GenAI families causes Qwen2.5-1.5B-Instruct to fall back to CPU on Windows, but the model's expected_runtime field ("ort-genai|onnxruntime-directml|tensorrt-rtx" in bundled-models.manifest.json:1554) has no CPU token. This produces a spurious ExpectedRuntimeMismatch warning on every CPU plan, even though CPU is now the intended fallback. Fix: add "onnxruntime-cpu" to that expected_runtime field in the manifest. Qwen2.5 is the only GenAI model with an expected_runtime field; whisper-genai and phi-genai models are unaffected.

github run

@tonythethompson
tonythethompson merged commit 474726e into main Oct 10, 2026
25 checks passed
@tonythethompson
tonythethompson deleted the feat/madlad-trt-rtx-fp16 branch October 10, 2026 08:36
@tonythethompson
tonythethompson restored the feat/madlad-trt-rtx-fp16 branch October 10, 2026 09:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants