-
Notifications
You must be signed in to change notification settings - Fork 2k
[TRTLLM-8238][feat] Add EVS support for nano-v2-vlm #8024
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
Conversation
📝 WalkthroughPre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests
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.
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. Comment |
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 (7)
tensorrt_llm/inputs/__init__.py (1)
2-2: Avoid eager torch import: lazily re‑export EVS functions to cut import‑time overhead.Importing
compute_retained_tokens_count/compute_retention_maskhere bringstorchintotensorrt_llm.inputsimport path unconditionally. Prefer lazy export to keep lightweight imports for non‑EVS users.Apply this diff to remove the eager import:
-from .evs import compute_retained_tokens_count, compute_retention_maskThen add a lazy accessor near the bottom of the file (outside the selected range):
# Lazy re-exports to avoid importing torch during package import. def __getattr__(name): if name in ("compute_retained_tokens_count", "compute_retention_mask"): from .evs import compute_retained_tokens_count as _cnt, compute_retention_mask as _msk globals()["compute_retained_tokens_count"] = _cnt globals()["compute_retention_mask"] = _msk return globals()[name] raise AttributeError(name)As per coding guidelines
tensorrt_llm/inputs/evs.py (3)
69-74: Cast to float32 for stable cosine similarity.
cosine_similarityon bfloat16 (especially CPU) can be numerically unstable or unsupported on some backends. Cast embeds to float32 for the similarity step.Apply this diff:
- # Core EVS - similarity = torch.nn.functional.cosine_similarity(video_embeds[1:, ...], + # Core EVS + _emb = video_embeds.to(torch.float32) + similarity = torch.nn.functional.cosine_similarity(_emb[1:, ...], - video_embeds[:-1, ...], + _emb[:-1, ...], dim=-1)
81-88: Use topk instead of full sort; clamp k to valid range.
argsortis O(N log N).topkis faster and avoids slicing beyond array bounds if mis‑configured. Also early‑return if k<=0.Apply this diff:
- order = torch.argsort(dissimilarity_flat, - dim=-1, - descending=True, - stable=True) - retain_num_tokens = compute_retained_tokens_count(video_size, - spatial_merge_size, q) - topk_indices = order[:retain_num_tokens] + retain_num_tokens = compute_retained_tokens_count(video_size, + spatial_merge_size, q) + k = min(retain_num_tokens, dissimilarity_flat.numel()) + if k <= 0: + mask = torch.zeros_like(dissimilarity_flat, dtype=torch.bool) + return mask.view(-1) if flatten_output else mask.view(dissimilarity.size()) + _, topk_indices = torch.topk(dissimilarity_flat, k=k, largest=True, sorted=False)
61-68: Shape safety: guard reshape assumptions.If
T * (H//s) * (W//s) != video_embeds.size(0) * (video_embeds.size(1) if video_embeds.dim() > 2 else 1), this will error. Add an assertion to fail fast with a clear message.Proposed addition:
video_embeds = video_embeds.reshape( T, H // spatial_merge_size, W // spatial_merge_size, video_embeds.size(-1), ) + assert (H // spatial_merge_size) > 0 and (W // spatial_merge_size) > 0, ( + f"Invalid spatial merge: H={H}, W={W}, spatial_merge_size={spatial_merge_size}" + )tensorrt_llm/_torch/models/modeling_nanov2vlm.py (3)
27-28: Validate and clamp VIDEO_PRUNING_RATIO from env.Avoid crashes or over‑pruning when env var is malformed or out of [0,1).
Apply this diff:
-VIDEO_PRUNING_RATIO = float(os.getenv("TLLM_VIDEO_PRUNING_RATIO", "0")) +try: + VIDEO_PRUNING_RATIO = float(os.getenv("TLLM_VIDEO_PRUNING_RATIO", "0")) +except ValueError: + VIDEO_PRUNING_RATIO = 0.0 +# Clamp for safety +VIDEO_PRUNING_RATIO = max(0.0, min(VIDEO_PRUNING_RATIO, 0.99))
53-54: Make spatial_merge_size computation robust.Division and truncation can yield 0 or off‑by‑one for odd ratios. Validate result.
Apply this diff:
- self.spatial_merge_size = int(self.patch_size / self.downsample_ratio) + self.spatial_merge_size = int(round(self.patch_size / self.downsample_ratio)) + if self.spatial_merge_size <= 0: + raise ValueError(f"Invalid spatial_merge_size from patch_size={self.patch_size}, downsample_ratio={self.downsample_ratio}")Please verify that for your configs: (H // spatial_merge_size) * (W // spatial_merge_size) == self.num_image_token per frame.
17-18: Import surface is fine, but consider dependency direction.Keeping the EVS import local to this model (rather than package‑root re‑export) helps avoid global import side‑effects; if you keep the package re‑export, prefer the lazy import suggested in inputs/init.py.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
tensorrt_llm/_torch/models/modeling_nanov2vlm.py(9 hunks)tensorrt_llm/inputs/__init__.py(2 hunks)tensorrt_llm/inputs/evs.py(1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{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:
tensorrt_llm/inputs/__init__.pytensorrt_llm/_torch/models/modeling_nanov2vlm.pytensorrt_llm/inputs/evs.py
**/*.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/inputs/__init__.pytensorrt_llm/_torch/models/modeling_nanov2vlm.pytensorrt_llm/inputs/evs.py
**/*.{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:
tensorrt_llm/inputs/__init__.pytensorrt_llm/_torch/models/modeling_nanov2vlm.pytensorrt_llm/inputs/evs.py
🧬 Code graph analysis (2)
tensorrt_llm/inputs/__init__.py (1)
tensorrt_llm/inputs/evs.py (2)
compute_retained_tokens_count(14-32)compute_retention_mask(35-94)
tensorrt_llm/_torch/models/modeling_nanov2vlm.py (3)
tensorrt_llm/inputs/evs.py (1)
compute_retention_mask(35-94)tensorrt_llm/inputs/registry.py (1)
register_input_processor(412-438)tensorrt_llm/inputs/multimodal.py (1)
MultimodalParams(196-520)
⏰ 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 (2)
tensorrt_llm/inputs/__init__.py (1)
52-53: LGTM: public API updated with EVS utilities.Re‑exported symbols correctly included in all.
tensorrt_llm/_torch/models/modeling_nanov2vlm.py (1)
123-163: EVS masking path looks consistent with token budgeting.The mask is computed per video chunk and applied before final reshape; selection count matches the prompt’s inserted token budget. Good separation for non‑video paths.
Confirm that
mm_embed.shape == (T, num_image_token, hidden)for video and thatstart_idx += video_size[0]correctly walks over multiple videos in a single sample (i.e., dimension 0 equals total frames).
rakib-hasan
left a comment
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.
LGTM overall. Add some minor comments.
ce53755 to
c2ec907
Compare
|
Originally EVS was implemented for Qwen 2.5 VL which used thw notation that
went alongside with video embeddings.
Hence here is why original EVS routines are using a similar approach.
Yes, you can flatten mask to (T,) and embeddings to (T, C) if you want.
From my idea, we only need to consider which frames to be pruned, (pruned
the image tokens by frame-level)
I want to stress out - we prune tokens, not frames. Hope this visualization
bring some clarity to the discussion on how EVS works
[image: 1059072773_8.png]
чт, 9 жовт. 2025 р. о 15:26 Wanli Jiang ***@***.***> пише:
… ***@***.**** commented on this pull request.
------------------------------
In tensorrt_llm/_torch/models/modeling_nanov2vlm.py
<#8024 (comment)>:
> + # Use VIDEO_PRUNING_RATIO if not explicitly provided
+ if video_pruning_ratio is None:
+ video_pruning_ratio = VIDEO_PRUNING_RATIO
+
+ num_frames = len(video)
+
+ if video_pruning_ratio > 0:
+ num_tokens_per_frame = self.get_num_tokens_per_image(image=video[0],
+ **kwargs)
+ num_tokens_per_frame_list = [num_tokens_per_frame] * num_frames
+
+ # Total patches across all frames
+ total_num_tokens_base = sum(num_tokens_per_frame_list)
+
+ # Calculate total desired tokens after pruning
+ desired_num_tokens = int(total_num_tokens_base *
@BloodAxe <https://github.com/BloodAxe> After rethinking about the
pipeline, I am curious why the retion mask needs to consider the image
height/width.
From my idea, we only need to consider which frames to be pruned, (pruned
the image tokens by frame-level), so the retention mask might be with the
shape (T,)?
—
Reply to this email directly, view it on GitHub
<#8024 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAEB6YDZ7X4GEAD3X5WQTKD3WZH6JAVCNFSM6AAAAACHSHJ4WCVHI2DSMVQWIX3LMV43YUDVNRWFEZLROVSXG5CSMV3GSZLXHMZTGMJYG4ZDCNRSGM>
.
You are receiving this because you were mentioned.Message ID:
***@***.***>
|
c2ec907 to
50b6649
Compare
50b6649 to
19aa882
Compare
19aa882 to
f276bb6
Compare
39b6bfb to
46cd482
Compare
46cd482 to
6e1cd33
Compare
|
PR_Github #22335 [ run ] completed with state |
|
/bot run --disable-fail-fast |
|
PR_Github #22354 [ run ] triggered by Bot. Commit: |
|
PR_Github #22354 [ run ] completed with state |
d65aab3 to
1c481e9
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #22408 [ run ] triggered by Bot. Commit: |
|
PR_Github #22408 [ run ] completed with state |
1c481e9 to
3f9bfae
Compare
|
/bot run --disable-fail-fast |
|
PR_Github #22438 [ run ] triggered by Bot. Commit: |
|
PR_Github #22438 [ run ] completed with state |
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
Signed-off-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
3f9bfae to
73fef72
Compare
* Update EVS codes. Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com>
73fef72 to
eaf8a59
Compare
|
/bot reuse-pipeline |
|
PR_Github #22497 [ reuse-pipeline ] triggered by Bot. Commit: |
|
PR_Github #22497 [ reuse-pipeline ] completed with state |
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com> Signed-off-by: Chang Liu <9713593+chang-l@users.noreply.github.com> Co-authored-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com> Signed-off-by: Chang Liu <9713593+chang-l@users.noreply.github.com> Co-authored-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com> Signed-off-by: Chang Liu <9713593+chang-l@users.noreply.github.com> Co-authored-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
Signed-off-by: Wanli Jiang <35160485+Wanli-Jiang@users.noreply.github.com> Signed-off-by: Chang Liu <9713593+chang-l@users.noreply.github.com> Co-authored-by: Chang Liu <9713593+chang-l@users.noreply.github.com>
Summary by CodeRabbit
Description
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.
Details
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-listparameter 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.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip 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-pipelineReuse 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.