Implement a function that estimates the memory footprint of the Key-Value (KV) cache used during autoregressive inference in Transformer-based language models.
During text generation, Transformers cache the Key and Value projections from previous tokens so they don't need to be recomputed at each decoding step. Understanding how large this cache grows is essential for planning GPU memory budgets and choosing sequence length limits.
model_config: A dictionary with the following keys:
'num_layers': Number of transformer layers (int)'num_attention_heads': Number of query attention heads (int)'num_kv_heads' (optional): Number of key/value heads. If not present, assume it equals num_attention_heads (standard multi-head attention)'hidden_size': Model hidden dimension (int)'dtype_bytes': Number of bytes per parameter element (e.g., 2 for FP16, 4 for FP32, 1 for INT8)batch_size: Number of sequences being processed simultaneously (int)seq_len: Number of tokens stored in the cache (int)Return a dictionary with:
'kv_cache_elements': Total number of scalar elements stored in the KV cache (int)'kv_cache_size_bytes': Total memory in bytes (int)'kv_cache_size_mb': Total memory in megabytes (rounded to 4 decimal places), using 1 MB = 1024 * 1024 bytes'per_layer_size_mb': Memory per layer in megabytes (rounded to 4 decimal places)'per_token_size_kb': Memory per token (for a single sequence, not multiplied by batch) in kilobytes (rounded to 4 decimal places), using 1 KB = 1024 bytesNote: The head dimension is derived from the hidden size and the number of query attention heads.