-
Notifications
You must be signed in to change notification settings - Fork 1.8k
[TRTLLM-8201][feat] TP sharding of Mamba layers #8548
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?
[TRTLLM-8201][feat] TP sharding of Mamba layers #8548
Conversation
Signed-off-by: greg-kwasniewski1 <[email protected]>
Signed-off-by: greg-kwasniewski1 <[email protected]>
Signed-off-by: greg-kwasniewski1 <[email protected]>
Signed-off-by: greg-kwasniewski1 <[email protected]>
Signed-off-by: greg-kwasniewski1 <[email protected]>
Signed-off-by: greg-kwasniewski1 <[email protected]>
Signed-off-by: greg-kwasniewski1 <[email protected]>
|
||
|
||
def _update_view_nodes(node: Node) -> None: | ||
def _validate_sharded_shapes( |
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.
can we simplify this function if you assume upstream of this transform there is something that standardizes the graph representation to look like this:
TensorRT-LLM/tensorrt_llm/_torch/auto_deploy/models/patches/bamba.py
Lines 22 to 144 in dcfd3ef
def _bamba_mixer_torch_forward( | |
self, | |
input_states, | |
cache_params: Optional[HybridMambaAttentionDynamicCache] = None, | |
cache_position: Optional[torch.LongTensor] = None, | |
attention_mask: Optional[torch.Tensor] = None, | |
): | |
# `input_states` is of shape `[B, T, hidden_dim]`, and during generate, each successive call | |
# will have T = T + 1. | |
batch_size, seq_len, _ = input_states.shape | |
dtype = input_states.dtype | |
# 1. Gated MLP's linear projection | |
input_states = apply_mask_to_padding_states(input_states, attention_mask) | |
projected_states = self.in_proj(input_states) | |
gate, hidden_states_B_C, dt = projected_states.split( | |
[self.intermediate_size, self.conv_dim, self.num_heads], dim=-1 | |
) | |
use_caching = cache_params is not None | |
# 2. Convolution sequence transformation (cached/uncached handled inside the op) | |
if use_caching: | |
# Prepare dense metadata for cached flattened op | |
seq_len_t = torch.full((batch_size,), seq_len, device=input_states.device, dtype=torch.int) | |
seq_start_t = torch.arange( | |
0, batch_size * seq_len, seq_len, device=input_states.device, dtype=torch.int | |
) | |
slot_idx_t = torch.arange(batch_size, device=input_states.device, dtype=torch.long) | |
if use_caching: | |
hidden_states_B_C = self.act( | |
torch.ops.auto_deploy.torch_cached_causal_conv1d( | |
# INPUTS | |
hidden_states_B_C, | |
self.conv1d.weight, | |
self.conv1d.bias, | |
# METADATA | |
seq_len_t, | |
seq_start_t, | |
slot_idx_t, | |
# CACHES | |
cache_params.conv_states[self.layer_idx], | |
# CONSTANTS | |
self.conv1d.stride[0], | |
self.conv1d.padding[0], | |
self.conv1d.dilation[0], | |
self.conv1d.groups, | |
self.conv1d.padding_mode, | |
) | |
) | |
else: | |
hidden_states_B_C = self.act( | |
torch.ops.auto_deploy.torch_causal_conv1d( | |
hidden_states_B_C, | |
self.conv1d.weight, | |
self.conv1d.bias, | |
self.conv1d.stride[0], | |
self.conv1d.padding[0], | |
self.conv1d.dilation[0], | |
self.conv1d.groups, | |
self.conv1d.padding_mode, | |
) | |
) | |
hidden_states_B_C = apply_mask_to_padding_states(hidden_states_B_C, attention_mask) | |
hidden_states, B, C = torch.split( | |
hidden_states_B_C, | |
[ | |
self.intermediate_size, | |
self.n_groups * self.ssm_state_size, | |
self.n_groups * self.ssm_state_size, | |
], | |
dim=-1, | |
) | |
# 3. SSM transformation | |
A = -torch.exp(self.A_log.float()) # [num_heads] | |
if use_caching: | |
# Use new flattened cached op for both cache updates and outputs | |
y = torch.ops.auto_deploy.torch_cached_ssm_transform( | |
# INPUTS | |
hidden_states=hidden_states.view(batch_size, seq_len, -1, self.head_dim), | |
A=A, | |
B=B.view(batch_size, seq_len, -1, self.ssm_state_size), | |
C=C.view(batch_size, seq_len, -1, self.ssm_state_size), | |
D=self.D, | |
dt=dt, | |
dt_bias=self.dt_bias, | |
# METADATA | |
seq_len=seq_len_t, | |
seq_start=seq_start_t, | |
slot_idx=slot_idx_t, | |
# CACHES | |
ssm_state_cache=cache_params.ssm_states[self.layer_idx], | |
# CONSTANTS | |
time_step_limit=list(self.time_step_limit), | |
chunk_size=self.chunk_size, | |
) | |
else: | |
y = torch.ops.auto_deploy.torch_ssm_transform( | |
hidden_states=hidden_states.view(batch_size, seq_len, -1, self.head_dim), | |
A=A, | |
B=B.view(batch_size, seq_len, -1, self.ssm_state_size), | |
C=C.view(batch_size, seq_len, -1, self.ssm_state_size), | |
D=self.D, | |
dt=dt, | |
dt_bias=self.dt_bias, | |
time_step_limit=list(self.time_step_limit), | |
chunk_size=self.chunk_size, | |
) | |
y = y.view(batch_size, seq_len, -1) | |
scan_output = self.norm(y, gate) | |
# end ssd naive | |
# !! This is the end of the uncached code path. | |
# 4. Final linear projection | |
contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size] | |
return contextualized_states |
From a first glance, it seems we only need to handle the split node then but not the view nodes
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.
View node update was there already for some previous transformer models, i don't remember which one. So while Mamba needs split nodes to update, other models need view nodes, I think the "shape cleaning" should be done in one place instead of a separate function for each model family.
} | ||
|
||
|
||
AutoModelForCausalLMFactory._set_sharding_config = _set_sharding_config_patched |
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.
will require clean-up
layer_type=LayerType.MAMBA, | ||
fused_weight_dims=config_params.get("fused_weight_dims"), | ||
) | ||
) |
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.
In my mind, a complete specification for col-row shard of a Mamba-like layer has 4 entries in the sharding_config
that are passed to the sharding_executor
:
- column-wise with appropriate
fused_weight_dims
for thein_proj
- column-wise with appropriate
fused_weight_dims
fortorch_causal_conv1d
- column-wise for the weight on the gated rms norm
- row-wise for
out_proj
More specifically, I don't think we should add special handling for mamba via something like the layer_type
argument.
Now there is two ways we can get these four entries:
- Sharding heuristic that analyzes the model and correctly configures those four entries. Seems like you already have something like this here. This can be repurposed as
detect_mamba_sharding
to add the appropriate entries into the sharding_config - Manual sharding config: this is pending your [TRTLLM-6342][feat] Support custom sharding config source #8153 PR and so might not be a good alternative for now. Even with 2. in place though, it wouldn't be the ideal solution since the manual sharding config would have to specify the
fused_weight_dims
which is not ideal either. So since we have 1. in place we can go with this option for now.
In terms of getting this merged to main
I would suggest the following split:
- Ability for the sharding executor to understand TPShardingInfo with fused_weight_dims. Moreover, we probably also need to ensure that causal conv and element-wise multiplication from the gated rms norm can be supported in the TPShardingInfo specification. + Unit tests
- Add a new sharding heuristic for the mamba layer that can auto-detect the correct sharding_config entry for mamba-like layers
In the meantime, the current branch can be used to test+benchmark Nemotron nano-v3. So please make sure it remains available for testing
# Split fused weights, apply TP sharding to each, then concatenate back | ||
sharded_weight = torch.cat( | ||
[split_tensor(w) for w in torch.split(weight_tensor, fused_weight_dims, dim=dim)], | ||
dim=dim, | ||
) |
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.
seems you should be able to just f_split
as defined below to get the sharded_weight
for either case
return self.predefined_config | ||
|
||
|
||
def _append_simple_shard( |
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.
what happened to this function?
Supports head parallelism for Mamba layers.
Currently, it assumes a rigid module structure:
When applied it:
Sharding mamba layers is currently supported only through factory sharding, by specifying
mamba
forin_proj
linear node.@coderabbitai summary
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.
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.