Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 32 additions & 6 deletions tensorrt_llm/_torch/auto_deploy/transform/library/sharding.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,9 @@ def scale_names(self) -> List[str]:
return ["weight_scale_inv"]

@staticmethod
def _compute_shard_bounds(weight_original_n: int, rank: int, world_size: int):
def _compute_shard_bounds(
weight_original_n: int, rank: int, world_size: int
) -> tuple[int, int]:
"""Compute (row_start, n_shard) matching torch.tensor_split semantics."""
n_big = weight_original_n % world_size
size_big = weight_original_n // world_size + 1
Expand Down Expand Up @@ -653,6 +655,19 @@ def _expand_scale_per_row(
else:
return scale[:, scale_indices]

@classmethod
def _get_sharded_scale(
cls,
scale: torch.Tensor,
weight_original_n: int,
dim: int,
rank: int,
world_size: int,
) -> torch.Tensor:
"""Shard a blocked FineGrained FP8 scale tensor for the local TP rank."""
row_start, n_shard = cls._compute_shard_bounds(weight_original_n, rank, world_size)
return cls._expand_scale_per_row(scale, dim, row_start, n_shard)

def shard_scales(
self,
dim: int,
Expand All @@ -665,8 +680,13 @@ def shard_scales(
weight_scale_inv: torch.Tensor,
) -> Dict[str, torch.Tensor]:
weight_original_n = weight_original_shape[dim]
row_start, n_shard = self._compute_shard_bounds(weight_original_n, rank, world_size)
sharded_scale = self._expand_scale_per_row(weight_scale_inv, dim, row_start, n_shard)
sharded_scale = self._get_sharded_scale(
weight_scale_inv,
weight_original_n,
dim,
rank,
world_size,
)
return {"weight_scale_inv": sharded_scale}

def shard_load_hook(
Expand All @@ -686,8 +706,13 @@ def shard_load_hook(
if scale_key in state_dict:
scale = state_dict[scale_key]
weight_original_n = weight_original_shape[dim]
row_start, n_shard = self._compute_shard_bounds(weight_original_n, rank, world_size)
state_dict[scale_key] = self._expand_scale_per_row(scale, dim, row_start, n_shard)
state_dict[scale_key] = self._get_sharded_scale(
scale,
weight_original_n,
dim,
rank,
world_size,
)


def _shard_fp4_weight_scale(
Expand Down Expand Up @@ -1875,7 +1900,8 @@ def _tp_shard_moe_scale(
)
elif scale_name == "weight_scale_inv":
f_split = partial(
FineGrainedFP8WeightShardingInfo._split_scale,
FineGrainedFP8WeightShardingInfo._get_sharded_scale,
weight_original_n=orig_weight_shape[dim],
dim=dim,
rank=rank,
world_size=world_size,
Expand Down
52 changes: 52 additions & 0 deletions tests/integration/defs/accuracy/test_llm_api_autodeploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,31 @@ def low_memory_overrides(config,
return config


def reduced_model_kwargs(num_hidden_layers: int,
model_path: str | None = None) -> dict:
"""Return model_kwargs to cap a model at ``num_hidden_layers`` layers.

Reduces peak memory so large models fit on a single GPU for pre-merge
smoke testing. The rest of the architecture (attention, MoE, SSM) is
preserved; only the layer count is truncated.

For models whose config derives layer count from a list attribute (e.g.
``layers_block_type`` in NemotronH), pass ``model_path`` so the list
is also truncated — otherwise the ``num_hidden_layers`` override has
no effect.
"""
overrides = {"num_hidden_layers": num_hidden_layers}
if model_path is not None:
from transformers import AutoConfig
hf_config = AutoConfig.from_pretrained(model_path,
trust_remote_code=True)
for attr in ("layers_block_type", ):
val = getattr(hf_config, attr, None)
if val is not None:
overrides[attr] = val[:num_hidden_layers]
return {"model_kwargs": overrides}


class TestLlama3_1_8B(LlmapiAccuracyTestHarness):
MODEL_NAME = "meta-llama/Llama-3.1-8B"
MODEL_PATH = hf_id_to_local_model_dir(MODEL_NAME)
Expand Down Expand Up @@ -598,6 +623,33 @@ def test_accuracy(self, model_id, world_size, enable_attention_dp,

print_memory_usage("after evaluation")

@skip_pre_hopper
@pytest.mark.skip_less_device_memory(40000)
@pytest.mark.parametrize("dtype", ["bf16", "fp8"])
def test_functional_small(self, dtype):
"""Single-GPU smoke test using a layer-reduced model.

Overrides num_hidden_layers so the 120B model fits on one GPU,
enabling pre-merge coverage of the full kernel dispatch path
(attention, MoE, SSM) without requiring a multi-GPU machine.
No accuracy threshold is checked — the truncated model is not
expected to produce meaningful text.
"""
model_path = self.MODEL_PATHS[dtype]
kwargs = {}
kwargs.update(
reduced_model_kwargs(num_hidden_layers=16, model_path=model_path))
with AutoDeployLLM(model=model_path,
tokenizer=model_path,
world_size=1,
yaml_extra=[self.CONFIG_YAML],
trust_remote_code=True,
**kwargs) as llm:
outputs = llm.generate(
["Hello, how are you?"],
sampling_params=SamplingParams(max_tokens=10))
assert len(outputs) == 1

@pytest.mark.skip_less_device_memory(180000)
@pytest.mark.parametrize("world_size", [4, 8])
def test_mtp(self, world_size):
Expand Down
2 changes: 2 additions & 0 deletions tests/integration/test_lists/qa/llm_function_core.txt
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,8 @@ accuracy/test_llm_api_autodeploy.py::TestNemotronSuperV3::test_accuracy[fp8-4-at
accuracy/test_llm_api_autodeploy.py::TestNemotronSuperV3::test_accuracy[nvfp4-1-attn_dp_off-trtllm]
accuracy/test_llm_api_autodeploy.py::TestNemotronSuperV3::test_accuracy[nvfp4-4-attn_dp_on-trtllm]
accuracy/test_llm_api_autodeploy.py::TestNemotronSuperV3::test_mtp[4]
accuracy/test_llm_api_autodeploy.py::TestNemotronSuperV3::test_functional_small[bf16]
accuracy/test_llm_api_autodeploy.py::TestNemotronSuperV3::test_functional_small[fp8]
accuracy/test_llm_api_autodeploy.py::TestNemotronV2::test_auto_dtype[False]
accuracy/test_llm_api_autodeploy.py::TestNemotronV2::test_auto_dtype[True]
accuracy/test_llm_api_autodeploy.py::TestNemotronV2::test_fp8[True]
Expand Down
2 changes: 2 additions & 0 deletions tests/integration/test_lists/test-db/l0_b200.yml
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,8 @@ l0_b200:
- accuracy/test_llm_api_autodeploy.py::TestNemotronNanoV3::test_accuracy[fp8-1-trtllm]
- accuracy/test_llm_api_autodeploy.py::TestNemotronNanoV3::test_accuracy[nvfp4-1-trtllm]
- accuracy/test_llm_api_autodeploy.py::TestNemotronSuperV3::test_accuracy[nvfp4-1-attn_dp_off-trtllm]
- accuracy/test_llm_api_autodeploy.py::TestNemotronSuperV3::test_functional_small[bf16]
- accuracy/test_llm_api_autodeploy.py::TestNemotronSuperV3::test_functional_small[fp8]
- unittest/auto_deploy/singlegpu/compile
- unittest/auto_deploy/singlegpu/custom_ops
- unittest/auto_deploy/singlegpu/models
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,11 +125,11 @@ def forward(self, x):
pytest.param(576, 4, 128, id="non_aligned_uneven_n-N576-ws4"),
],
)
def test_finegrained_fp8_expand_scale_per_row(weight_original_n, world_size, block_n):
"""Tests _compute_shard_bounds and _expand_scale_per_row for all shard boundary cases.
def test_finegrained_fp8_get_sharded_scale(weight_original_n, world_size, block_n):
"""Tests FineGrained FP8 scale sharding for all shard boundary cases.

Verifies that _compute_shard_bounds matches torch.tensor_split semantics and that
_expand_scale_per_row assigns the correct scale block to every weight row:
Verifies that _get_sharded_scale assigns the correct scale block to every
weight row:
- Aligned shards: compact scale slice with block_n preserved for the FP8 GEMM kernel.
- Non-aligned shards: per-row expansion so each weight row gets its correct block index.
- N not divisible by block_n: clamp to last scale row avoids out-of-bounds indexing.
Expand All @@ -139,23 +139,18 @@ def test_finegrained_fp8_expand_scale_per_row(weight_original_n, world_size, blo
chunks = torch.tensor_split(torch.arange(weight_original_n), world_size)

for rank in range(world_size):
row_start, n_shard = FineGrainedFP8WeightShardingInfo._compute_shard_bounds(
weight_original_n, rank, world_size
)
# _compute_shard_bounds must match torch.tensor_split
assert n_shard == len(chunks[rank]), (
f"rank={rank}: n_shard={n_shard} != {len(chunks[rank])}"
)
if len(chunks[rank]) > 0:
assert row_start == int(chunks[rank][0]), (
f"rank={rank}: row_start={row_start} != {int(chunks[rank][0])}"
)

shard_rows = chunks[rank]
n_shard = len(shard_rows)
if n_shard == 0:
continue

sharded = FineGrainedFP8WeightShardingInfo._expand_scale_per_row(
scale, dim=0, row_start=row_start, n_shard=n_shard
row_start = int(shard_rows[0])

sharded = FineGrainedFP8WeightShardingInfo._get_sharded_scale(
scale,
weight_original_n=weight_original_n,
dim=0,
rank=rank,
world_size=world_size,
)

aligned = (row_start % block_n == 0) and (n_shard % block_n == 0)
Expand Down
Loading