Skip to content

[CLI] Report KV cache memory usage in mlc_llm compile #3221

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
39 changes: 38 additions & 1 deletion python/mlc_llm/cli/model_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,12 +93,49 @@ def _report_memory_usage(metadata: Dict[str, Any], config: Union[Dict, ConfigBas
total_size = params_bytes + temp_func_bytes
logger.info(
"%s: %.2f MB (Parameters: %.2f MB. Temporary buffer: %.2f MB)",
green("Total memory usage without KV cache:"),
green("Total memory usage without KV cache"),
total_size / 1024 / 1024,
params_bytes / 1024 / 1024,
temp_func_bytes / 1024 / 1024,
)

# Compute KV cache size per token of context window.
if isinstance(config, ConfigBase):
config = asdict(config)
if (
"head_dim" in config
and "num_hidden_layers" in config
and "num_key_value_heads" in config
and "quantization" in metadata
):
quantization_type = metadata["quantization"]
dtype_bytes = None
if "f32" in quantization_type:
dtype_bytes = 4
elif "bf16" in quantization_type:
dtype_bytes = 2
elif "f16" in quantization_type:
dtype_bytes = 2
# TODO: If support quantized KV in future, need to change this # pylint: disable=fixme
if dtype_bytes is not None:
bytes_per_token = (
config["head_dim"]
* config["num_hidden_layers"]
* config["num_key_value_heads"]
* dtype_bytes
* 2 # 2 for key and value
)
logger.info(
"%s: %.2f MB per token in the context window",
green("KV cache size"),
bytes_per_token / 1024 / 1024,
)
logger.info(
"%s: %.2f MB",
green("Total memory usage with a 4K KV cache"),
(total_size + bytes_per_token * 4096) / 1024 / 1024,
)

logger.info(
"To reduce memory usage, "
"tweak `prefill_chunk_size`, `context_window_size` and `sliding_window_size`"
Expand Down
Loading