-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[None][feat] Refactor llama4 for multimodal encoder IFB #6844
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
📝 WalkthroughWalkthroughIntroduces a disaggregated multimodal path via TLLM_MULTIMODAL_DISAGGREGATED, adds Llama4VisionEncoder to handle vision feature extraction, updates Llama4ForConditionalGeneration to use the encoder conditionally, adjusts Llama4InputProcessor to pass pixel_values instead of embeddings, and updates documentation to reflect Encoder IFB support for Llama 4. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant U as User/Input
participant IP as Llama4InputProcessor
participant M as Llama4ForConditionalGeneration
participant E as Llama4VisionEncoder
participant T as Text Model
Note over M: DISAGG=0 (default)
U->>IP: Provide text + images
IP->>M: tokens + multimodal_params (pixel_values)
M->>E: forward(multimodal_params)
E->>M: mm_embeds (image_features)
M->>T: generate(tokens, mm_embeds)
T-->>U: outputs
sequenceDiagram
autonumber
participant U as User/Input
participant IP as Llama4InputProcessor
participant M as Llama4ForConditionalGeneration
participant T as Text Model
Note over M: DISAGG=1 (disaggregated)
U->>IP: Provide text + images
IP->>M: tokens + multimodal_embedding (passthrough) or params
M->>T: generate(tokens, multimodal_embedding)
T-->>U: outputs
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
✨ 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/Issue comments)Type Other keywords and placeholders
Status, 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: 4
🔭 Outside diff range comments (1)
tensorrt_llm/_torch/models/modeling_llama.py (1)
1219-1232
: Potential memory leak: Store full_model_config as instance variable.The
full_model_config
is created but only used locally. If it's needed for themm_encoder
, it should be stored as an instance variable to ensure proper lifecycle management.def __init__( self, model_config: ModelConfig[Llama4Config], ): # Keep a reference to the full config (with vision) before switching to text-only - full_model_config = model_config + self.full_model_config = model_config # TODO: figure out a better way to handle multimodality. model_config = copy.copy(model_config) architectures = model_config.pretrained_config.architectures model_config.pretrained_config = model_config.pretrained_config.text_config model_config.pretrained_config.architectures = architectures super().__init__(Llama4Model(model_config), model_config) self.preload_weight_modules = self.model.preload_weight_modules if not DISAGG: - self.mm_encoder = Llama4VisionEncoder(full_model_config) + self.mm_encoder = Llama4VisionEncoder(self.full_model_config)
🧹 Nitpick comments (1)
tensorrt_llm/_torch/models/modeling_llama.py (1)
48-49
: Consider making the environment variable name more descriptive.The environment variable
TLLM_MULTIMODAL_DISAGGREGATED
controls a critical architectural decision. Consider:
- Adding documentation about what "disaggregated" means in this context
- Using a more descriptive name like
TLLM_LLAMA4_USE_EXTERNAL_VISION_ENCODER
-DISAGG = os.getenv('TLLM_MULTIMODAL_DISAGGREGATED', '0') == '1' +# Controls whether to use an external vision encoder (disaggregated mode) +# When False (default): Use dedicated mm_encoder (Llama4VisionEncoder) for vision processing +# When True: Use existing multimodal_embedding tokens path +DISAGG = os.getenv('TLLM_MULTIMODAL_DISAGGREGATED', '0') == '1'
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
docs/source/reference/multimodal-feature-support-matrix.md
(1 hunks)tensorrt_llm/_torch/models/modeling_llama.py
(8 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py
📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)
**/*.py
: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else
Files:
tensorrt_llm/_torch/models/modeling_llama.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}
📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)
Prepend NVIDIA copyright header (current year) to all source files
Files:
tensorrt_llm/_torch/models/modeling_llama.py
🔇 Additional comments (3)
docs/source/reference/multimodal-feature-support-matrix.md (1)
9-9
: LGTM! Documentation update aligns with code changes.The documentation correctly reflects that Llama 4 now supports Encoder IFB, which is consistent with the introduction of the disaggregated multimodal pathway via
Llama4VisionEncoder
in the implementation.tensorrt_llm/_torch/models/modeling_llama.py (2)
19-19
: MultimodalParams import is correctThe class
MultimodalParams
is defined intensorrt_llm/inputs/multimodal.py
(line 152), so importing it directly fromtensorrt_llm.inputs.multimodal
is valid. No changes are needed.
- Definition location:
tensorrt_llm/inputs/multimodal.py:152
- No export needed in
__init__.py
when importing directly from the module
1273-1283
: Thread safety concern with temporary attribute manipulation.The
load_weights
method temporarily removes and restores themm_encoder
attribute. This pattern could cause issues in multi-threaded scenarios or if an exception occurs.Consider using a context manager pattern for safer attribute manipulation:
+ @contextlib.contextmanager + def _temporarily_remove_mm_encoder(self): + """Context manager to temporarily remove mm_encoder during weight loading.""" + had_mm_encoder = hasattr(self, "mm_encoder") + saved_mm_encoder = getattr(self, "mm_encoder", None) + if had_mm_encoder: + delattr(self, "mm_encoder") + try: + yield + finally: + if had_mm_encoder: + self.mm_encoder = saved_mm_encoder + def load_weights(self, weights: Dict, weight_mapper: BaseWeightMapper): - # Temporarily detach mm_encoder so the TRT-LLM loader doesn't try to load it - had_mm_encoder = hasattr(self, "mm_encoder") - saved_mm_encoder = getattr(self, "mm_encoder", None) - if had_mm_encoder: - delattr(self, "mm_encoder") - try: + with self._temporarily_remove_mm_encoder(): super().load_weights(weights, weight_mapper) - finally: - if had_mm_encoder: - self.mm_encoder = saved_mm_encoderNote: You'll need to add
import contextlib
at the top of the file.Likely an incorrect or invalid review 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.
Thx for the work.
Signed-off-by: Dongfeng Yu <[email protected]>
Signed-off-by: Dongfeng Yu <[email protected]>
Signed-off-by: Dongfeng Yu <[email protected]>
94b0263
to
f0f9abe
Compare
Signed-off-by: Dongfeng Yu <[email protected]>
/bot run |
PR_Github #16628 [ run ] triggered by Bot |
PR_Github #16628 [ run ] completed with state |
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.
We should also note the addition of vision support with Llama4 in the supported models table (currently just "L", should be made "L+V")
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.
@chang-l pointed out that the "L+I" update has already been made here:
| `Llama4ForConditionalGeneration` | Llama 4 | `meta-llama/Llama-4-Scout-17B-16E-Instruct` | L + I | |
Signed-off-by: Dongfeng Yu <[email protected]>
Following #6478
Make vision model standalone.
Summary by CodeRabbit
New Features
Documentation
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.