-
Notifications
You must be signed in to change notification settings - Fork 1.7k
[None][feat] move kv cache measure into transfer session #6633
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Signed-off-by: zhengd-nv <[email protected]>
📝 WalkthroughWalkthroughThis change migrates the KV cache transfer measurement logic from a dedicated helper class ( Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant DataSenderImpl
participant TransferSession
participant DataReceiverImpl
participant FileSystem
User->>DataSenderImpl: Initiate send (with measurement enabled)
DataSenderImpl->>TransferSession: Create session (recordMeasure=true)
loop For each KV cache transfer
DataSenderImpl->>TransferSession: appendMeasure(delay, duration, size)
end
DataSenderImpl->>FileSystem: On release, exportMeasure() to CSV
User->>DataReceiverImpl: Initiate receive (with measurement enabled)
DataReceiverImpl->>TransferSession: Create session (recordMeasure=true)
loop For each KV cache receive
DataReceiverImpl->>TransferSession: appendMeasure(delay, duration, size)
end
DataReceiverImpl->>FileSystem: On receiveSync, exportMeasure() to CSV (mutex protected)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~40 minutes Possibly related PRs
Suggested reviewers
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. 📜 Recent review detailsConfiguration used: .coderabbit.yaml 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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)
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Nitpick comments (4)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (1)
104-124
: Consider making the CSV format more extensible.The current implementation assumes all connections have the same number of measurements. Consider adding the connection index to the header for clarity when dealing with multiple connections.
- outFile << "RequestID"; - for (size_t i = 0; i < mMeasures.size(); i++) - { - outFile << ",Delay(ms),Duration(ms),Bandwidth(Gbps)"; - } - outFile << '\n'; + outFile << "RequestID"; + for (size_t i = 0; i < mMeasures.size(); i++) + { + outFile << ",Conn" << i << "_Delay(ms)" + << ",Conn" << i << "_Duration(ms)" + << ",Conn" << i << "_Bandwidth(Gbps)"; + } + outFile << '\n';cpp/tensorrt_llm/batch_manager/dataTransceiver.h (1)
174-177
: Document the measurement methods.Consider adding Doxygen comments to explain the purpose and parameters of these public methods.
+ /// @brief Append a transfer measurement to the session + /// @param delay Time from last token (context) or arrival time (generation) in milliseconds + /// @param duration Transfer duration in milliseconds + /// @param size Transfer size in bytes void appendMeasure(double delay, double duration, size_t size); + /// @brief Export recorded measurements to a CSV file + /// @param outFile Output file stream to write CSV data + /// @param isContext True if this is a context phase transfer, false for generation phase // TODO: 1. use global id instead of context request id; 2. export to llm metrics instead of file void exportMeasure(std::ofstream& outFile, bool isContext) const;cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp (2)
59-63
: Consider adding error handling for file opening.The code doesn't handle potential file opening failures, which could occur due to permissions, disk space, or other I/O issues.
Consider adding basic error handling:
auto outputPath = getOutputPath("send"); if (!outputPath.empty()) { mMeasuresFile.open(outputPath.string()); + if (!mMeasuresFile.is_open()) + { + // Log warning about measurement file failure + } }
166-170
: Consider adding error handling for file opening.Similar to the sender implementation, this lacks error handling for potential file opening failures.
Consider adding basic error handling:
auto outputPath = getOutputPath("recv"); if (!outputPath.empty()) { mMeasuresFile.open(outputPath.string()); + if (!mMeasuresFile.is_open()) + { + // Log warning about measurement file failure + } }
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp
(2 hunks)cpp/tensorrt_llm/batch_manager/cacheFormatter.h
(0 hunks)cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
(1 hunks)cpp/tensorrt_llm/batch_manager/dataTransceiver.h
(2 hunks)cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp
(7 hunks)cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.h
(3 hunks)cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
(2 hunks)
💤 Files with no reviewable changes (1)
- cpp/tensorrt_llm/batch_manager/cacheFormatter.h
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{cpp,h,hpp,cc,cxx}
📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)
**/*.{cpp,h,hpp,cc,cxx}
: Closing braces of namespaces should have a comment saying the namespace it closes (e.g., } // namespace foo).
Prefer const or constexpr variables over #defines whenever possible.
A variable that is not modified after its initialization should be declared as const.
Except 0 (only used in comparison for checking signness/existence/emptiness) and nullptr, true, false, all other literals should only be used for variable initialization.
Use the Allman indentation style for braces.
Put the semicolon for an empty for or while loop in a new line.
The statement forming the body of a switch, while, do .. while or for statement shall be a compound statement (use brace-delimited statements).
If and else should always be followed by brace-delimited statements, even if empty or a single statement.
C++ filenames should use camel case with first letter lowercase (e.g., thisIsAFilename.cpp), and all files involved in the compilation of a target must have filenames that are case-insensitive unique.
All types (including class names) are camel case with uppercase first letter (e.g., FooBarClass).
Local variables, methods, and namespaces use camel case with first letter lowercase (e.g., localFooBar).
Non-magic-number global variables that are non-static and not defined in anonymous namespace use camel case prefixed by 'g' (e.g., gDontUseGlobalFoos).
Non-magic-number global variables that are static or defined in an anonymous namespace use camel case prefixed by 's' (e.g., sMutableStaticGlobal).
Locally visible static variable uses camel case with lowercase prefix 's' as the first letter of the name (e.g., static std::once_flag sFlag;).
Class member variables use camelcase prefixed with 'm' (e.g., mNbFooValues). Public member variables do not require the 'm' prefix but it is encouraged for clarity.
Constants (enumerations, global constants, static constants at class-scope, and function-scope magic-number/literal constants) are uppercase snakecase with prefix 'k...
Files:
cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp
cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.h
cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
cpp/tensorrt_llm/batch_manager/dataTransceiver.h
**/*.{cpp,h,cu,py}
📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)
All TensorRT-LLM Open Source Software code should contain an NVIDIA copyright header that includes the current year. This includes .cpp, .h, .cu, .py, and any other source files which are compiled or interpreted.
Files:
cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp
cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.h
cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp
cpp/tensorrt_llm/batch_manager/dataTransceiver.h
**/*.{h,hpp}
📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)
Use a preprocessor guard in header files. The guard name must have prefix TRTLLM_ followed by the filename, all in caps, and no trailing underscore.
Files:
cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.h
cpp/tensorrt_llm/batch_manager/dataTransceiver.h
🔇 Additional comments (17)
cpp/tensorrt_llm/batch_manager/cacheFormatter.cpp (2)
363-363
: LGTM! Measurement recording properly migrated to TransferSession.The replacement of
kvCacheMeasureHelper.appendKVCacheTransfer
withsession.appendMeasure
correctly preserves the measurement functionality while consolidating it within the TransferSession class.
715-715
: LGTM! Consistent measurement recording in receive path.The change maintains consistency with the send path by using
session.appendMeasure
for recording transfer metrics.cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.h (3)
26-26
: LGTM! Required header for file operations.The inclusion of
<fstream>
is necessary for the new file output stream members.
109-110
: LGTM! Proper thread safety for concurrent file access.The addition of both the file stream and mutex for DataReceiverImpl is appropriate for handling concurrent receives safely.
72-72
: Ignore mutex addition: DataSenderImpl already synchronizes file writesAll calls that write to mMeasuresFile in DataSenderImpl are performed under the mMtxForMap lock. For example, in sendSync (around line 149 of dataTransceiverImpl.cpp):
std::unique_lock<std::mutex> lk(mMtxForMap); if (mMeasuresFile.is_open()) { it->second.exportMeasure(mMeasuresFile, true); }This serializes all exportMeasure calls, ensuring thread‐safe writes. No additional mutex for mMeasuresFile is needed.
Likely an incorrect or invalid review comment.
cpp/tensorrt_llm/batch_manager/mlaCacheFormatter.cpp (3)
239-239
: LGTM! Consistent measurement recording implementation.The change correctly migrates the measurement recording to use
session.appendMeasure
, maintaining consistency with the base cache formatter implementation.
304-304
: LGTM! Proper connection selection for MLA receive operations.The addition of
pickRecvConnections
call ensures that the MLA formatter uses the appropriate subset of connections for receiving, which is important for the MLA-specific communication pattern.
436-436
: LGTM! Measurement recording properly implemented in receive path.The change maintains consistency with the send path and base formatter implementation.
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (1)
94-102
: LGTM! Efficient measurement recording with proper calculations.The bandwidth calculation correctly converts from bytes and milliseconds to Gbps, and the early return optimization avoids unnecessary work when recording is disabled.
cpp/tensorrt_llm/batch_manager/dataTransceiver.h (2)
100-105
: LGTM! Well-structured measurement data type.The
Measure
struct appropriately captures the key metrics for transfer performance analysis.
109-109
: Consider making recordMeasure parameter have a default value.Since measurement recording is optional, providing a default value would maintain backward compatibility and simplify usage when measurement is not needed.
TransferSession(std::vector<Connection const*> connections, DataContext dataContext, executor::DataTransceiverState const& selfState, executor::DataTransceiverState otherState, - runtime::BufferManager const& bufferManager, LlmRequest const* llmRequest = nullptr, bool recordMeasure = false) + runtime::BufferManager const& bufferManager, LlmRequest const* llmRequest = nullptr, bool recordMeasure = false)Wait, it already has a default value. This is correct as-is.
cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp (6)
24-25
: LGTM: Include addition follows best practices.The
<filesystem>
include is appropriately added for the new file path operations used ingetOutputPath
.
35-35
: LGTM: Namespace alias follows standard practices.The filesystem namespace alias is concise and commonly used.
109-111
: LGTM: Correct integration of measurement flag.The TransferSession constructor call correctly passes the measurement recording flag based on file availability.
150-153
: LGTM: Proper measurement export with thread safety.The export functionality is correctly implemented with mutex protection and appropriate timing before session cleanup.
235-236
: LGTM: Consistent measurement flag integration.The TransferSession constructor correctly incorporates the measurement recording flag, maintaining consistency with the sender implementation.
242-246
: LGTM: Excellent thread safety implementation.The dedicated mutex for file operations shows good understanding of thread safety requirements, and the lock scope is appropriately minimal.
Signed-off-by: zhengd-nv <[email protected]>
Signed-off-by: zhengd-nv <[email protected]>
/bot run |
PR_Github #14212 [ run ] triggered by Bot |
Signed-off-by: zhengd-nv <[email protected]>
Signed-off-by: zhengd-nv <[email protected]>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
♻️ Duplicate comments (1)
cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp (1)
37-48
: Add error handling for directory creation.The function doesn't handle potential failures in
fs::create_directories()
, which could throw exceptions or fail silently depending on the filesystem state.Consider adding error handling:
static fs::path getTransferOutputPath(char const* tag) { auto outputPath = common::getEnvKVCacheTransferOutputPath(); if (!outputPath.empty()) { auto rank = mpi::MpiComm::world().getRank(); auto path = fs::path(outputPath); - fs::create_directories(path); + std::error_code ec; + if (!fs::create_directories(path, ec) && ec) + { + // Log warning or handle error appropriately + return {}; + } return path / ("rank_" + std::to_string(rank) + "_" + tag + ".csv"); } return {}; }
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
(1 hunks)cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp
(5 hunks)cpp/tensorrt_llm/common/envUtils.cpp
(1 hunks)cpp/tensorrt_llm/common/envUtils.h
(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- cpp/tensorrt_llm/common/envUtils.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
- cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
⏰ 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 (3)
cpp/tensorrt_llm/common/envUtils.h (1)
79-79
: LGTM! Performance optimization by returning const reference.The change from returning
std::string
by value toconst std::string&
by reference avoids unnecessary string copying, which is a good performance optimization for environment variable accessors that typically return static strings.cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp (2)
24-24
: LGTM! Appropriate includes for filesystem operations.The addition of the
<filesystem>
header and the namespace alias are necessary and follow common conventions for the new file path operations.Also applies to: 35-35
239-250
: LGTM! Good thread safety implementation.The measurement export logic is well-implemented with proper mutex synchronization and lazy file opening. The use of
mMeasuresFileMutex
ensures thread safety for concurrent access to the measurement file.
Signed-off-by: zhengd-nv <[email protected]>
/bot run |
PR_Github #14275 [ run ] triggered by Bot |
PR_Github #14212 [ run ] completed with state |
PR_Github #14275 [ run ] completed with state |
/bot run |
PR_Github #14349 [ run ] triggered by Bot |
Summary by CodeRabbit
New Features
Refactor
Description
Test Coverage
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 thestage-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.