Skip to content

Conversation

@nv-yilinf
Copy link
Collaborator

@nv-yilinf nv-yilinf commented Sep 25, 2025

@coderabbitai summary

Description

Improve /perf_metrics endpoints in the following aspects:

  1. Add server_start_time/server_first_token_time and disagg_server_start_time/disagg_server_first_token_time to help us better understand server overhead.
  2. Add time sync support between disagg and ctx/gen servers. Also add time sync support between each ctx/gen server and its own worker node that within the same MPI world
  3. Add support for multiple post workers. Post workers use different output object thus need special handling.

example output of /perf_metrics :

[
  {
    "ctx_server": "http://localhost:8001",
    "gen_server": "http://localhost:8002",
    "**disagg_server_arrival_time**": 16784.652225035,
    "**disagg_server_first_token_ts**": 16784.690138695,
    "ctx_perf_metrics": {
      "request_id": 3,
      "perf_metrics": {
        "first_iter": 43,
        "last_iter": 43,
        "timing_metrics": {
          "**server_arrival_time**": 16784.6539136575,
          "arrival_time": 16784.6547101045,
          "first_scheduled_time": 16784.656631104503,
          "first_token_time": 16784.677545104503,
          "**server_first_token_time**": 16784.681579103497,
          "last_token_time": 16784.677545104503
        },
        "kv_cache_metrics": {
          "num_total_allocated_blocks": 1,
          "num_new_allocated_blocks": 1,
          "num_reused_blocks": 0,
          "num_missed_blocks": 1
        }
      },
      "ctx_request_id": 2049
    },
    "gen_perf_metrics": {
      "request_id": 3,
      "perf_metrics": {
        "first_iter": 300,
        "last_iter": 554,
        "timing_metrics": {
          "server_arrival_time": 16784.683668109,
          "arrival_time": 16784.68432452,
          "first_scheduled_time": 16784.68696352,
          "first_token_time": 16784.69008552,
          "server_first_token_time": 16784.689811751,
          "last_token_time": 16785.058020520002,
          "kv_cache_size": 360448,
          "kv_cache_transfer_start": 16784.686093520002,
          "kv_cache_transfer_end": 16784.68664252
        },
        "kv_cache_metrics": {
          "num_total_allocated_blocks": 1,
          "num_new_allocated_blocks": 1,
          "num_reused_blocks": 1,
          "num_missed_blocks": 0
        }
      },
      "ctx_request_id": 2049
    }
  }
]

Test Coverage

PR Checklist

Please review the following before submitting your PR:

  • PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.

  • PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.

  • Test cases are provided for new code paths (see test instructions)

  • Any new dependencies have been scanned for license and vulnerabilities

  • CODEOWNERS updated if ownership changes

  • Documentation updated as needed

  • The reviewers assigned automatically/manually are appropriate for the PR.

  • Please check this after reviewing the above items as appropriate for this PR.

GitHub Bot Help

/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...

Provide a user friendly way for developers to interact with a Jenkins server.

Run /bot [-h|--help] to print this help message.

See details below for each supported subcommand.

run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]

Launch build/test pipelines. All previously running jobs will be killed.

--reuse-test (optional)pipeline-id (OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.

--disable-reuse-test (OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.

--disable-fail-fast (OPTIONAL) : Disable fail fast on build/tests/infra failures.

--skip-test (OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.

--stage-list "A10-PyTorch-1, xxx" (OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.

--gpu-type "A30, H100_PCIe" (OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.

--test-backend "pytorch, cpp" (OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.

--only-multi-gpu-test (OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.

--disable-multi-gpu-test (OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.

--add-multi-gpu-test (OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.

--post-merge (OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.

--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" (OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".

--detailed-log (OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.

--debug (OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in the stage-list parameter to access the appropriate container environment. Note: Does NOT update GitHub check status.

For guidance on mapping tests to stage names, see docs/source/reference/ci-overview.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip testing for latest commit on pull request. --comment "Reason for skipping build/test" is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

reuse-pipeline

reuse-pipeline

Reuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.

@nv-yilinf nv-yilinf changed the title Ttft tracer [None][feat] perf_metrics endpoint functionality improvement Sep 26, 2025
@nv-yilinf nv-yilinf marked this pull request as ready for review September 26, 2025 01:00
@nv-yilinf nv-yilinf requested review from a team as code owners September 26, 2025 01:00
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 26, 2025

📝 Walkthrough

Walkthrough

Adds an optional global steady clock offset across C++ core, Python bindings, and servers. Propagates offset from server/executor to request objects, adjusts timing points, and extends metrics. Introduces executor-side distributed clock sync, server endpoints/middleware for offset and arrival timestamps, and threads metrics through postproc/result paths.

Changes

Cohort / File(s) Summary
Core LLM request timing and offset API
cpp/include/tensorrt_llm/batch_manager/llmRequest.h
Introduces Duration alias and optional mGlobalSteadyClockOffset. Adds helper methods for global/local steady clock mapping and now/TimePoint. Updates constructors to accept optional global offset. Switches KvCache timing API to TimePoint and uses offset-aware time getters.
Nanobind bindings: offset threading
cpp/tensorrt_llm/nanobind/batch_manager/bindings.cpp, cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.h, cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.cpp
Extends LlmRequest binding and constructor to accept optional global_steady_clock_offset and forward to base. Updates toTrtLlm to pass arrival_time and offset to tb::LlmRequest.
Pybind bindings: offset threading
cpp/tensorrt_llm/pybind/batch_manager/bindings.cpp, cpp/tensorrt_llm/pybind/batch_manager/llmRequest.h, cpp/tensorrt_llm/pybind/batch_manager/llmRequest.cpp
Adds optional globalSteadyClockOffset to constructor exposure and forwards to tb::LlmRequest along with arrivalTime. Adjusts toTrtLlm call sites accordingly.
Executor clock sync and request propagation
tensorrt_llm/_torch/pyexecutor/py_executor.py, tensorrt_llm/_torch/pyexecutor/executor_request_queue.py, tensorrt_llm/_torch/pyexecutor/llm_request.py
Adds distributed monotonic clock sync to compute per-rank offset at init; stores and logs. Passes offset into ExecutorRequestQueue and attaches to requests (py_global_steady_clock_offset), which is forwarded during LlmRequest construction. Skips some perf updates for non-initial decoding iterations.
Post-processing and result propagation
tensorrt_llm/executor/postproc_worker.py, tensorrt_llm/executor/result.py
Extends Output with request_perf_metrics and disaggregated_params; threads these through processing and assigns to first result output.
OpenAI servers: offset endpoints, middleware, metrics
tensorrt_llm/serve/openai_server.py, tensorrt_llm/serve/openai_disagg_server.py
Adds middleware to stamp server_arrival_time via time.monotonic. Introduces steady clock offset endpoints (/steady_clock_offset GET/POST) and application to timing fields. Disagg server computes/applies offsets against context/gen servers, updates perf metric keys, merges streaming responses, and propagates disaggregated params and raw_request.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant R0 as Rank 0
  participant Rn as Other Ranks
  participant PE as PyExecutor
  participant ERQ as ExecutorRequestQueue

  Note over PE: Initialization
  PE->>R0: barrier + capture steady_clock now
  PE->>Rn: barrier + capture steady_clock now
  R0-->>PE: t0
  Rn-->>PE: t_n (per-rank)
  PE->>PE: compute offsets (t0 - t_n)
  PE->>ERQ: construct(..., global_steady_clock_offset=offset_n)
  Note over ERQ: Store offset for requests
Loading
sequenceDiagram
  autonumber
  participant Client
  participant S as OpenAI Server
  participant DS as Disagg Server (optional)
  participant PX as PyExecutor
  participant Q as ExecutorRequestQueue
  participant PyReq as pyexecutor LlmRequest
  participant CppReq as C++ LlmRequest

  Client->>S: HTTP request
  activate S
  Note over S: Middleware stamps server_arrival_time (monotonic)
  S->>S: apply disagg_server_steady_clock_offset to timings
  alt Disaggregated
    S->>DS: request (raw_request passed)
    DS->>DS: stamp arrival, apply per-server offsets
    DS-->>S: streamed/merged responses (+metrics)
  end
  S->>PX: enqueue generation request (+raw_request metrics)
  PX->>Q: push(..., global_steady_clock_offset)
  Q->>PyReq: attach py_global_steady_clock_offset
  PyReq->>CppReq: construct(arrival_time, globalSteadyClockOffset)
  Note over CppReq: use maybeToGlobalSteadyClock/getSteadyClockNow for timing fields
  deactivate S
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.77% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The pull request description retains template placeholders and guidance without a concrete PR title following the “[Ticket][type] Summary” format, and the Test Coverage section and many checklist items are left unfilled, so it does not satisfy the repository’s PR description requirements. Please provide a valid PR title following the “[JIRA ticket/NVBugs ID/GitHub issue/None][type] Summary” template, populate the Test Coverage section with relevant tests, and complete the PR Checklist and any other required sections from the repository’s description template.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title refers to perf_metrics endpoint improvements, which corresponds to part of the changeset, but it does not capture the broader global steady clock offset support introduced across multiple modules, making it only partially representative of the main change.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

👮 Agentic pre-merge checks are now available in preview!

Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.

  • Built-in checks – Quickly apply ready-made checks to enforce title conventions, require pull request descriptions that follow templates, validate linked issues for compliance, and more.
  • Custom agentic checks – Define your own rules using CodeRabbit’s advanced agentic capabilities to enforce organization-specific policies and workflows. For example, you can instruct CodeRabbit’s agent to verify that API documentation is updated whenever API schema files are modified in a PR. Note: Upto 5 custom checks are currently allowed during the preview period. Pricing for this feature will be announced in a few weeks.

Please see the documentation for more information.

Example:

reviews:
  pre_merge_checks:
    custom_checks:
      - name: "Undocumented Breaking Changes"
        mode: "warning"
        instructions: |
          Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).

Please share your feedback with us on this Discord post.


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 and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 8

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.cpp (1)

79-132: Don’t always engage arrivalTime: pass nullopt when unset

You pass mPerfMetrics.timingMetrics.arrivalTime (a default-constructed TimePoint) unconditionally, which forces arrivalTime to epoch when none was provided. That breaks metrics (e.g., huge E2E). Build an optional and pass nullopt for the default value.

Apply this diff:

-    return std::make_shared<tb::LlmRequest>(                       //
+    std::optional<tb::LlmRequest::TimePoint> arrivalTimeOpt = std::nullopt;
+    if (mPerfMetrics.timingMetrics.arrivalTime != tb::LlmRequest::TimePoint{}) {
+        arrivalTimeOpt = mPerfMetrics.timingMetrics.arrivalTime;
+    }
+    return std::make_shared<tb::LlmRequest>(                       //
         mRequestId,                                                //
         mMaxNewTokens,                                             //
         std::make_shared<std::vector<TokenIdType>>(mTokens.at(0)), //
         mSamplingConfig,                                           //
         mIsStreaming,                                              //
         mEndId,                                                    //
         mPadId,                                                    //
         from_torch(mEmbeddingBias),                                //
         from_torch(mBadWordsList),                                 //
         from_torch(mStopWordsList),                                //
         mPositionIds,                                              //
         from_torch(mPromptEmbeddingTable),                         //
         mPromptVocabSize,                                          //
         mMultimodalHashes,                                         //
         mMultimodalPositions,                                      //
         mMultimodalLengths,                                        //
         from_torch(mMultimodalEmbedding),                          //
         from_torch(mMropeRotaryCosSin),                            //
         mMropePositionDeltas,                                      //
         mLoraTaskId,                                               //
         from_torch(mLoraWeights),                                  //
         from_torch(mLoraConfig),                                   //
         mLookaheadConfig,                                          //
         mKvCacheRetentionConfig,                                   //
         mReturnLogProbs,                                           //
         mReturnContextLogits,                                      //
         mReturnGenerationLogits,                                   //
         optDraftTokens,                                            //
         from_torch(mDraftLogits),                                  //
         mExcludeInputFromOutput,                                   //
         callbackAdapter(mLogitsPostProcessor),                     //
         mApplyLogitsPostProcessorBatched,                          //
         optEncoderInputTokens,                                     //
         mReturnEncoderOutput,                                      //
         mClientId,                                                 //
         mPriority,                                                 //
         from_torch(mEncoderInputFeatures),                         //
         mEncoderOutputLength,                                      //
         from_torch(mCrossAttentionMask),                           //
         getLlmRequestType(),                                       //
         std::nullopt,                                              // inputTokenExtraIds
         mNumReturnSequences,                                       //
         mEagleConfig,                                              //
         from_torch(mSkipCrossAttnBlocks),                          //
         false,                                                     // returnPerfMetrics
         mGuidedDecodingParams,                                     //
         mLanguageAdapterUid,                                       //
         mAllottedTimeMs,                                           //
         mContextPhaseParams,                                       //
         mCacheSaltID,                                              //
-        mPerfMetrics.timingMetrics.arrivalTime,                    //
+        arrivalTimeOpt,                                            //
         mGlobalSteadyClockOffset                                   //
     );
cpp/tensorrt_llm/pybind/batch_manager/llmRequest.cpp (1)

79-132: Mirror nanobind fix: guard arrivalTime with std::optional

Same issue here: passing a default-constructed TimePoint always engages arrivalTime. Pass nullopt unless it was explicitly set.

Apply this diff:

-    return std::make_shared<tb::LlmRequest>(                       //
+    std::optional<tb::LlmRequest::TimePoint> arrivalTimeOpt = std::nullopt;
+    if (mPerfMetrics.timingMetrics.arrivalTime != tb::LlmRequest::TimePoint{}) {
+        arrivalTimeOpt = mPerfMetrics.timingMetrics.arrivalTime;
+    }
+    return std::make_shared<tb::LlmRequest>(                       //
         mRequestId,                                                //
         mMaxNewTokens,                                             //
         std::make_shared<std::vector<TokenIdType>>(mTokens.at(0)), //
         mSamplingConfig,                                           //
         mIsStreaming,                                              //
         mEndId,                                                    //
         mPadId,                                                    //
         from_torch(mEmbeddingBias),                                //
         from_torch(mBadWordsList),                                 //
         from_torch(mStopWordsList),                                //
         mPositionIds,                                              //
         from_torch(mPromptEmbeddingTable),                         //
         mPromptVocabSize,                                          //
         mMultimodalHashes,                                         //
         mMultimodalPositions,                                      //
         mMultimodalLengths,                                        //
         from_torch(mMultimodalEmbedding),                          //
         from_torch(mMropeRotaryCosSin),                            //
         mMropePositionDeltas,                                      //
         mLoraTaskId,                                               //
         from_torch(mLoraWeights),                                  //
         from_torch(mLoraConfig),                                   //
         mLookaheadConfig,                                          //
         mKvCacheRetentionConfig,                                   //
         mReturnLogProbs,                                           //
         mReturnContextLogits,                                      //
         mReturnGenerationLogits,                                    //
         optDraftTokens,                                            //
         from_torch(mDraftLogits),                                  //
         mExcludeInputFromOutput,                                   //
         callbackAdapter(mLogitsPostProcessor),                     //
         mApplyLogitsPostProcessorBatched,                          //
         optEncoderInputTokens,                                     //
         mReturnEncoderOutput,                                      //
         mClientId,                                                 //
         mPriority,                                                 //
         from_torch(mEncoderInputFeatures),                         //
         mEncoderOutputLength,                                      //
         from_torch(mCrossAttentionMask),                           //
         getLlmRequestType(),                                       //
         std::nullopt,                                              // inputTokenExtraIds
         mNumReturnSequences,                                       //
         mEagleConfig,                                              //
         from_torch(mSkipCrossAttnBlocks),                          //
         false,                                                     // returnPerfMetrics
         mGuidedDecodingParams,                                     //
         mLanguageAdapterUid,                                       //
         mAllottedTimeMs,                                           //
         mContextPhaseParams,                                       //
         mCacheSaltID,                                              //
-        mPerfMetrics.timingMetrics.arrivalTime,                    //
+        arrivalTimeOpt,                                            //
         mGlobalSteadyClockOffset                                   //
     );
cpp/tensorrt_llm/pybind/batch_manager/bindings.cpp (1)

299-369: Fix pybind constructor wiring for clock offset

The new constructor branch doesn’t compile:

  • TimePoint::duration is unqualified.
  • You pass global_steady_clock_offset, which isn’t defined—the parameter is globalSteadyClockOffset.
  • The exposed kwargs use nb::arg, but this translation unit only has py::arg.

These regressions block the build and the binding can’t expose the new argument. Please wire it up with the qualified type, the correct variable name, and py::arg.

Apply this diff:

-                     std::optional<TimePoint::duration> globalSteadyClockOffset = std::nullopt)
+                     std::optional<tb::LlmRequest::TimePoint::duration> globalSteadyClockOffset = std::nullopt)
...
-                         language_adapter_uid, allotted_time_ms, context_phase_params, cache_salt_id, arrival_time, global_steady_clock_offset};
+                         language_adapter_uid, allotted_time_ms, context_phase_params, cache_salt_id, arrival_time,
+                         globalSteadyClockOffset};
...
-            nb::arg("arrival_time") = std::nullopt, nb::arg("global_steady_clock_offset") = std::nullopt)
+            py::arg("arrival_time") = std::nullopt, py::arg("global_steady_clock_offset") = std::nullopt)
cpp/tensorrt_llm/pybind/batch_manager/llmRequest.h (1)

89-154: Forward the global offset to the base ctor

The new globalSteadyClockOffset parameter stops at this wrapper—the Base constructor never receives it, so the pybind path can’t participate in the global clock sync you’re adding elsewhere. Please forward it alongside arrivalTime.

Apply this diff:

-            cacheSaltID,                                                                                         //
-            arrivalTime                                                                                          //
+            cacheSaltID,                                                                                         //
+            arrivalTime,                                                                                         //
+            globalSteadyClockOffset                                                                              //
🧹 Nitpick comments (6)
cpp/include/tensorrt_llm/batch_manager/llmRequest.h (3)

1697-1715: Make KvCache transfer getters const-correct

getKvCacheTransferStart/End can be const; they just read metrics. Improves API clarity.

Apply this diff:

-    TimePoint getKvCacheTransferStart()
+    TimePoint getKvCacheTransferStart() const
     {
         return mPerfMetrics.timingMetrics.kvCacheTransferStart;
     }
 
-    TimePoint getKvCacheTransferEnd()
+    TimePoint getKvCacheTransferEnd() const
     {
         return mPerfMetrics.timingMetrics.kvCacheTransferEnd;
     }

104-104: Prefer steady_clock::duration alias

Simplify the alias; both are equivalent but this is clearer.

-    using Duration = std::chrono::time_point<std::chrono::steady_clock>::duration;
+    using Duration = std::chrono::steady_clock::duration;

1679-1681: Remove redundant duration_cast

currentTime - mStartTime already yields steady_clock::duration. Minor readability win.

-        auto const elapsed = (std::chrono::duration_cast<Duration>(currentTime - mStartTime));
+        auto const elapsed = currentTime - mStartTime;
tensorrt_llm/executor/postproc_worker.py (1)

72-73: Consider using explicit types instead of Any for new fields.

The new fields request_perf_metrics and disaggregated_params use Any type hints, which reduces type safety and makes the code harder to understand.

Define more specific types or use Optional[Dict] if the structure is dictionary-based:

 class Output(NamedTuple):
     client_id: int
     res: Any
     is_final: bool
     error: str = ""
     metrics: Optional[dict[str, float]] = None
-    request_perf_metrics: Any = None
-    disaggregated_params: Any = None
+    request_perf_metrics: Optional[Dict[str, Any]] = None
+    disaggregated_params: Optional[Dict[str, Any]] = None
cpp/tensorrt_llm/nanobind/batch_manager/bindings.cpp (1)

294-336: Validate global_steady_clock_offset within ±60 s
In cpp/tensorrt_llm/nanobind/batch_manager/bindings.cpp (after line 295), add:

if (global_steady_clock_offset) {
    auto ms = global_steady_clock_offset->count();
    if (ms > 60000 || ms < -60000) {
        // Log warning for large clock offset
    }
}
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)

368-381: Ensure error handling for distributed sync in _get_global_steady_clock_offset
Wrap barrier() and allgather() in a try/except to catch and log communication failures and provide a safe fallback, for example:

 def _get_global_steady_clock_offset(self):
     assert self.global_rank >= 0, "rank should be >= 0"
-    # Sync all ranks
-    self.dist.barrier()
-    local_timestamp = time.monotonic()
-    all_rank_timestamps = self.dist.allgather(local_timestamp)
-    if self.global_rank == 0:
-        logger.info(
-            f"global_steady_clock_offset at each rank: {[local_timestamp - ts for ts in all_rank_timestamps]}"
-        )
-    return all_rank_timestamps[0] - local_timestamp
+    try:
+        # Sync all ranks
+        self.dist.barrier()
+        local_timestamp = time.monotonic()
+        all_rank_timestamps = self.dist.allgather(local_timestamp)
+        if self.global_rank == 0:
+            logger.info(
+                f"global_steady_clock_offset at each rank: {[local_timestamp - ts for ts in all_rank_timestamps]}"
+            )
+        return all_rank_timestamps[0] - local_timestamp
+    except Exception as e:
+        logger.error(f"Failed to compute global steady clock offset: {e}")
+        return 0.0
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7e2521a and 6bd99cc.

📒 Files selected for processing (14)
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h (16 hunks)
  • cpp/tensorrt_llm/nanobind/batch_manager/bindings.cpp (3 hunks)
  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.cpp (1 hunks)
  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.h (2 hunks)
  • cpp/tensorrt_llm/pybind/batch_manager/bindings.cpp (3 hunks)
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.cpp (1 hunks)
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.h (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py (3 hunks)
  • tensorrt_llm/_torch/pyexecutor/llm_request.py (1 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py (4 hunks)
  • tensorrt_llm/executor/postproc_worker.py (4 hunks)
  • tensorrt_llm/executor/result.py (1 hunks)
  • tensorrt_llm/serve/openai_disagg_server.py (12 hunks)
  • tensorrt_llm/serve/openai_server.py (12 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh}: Namespace closing braces must include a trailing comment with the namespace name (e.g., '} // namespace foo').
Prefer const or constexpr variables over #define for constants.
Declare variables that are not modified after initialization as const.
Avoid magic literals in code; except for 0, nullptr, true, false. Use named constants for comparisons and logic.
Use Allman brace style for formatting.
Place the semicolon of an empty for/while loop on a new line.
Bodies of switch/while/do-while/for must be compound statements (brace-delimited), and if/else must always be followed by brace-delimited statements.
Type names (e.g., classes) must be CamelCase starting with an uppercase letter (e.g., FooBar).
Local variables, methods, and namespaces use lowerCamelCase (e.g., localFooBar).
Non-magic-number global variables that are non-static and not in an anonymous namespace must be lowerCamelCase prefixed with 'g' (e.g., gDontUseGlobalFoos).
Non-magic-number globals that are static or in an anonymous namespace use lowerCamelCase prefixed with 's' (e.g., sMutableStaticGlobal).
Locally visible static variables use lowerCamelCase with 's' prefix (e.g., static std::once_flag sFlag).
Private/protected member variables use 'm' prefix with CamelCase (e.g., mNbFooValues). Public members may omit, but 'm' is encouraged for clarity.
Constants (enums, global constants, static constants, and function-scope magic/literal constants) use uppercase SNAKE_CASE with 'k' prefix (e.g., kDIGIT_NUM).
Function-scope constants that are not magic numbers or literals are named like non-constant variables (e.g., bool const pass = a && b).
If macros are necessary, name them in UPPER_SNAKE_CASE (e.g., FOO_VERSION) and prefer constants over #define.
Use LLVM clang-format; wrap lines at a maximum of 120 columns; use '// clang-format off/on' sparingly with justification.
Use smart pointers for heap allocations; prefer unique_ptr for sole ownership, shared_ptr for shared...

Files:

  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.h
  • cpp/tensorrt_llm/nanobind/batch_manager/bindings.cpp
  • cpp/tensorrt_llm/pybind/batch_manager/bindings.cpp
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.cpp
  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.cpp
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.h
**/*.{cpp,cxx,cc,cu,h,hpp,hh,hxx,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

C++ filenames should be lowerCamelCase (first letter lowercase) and must be case-insensitive unique within a compilation target.

Files:

  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.h
  • cpp/tensorrt_llm/nanobind/batch_manager/bindings.cpp
  • cpp/tensorrt_llm/pybind/batch_manager/bindings.cpp
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.cpp
  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.cpp
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.h
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use only spaces, no tabs; indent with 4 spaces.

Files:

  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.h
  • tensorrt_llm/_torch/pyexecutor/llm_request.py
  • cpp/tensorrt_llm/nanobind/batch_manager/bindings.cpp
  • cpp/tensorrt_llm/pybind/batch_manager/bindings.cpp
  • tensorrt_llm/executor/result.py
  • tensorrt_llm/executor/postproc_worker.py
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.cpp
  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.cpp
  • tensorrt_llm/serve/openai_disagg_server.py
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • tensorrt_llm/serve/openai_server.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.h
**/*.{h,hpp,hh,hxx}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Document new class interfaces and function prototypes with Doxygen; use //! for single-line and //!< for members.

Files:

  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.h
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.h
**/*.{h,hpp,hh,hxx,cpp,cxx,cc}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.{h,hpp,hh,hxx,cpp,cxx,cc}: Prefer anonymous namespaces over 'static' for internal linkage of functions.
All templates (class/function/member/static) must be instantiated at least once; non-POD classes should have private data members.

Files:

  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.h
  • cpp/tensorrt_llm/nanobind/batch_manager/bindings.cpp
  • cpp/tensorrt_llm/pybind/batch_manager/bindings.cpp
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.cpp
  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.cpp
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.h
**/*.{h,hpp,hh,hxx,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Use include guards named 'TRTLLM_<FILE_NAME_IN_CAPS_WITH_UNDERSCORES>_H' (no leading or trailing underscore; directory names excluded).

Files:

  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.h
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.h
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).

Files:

  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.h
  • tensorrt_llm/_torch/pyexecutor/llm_request.py
  • cpp/tensorrt_llm/nanobind/batch_manager/bindings.cpp
  • cpp/tensorrt_llm/pybind/batch_manager/bindings.cpp
  • tensorrt_llm/executor/result.py
  • tensorrt_llm/executor/postproc_worker.py
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.cpp
  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.cpp
  • tensorrt_llm/serve/openai_disagg_server.py
  • cpp/include/tensorrt_llm/batch_manager/llmRequest.h
  • tensorrt_llm/serve/openai_server.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.h
**/*.py

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.

Files:

  • tensorrt_llm/_torch/pyexecutor/llm_request.py
  • tensorrt_llm/executor/result.py
  • tensorrt_llm/executor/postproc_worker.py
  • tensorrt_llm/_torch/pyexecutor/executor_request_queue.py
  • tensorrt_llm/serve/openai_disagg_server.py
  • tensorrt_llm/serve/openai_server.py
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
🧠 Learnings (1)
📚 Learning: 2025-08-20T06:56:02.889Z
Learnt from: eopXD
PR: NVIDIA/TensorRT-LLM#6768
File: cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp:577-579
Timestamp: 2025-08-20T06:56:02.889Z
Learning: In cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, maxSequenceLength is now enforced as a non-optional argument in the BlockManager constructor, so concerns about std::nullopt defaulting to 0 are not applicable. When windowSize > maxSequenceLength, a warning should be added instead of handling optional parameter cases.

Applied to files:

  • cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.h
  • cpp/tensorrt_llm/pybind/batch_manager/llmRequest.cpp
🧬 Code graph analysis (4)
tensorrt_llm/executor/postproc_worker.py (1)
tensorrt_llm/serve/openai_disagg_server.py (1)
  • perf_metrics (204-255)
tensorrt_llm/serve/openai_disagg_server.py (2)
tensorrt_llm/serve/openai_server.py (3)
  • add_process_time_header (167-171)
  • openai_completion (603-756)
  • set_steady_clock_offset (323-326)
tensorrt_llm/serve/router.py (4)
  • finish_request (172-173)
  • finish_request (423-424)
  • finish_request (496-502)
  • finish_request (601-608)
tensorrt_llm/serve/openai_server.py (3)
tensorrt_llm/serve/openai_disagg_server.py (2)
  • add_process_time_header (141-145)
  • set_steady_clock_offset (529-533)
triton_backend/all_models/inflight_batcher_llm/tensorrt_llm_bls/1/lib/decode.py (1)
  • Response (200-245)
tensorrt_llm/llmapi/llm.py (1)
  • RequestOutput (49-89)
tensorrt_llm/_torch/pyexecutor/py_executor.py (1)
tensorrt_llm/_torch/distributed/communicator.py (3)
  • barrier (339-340)
  • allgather (101-102)
  • allgather (336-337)
🪛 Ruff (0.13.1)
tensorrt_llm/serve/openai_disagg_server.py

269-269: Do not catch blind exception: Exception

(BLE001)


327-327: Avoid specifying long messages outside the exception class

(TRY003)


340-340: Avoid specifying long messages outside the exception class

(TRY003)


342-342: Undefined name anext. Consider specifying requires-python = ">= 3.10" or tool.ruff.target-version = "py310" in your pyproject.toml file.

(F821)


349-350: Store a reference to the return value of asyncio.create_task

(RUF006)


527-527: Do not catch blind exception: Exception

(BLE001)

tensorrt_llm/serve/openai_server.py

681-681: Undefined name anext. Consider specifying requires-python = ">= 3.10" or tool.ruff.target-version = "py310" in your pyproject.toml file.

(F821)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Pre-commit Check
🔇 Additional comments (5)
cpp/include/tensorrt_llm/batch_manager/llmRequest.h (1)

2192-2211: Nice: centralized clock-domain normalization

maybeToGlobalSteadyClock and getSteadyClockNow encapsulate the offset logic well. This is the right approach to avoid scattered conversions.

tensorrt_llm/executor/result.py (1)

340-350: LGTM: propagate request_perf_metrics and disaggregated_params

Correctly attaches request_perf_metrics and ensures disaggregated_params is populated for the first output, aligning with postproc worker changes.

tensorrt_llm/_torch/pyexecutor/llm_request.py (1)

589-591: Confirm global_steady_clock_offset units in Python binding
The C++ constructor takes a std::chrono::steady_clock::duration (nanosecond ticks by default); ensure py_global_steady_clock_offset is supplied as an integer count of nanoseconds (or convert seconds→nanoseconds) to avoid silent timing skew.

cpp/tensorrt_llm/nanobind/batch_manager/llmRequest.h (1)

89-90: LGTM! Appropriate extension for clock synchronization.

The addition of the globalSteadyClockOffset parameter maintains backward compatibility with the default std::nullopt value, properly forwards to the base class, and follows the existing pattern of optional parameters.

cpp/tensorrt_llm/nanobind/batch_manager/bindings.cpp (1)

294-295: Consistent parameter naming and documentation.

The new parameter global_steady_clock_offset is well-integrated with appropriate default value. The parameter placement at the end maintains backward compatibility.

Also applies to: 336-336, 362-362

@nv-yilinf
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20130 [ run ] triggered by Bot

@nv-yilinf
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20131 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20130 [ run ] completed with state ABORTED
LLM/main/L0_MergeRequest_PR #15173 (Blue Ocean) completed with status: ABORTED

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20131 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15174 completed with status: 'FAILURE'

Copy link
Collaborator

@Superjomn Superjomn left a comment

Choose a reason for hiding this comment

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

LGTM on the llmapi changes.

@nv-yilinf
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20441 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20441 [ run ] completed with state DISABLED
L0 testing is limited to prioritized users. User nv-yilinf is not in the prioritized list. L0 testing cannot be triggered.

@nv-yilinf
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20470 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20470 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15435 completed with status: 'FAILURE'

Signed-off-by: nv-yilinf <[email protected]>
@nv-yilinf
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20484 [ run ] triggered by Bot

@nv-yilinf
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20493 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20484 [ run ] completed with state ABORTED
/LLM/main/L0_MergeRequest_PR pipeline #15449 completed with status: 'FAILURE'

@nv-yilinf
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20502 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20493 [ run ] completed with state ABORTED
LLM/main/L0_MergeRequest_PR #15458 (Blue Ocean) completed with status: ABORTED

@nv-yilinf
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20509 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20502 [ run ] completed with state ABORTED
LLM/main/L0_MergeRequest_PR #15464 (Blue Ocean) completed with status: ABORTED

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20509 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15469 completed with status: 'FAILURE'

@nv-yilinf
Copy link
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20539 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #20539 [ run ] completed with state SUCCESS
/LLM/main/L0_MergeRequest_PR pipeline #15496 completed with status: 'SUCCESS'

@nv-yilinf nv-yilinf enabled auto-merge (squash) October 2, 2025 17:43
@nv-yilinf nv-yilinf merged commit 01423ac into NVIDIA:main Oct 3, 2025
5 checks passed
evezhier pushed a commit to evezhier/TensorRT-LLM that referenced this pull request Oct 3, 2025
faradawn pushed a commit to faradawn/TensorRT-LLM that referenced this pull request Oct 3, 2025
…8005)

Signed-off-by: Yilin Fan <[email protected]>
Signed-off-by: nv-yilinf <[email protected]>
Signed-off-by: Faradawn Yang <[email protected]>
@nv-yilinf nv-yilinf deleted the ttft-tracer branch October 3, 2025 16:55
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.

6 participants