### Get attention decode and prefill MFU Source: https://github.com/alibaba/infersim Shows how to use get_attn_decode_perf and get_attn_prefill_mfu from mfu.mfu. For decode, if an exact bench point exists, measured latency is returned; otherwise it returns (mfu, None) and uses an analytical path. The example prints the measured latency in microseconds or the analytical MFU, and prints the prefill attention MFU. ```python from config.model_config import ModelConfig from mfu.mfu import get_attn_decode_perf, get_attn_prefill_mfu config = ModelConfig("hf_configs/deepseek_v3_config.json") # Decode: measured latency when an exact bench point exists, else (mfu, None) mfu, latency = get_attn_decode_perf( config, target_bs=64, kv_len=2048, device_type="H800", use_fp8_kv=False, tp_size=1, ) if latency is not None: print(f"measured latency: {latency * 1e6:.2f} us (mfu {mfu})") else: print(f"analytical path with mfu {mfu}") prefill_mfu = get_attn_prefill_mfu(config, seq_len=4096, device_type="H800", tp_size=1) print(f"prefill attn mfu: {prefill_mfu}") ``` -------------------------------- ### Example: using gpu_map and TFLOPS_TO_GFLOPS Source: https://github.com/alibaba/infersim Shows how to access a GPU profile from gpu_map and compute latency from GFLOPs. Indexing with an unknown key raises KeyError; the --device-type argparse choices restrict this at the CLI. ```python from hardware.gpu import gpu_map, TFLOPS_TO_GFLOPS gpu = gpu_map["H800"] print(gpu.fp16_tflops) # 989 print(gpu.mem_bw) # 3430 * 0.8 print(gpu.sm_version) # 90 # GFLOPs -> seconds: gflops / (tflops * 1000 * mfu) gflops = 4.03e0 latency_s = gflops / (gpu.fp16_tflops * TFLOPS_TO_GFLOPS * 0.35) print(f"{latency_s * 1e6:.2f} us") ``` -------------------------------- ### Example: load_moe_weights_time in decode loop Source: https://github.com/alibaba/infersim Demonstrates using load_moe_weights_time directly in a decode loop for a Qwen3-30B-A3B config on an H20 GPU. Prints the MoE weight load time in microseconds. ```python from config.model_config import ModelConfig from hardware.gpu import gpu_map, TFLOPS_TO_GFLOPS from params.params import load_moe_weights_time config = ModelConfig("hf_configs/qwen3-30B-A3B_config.json") gpu = gpu_map["H20"] t_load = load_moe_weights_time( config, use_fp8=False, gpu=gpu, num_gpus=4, tp_size=1, num_tokens=100, ) print(f"MoE weight load: {t_load * 1e6:.2f} us") ``` -------------------------------- ### Run decode.sh for Qwen3-30B-A3B simulation Source: https://github.com/alibaba/infersim/blob/main/README.md Executes the example script to simulate decoding for the Qwen3-30B-A3B model on H20 GPUs with world size 4. The output shows detailed metrics including model weights, KV cache usage, FLOPs, and decoding performance (TPOT 38.00 ms, throughput 2632 TGS). ```bash $ bash example/qwen3-30B-A3B/decode.sh ``` -------------------------------- ### Basic decode simulation of a MoE model using main.py Source: https://github.com/alibaba/infersim Runs a decode-only simulation for a Qwen3-30B-A3B MoE model on H20 with world size 4 and decode batch size 100. Mirrors the decode.sh example by constructing an argparse.Namespace with the same flags and calling main(args). ```python # Equivalent of: python3 main.py --config-path hf_configs/qwen3-30B-A3B_config.json \ # --device-type H20 --world-size 4 --decode-bs 100 --decode-only import argparse from main import main parser = argparse.ArgumentParser() # In practice the flags come from parser.parse_args(); this mirrors the # decode.sh example: args = argparse.Namespace( config_path="hf_configs/qwen3-30B-A3B_config.json", device_type="H20", world_size=4, tp_size=1, num_nodes=1, max_prefill_tokens=4096, prefill_attn_mfu=None, prefill_moe_mfu=None, decode_bs=100, target_tgs=2560, target_tpot=50, target_isl=4096, target_osl=2048, use_fp8_gemm=False, use_fp8_kv=False, decode_scheduler_overhead_ms=None, enable_shared_expert_overlap=False, enable_deepep=False, enable_tbo=False, sm_ratio=108 / 132, prefill_only=False, decode_only=True, ) main(args) ``` -------------------------------- ### Example: compute attention and expert parameter sizes Source: https://github.com/alibaba/infersim Shows how to compute attention layer and expert parameter sizes for a given config, using fp8 and tensor parallelism. Prints the sizes in MB and the expected active local experts for a batch size of 64. ```python from config.model_config import ModelConfig from hardware.gpu import gpu_map from params.params import ( get_attn_params_size, get_expert_params_size, get_expected_active_experts, ) config = ModelConfig("hf_configs/deepseek_v3_config.json") tp_size, world_size = 1, 128 attn_bytes = get_attn_params_size(config, use_fp8=True, tp_size=tp_size) expert_bytes = get_expert_params_size(config, use_fp8=True, tp_size=tp_size) ep_size = world_size // tp_size print(f"attn layer: {attn_bytes / 1024**2:.1f} MB | one expert: {expert_bytes / 1024**2:.1f} MB") active = get_expected_active_experts(config, world_size, tp_size, num_tokens=64) print(f"expected active local experts for bs=64: {active:.1f} / {config.num_routed_experts / ep_size:.1f}") ``` -------------------------------- ### Example usage of sparse_mla_fp8 with H800 Source: https://github.com/alibaba/infersim Shows how to load a model config and call the simulator with an SM-90 GPU (H800). Prints the estimated time and TFLOPS. ```python from kernel_sim.sparse_mla_fp8 import sparse_mla_fp8 from config.model_config import ModelConfig config = ModelConfig("hf_configs/deepseek_v3.2_config.json") time_ms, tflops = sparse_mla_fp8( batch_size=128, num_heads=config.num_attention_heads, seq_len=4096, topk=config.index_topk, dim=config.kv_lora_rank, gpu_type="H800", # SM 90 — supported dim_rope=config.qk_rope_head_dim, ) print(f"Time: {time_ms:.3f} ms | TFLOPS: {tflops:.3f}") ``` -------------------------------- ### Example: compute total per-token GFLOPs for DeepSeek V3 Source: https://github.com/alibaba/infersim Loads a ModelConfig from a JSON file, computes attention core and other FLOPs with absorb=True, MoE GFLOPs, then sums and multiplies by number of hidden layers to print total per-token GFLOPs. ```python from config.model_config import ModelConfig from flops.flops import get_attn_gflops, get_moe_gflops config = ModelConfig("hf_configs/deepseek_v3_config.json") attn_core, other = get_attn_gflops(config, avg_context_len=4096, tp_size=1, absorb=True) moe = get_moe_gflops(config, tp_size=1) total = (attn_core + other + moe) * config.num_hidden_layers print(f"per-token total: {total:.2f} GFLOPs") ``` -------------------------------- ### Decode path example using create_linear_attn Source: https://github.com/alibaba/infersim Shows how to create a linear attention module and benchmark its decode path. Uses ModelConfig with a Qwen3.5 config file, enables FP8 GEMM, and measures decode core and other latencies on H20. ```python from config.model_config import ModelConfig from layers.linear_attn import create_linear_attn config = ModelConfig("hf_configs/qwen3.5-35B-A3B_config.json") linear_attn = create_linear_attn(config, use_fp8_gemm=True, tp_size=1) # Decode: states bytes from kvcache.get_states_size from kvcache.kvcache import get_states_size states_bytes = get_states_size(config) t_core = linear_attn.decode_attn_core(bs=224, states_bytes=states_bytes, device_type="H20") t_others = linear_attn.decode_attn_others(bs=224, device_type="H20") print(f"linear attn decode: {1e6 * (t_core + t_others):.2f} us") ``` -------------------------------- ### Example: raw GEMM FLOPs and absorbed vs non-absorbed MLA comparison Source: https://github.com/alibaba/infersim Shows raw FLOP count for a custom GEMM using gemm_flops, and compares absorbed vs non-absorbed MLA attention core GFLOPs for the same config. Prints both values. ```python from config.model_config import ModelConfig from flops.flops import gemm_flops, get_attn_gflops # Raw FLOP count for a custom GEMM flops = gemm_flops(m=4096, n=2048, k=7168) # Non-absorbed MLA variant for comparison config = ModelConfig("hf_configs/deepseek_v3_config.json") absorbed = get_attn_gflops(config, 4096, 1, absorb=True) noabsorb = get_attn_gflops(config, 4096, 1, absorb=False) print(f"absorbed core {absorbed[0]:.2f} GFLOPs vs non-absorbed {noabsorb[0]:.2f} GFLOPs") ``` -------------------------------- ### Example: MLA KV cache size for DeepSeek V3 Source: https://github.com/alibaba/infersim Shows how to compute per-token KV cache size for an MLA model (DeepSeek V3) with and without FP8. Demonstrates that TP does not shard the MLA KV cache. ```python from config.model_config import ModelConfig from kvcache.kvcache import get_kvcache_size config = ModelConfig("hf_configs/deepseek_v3_config.json") # MLA: TP does not shard the KV cache bytes_bf16 = get_kvcache_size(config, use_fp8=False, tp_size=8) bytes_fp8 = get_kvcache_size(config, use_fp8=True, tp_size=8) print(f"MLA KV per token: {bytes_bf16} B (bf16) / {bytes_fp8} B (fp8)") ``` -------------------------------- ### Example: Per-request cache footprint for Qwen3.5-35B-A3B Source: https://github.com/alibaba/infersim Computes per-request cache footprint for a hybrid model: full-attention layers' KV over the context plus GDN recurrent states. Uses get_kvcache_size and get_states_size. ```python from config.model_config import ModelConfig from kvcache.kvcache import get_kvcache_size, get_states_size config = ModelConfig("hf_configs/qwen3.5-35B-A3B_config.json") kv_per_token = get_kvcache_size(config, use_fp8=False, tp_size=1) states = get_states_size(config) # GDN recurrent state context_len = 4096 + 2048 # Per-request cache footprint: full-attn layers' KV over the context plus states full_attn_kv = kv_per_token / config.num_hidden_layers * config.num_full_attn_layers * context_len print(f"full-attn KV per request: {full_attn_kv / 1024**2:.2f} MB") print(f"GDN states per request: {states / 1024**2:.2f} MB") print(f"total: {(full_attn_kv + states) / 1024**2:.2f} MB") ``` -------------------------------- ### Prefill path example with missing bench data handling Source: https://github.com/alibaba/infersim Benchmarks the prefill path with FP8 GEMM disabled. The bench-data CSV name embeds the GDN shape and get_linear_attn_prefill_latency asserts the file exists; missing files raise AssertionError, which is caught and printed. ```python from config.model_config import ModelConfig from layers.linear_attn import create_linear_attn config = ModelConfig("hf_configs/qwen3.5-122B-A10B_config.json") linear_attn = create_linear_attn(config, use_fp8_gemm=False, tp_size=1) # The bench-data CSV name embeds the GDN shape: # bench_data/gdn/prefill/{device}/{conv_kdim}-{num_key_heads}-{key_head_dim}-{num_value_heads}-{value_head_dim}.csv # get_linear_attn_prefill_latency asserts the file exists. try: t = linear_attn.prefill_attn_core(seq_len=4096, states_bytes=0, device_type="H20") print(f"{1e6 * t:.2f} us") except AssertionError as e: print("bench data missing:", e) ``` -------------------------------- ### Error handling for invalid MFU override and unsupported overlap flag Source: https://github.com/alibaba/infersim Shows two error-handling scenarios: mfu_value rejects an invalid MFU override with argparse.ArgumentTypeError, and main() raises ValueError when enable_shared_expert_overlap is used on a non-Qwen3.5 hybrid model. The second example uses a Qwen3-8B config that is not a hybrid MoE. ```python import argparse from main import mfu_value, main # 1) Invalid MFU override is rejected by argparse try: mfu_value("1.5") except argparse.ArgumentTypeError as e: print("rejected:", e) # "MFU must be in the range (0, 1]" # 2) Shared-expert overlap on a non-Qwen3.5 hybrid raises ValueError in main() import argparse from main import main args = argparse.Namespace( config_path="hf_configs/qwen3-8B_config.json", # not a hybrid MoE device_type="H20", world_size=1, tp_size=1, num_nodes=1, max_prefill_tokens=4096, prefill_attn_mfu=None, prefill_moe_mfu=None, decode_bs=None, target_tgs=2560, target_tpot=50, target_isl=4096, target_osl=2048, use_fp8_gemm=False, use_fp8_kv=False, decode_scheduler_overhead_ms=None, enable_shared_expert_overlap=True, enable_deepep=False, enable_tbo=False, sm_ratio=108 / 132, prefill_only=False, decode_only=True, ) try: main(args) except ValueError as e: print("ValueError:", e) # --enable-shared-expert-overlap is only supported for the Qwen3.5 MoE HybridModel ``` -------------------------------- ### Decode attention with MLA config (DeepSeek V3) Source: https://github.com/alibaba/infersim Creates an attention module for a DeepSeek V3 config (MLA) with FP8 GEMM enabled and FP8 KV disabled. Calls decode_attn_core and decode_attn_others for a batch size of 64 and KV length of 2048, using example per-token KV bytes, and prints the total decode attention time in microseconds. ```python from config.model_config import ModelConfig from layers.attn import create_attention config = ModelConfig("hf_configs/deepseek_v3_config.json") # MLA attn = create_attention(config, use_fp8_gemm=True, use_fp8_kv=False, tp_size=1) # Decode: bs=64, kv_len=2048, per-token KV bytes from kvcache module kvcache_bytes = 512 + 64 # example per-token bytes t_core = attn.decode_attn_core(64, 2048, kvcache_bytes, "H800") t_others = attn.decode_attn_others(64, "H800") print(f"decode attn total: {1e6 * (t_core + t_others):.2f} us") ``` -------------------------------- ### main.py --help output Source: https://github.com/alibaba/infersim/blob/main/README.md Shows the command-line interface for the Infersim simulator. Lists all options including --config-path, --device-type, --world-size, --tp-size, --num-nodes, --max-prefill-tokens, --prefill-attn-mfu, --prefill-moe-mfu, --decode-bs, --target-tgs, --target-tpot, --target-isl, --target-osl, --use-fp8-gemm, --use-fp8-kv, --decode-scheduler-overhead-ms, --enable-shared-expert-overlap, --enable-deepep, --enable-tbo, --sm-ratio, --prefill-only, and --decode-only. Note that --enable-shared-expert-overlap is only supported for the Qwen3.5 MoE HybridModel. ```text $ python3 main.py --help usage: main.py [-h] --config-path CONFIG_PATH [--device-type {H20,H800,H200,GB200,PRO5000}] [--world-size WORLD_SIZE] [--tp-size TP_SIZE] [--num-nodes NUM_NODES] [--max-prefill-tokens MAX_PREFILL_TOKENS] [--prefill-attn-mfu PREFILL_ATTN_MFU] [--prefill-moe-mfu PREFILL_MOE_MFU] [--decode-bs DECODE_BS] [--target-tgs TARGET_TGS] [--target-tpot TARGET_TPOT] [--target-isl TARGET_ISL] [--target-osl TARGET_OSL] [--use-fp8-gemm] [--use-fp8-kv] [--decode-scheduler-overhead-ms DECODE_SCHEDULER_OVERHEAD_MS] [--enable-shared-expert-overlap] [--enable-deepep] [--enable-tbo] [--sm-ratio SM_RATIO] [--prefill-only] [--decode-only] optional arguments: -h, --help show this help message and exit --config-path CONFIG_PATH The path of the hf model config.json --device-type {H20,H800,H200,GB200,PRO5000} Device type --world-size WORLD_SIZE Num of GPUs --tp-size TP_SIZE Tensor parallel size. If >1, both attention and MoE use TP; if =1, attention uses DP and MoE uses EP. --num-nodes NUM_NODES Num of nodes --max-prefill-tokens MAX_PREFILL_TOKENS Max prefill tokens per GPU --prefill-attn-mfu PREFILL_ATTN_MFU Override prefill attention MFU. If omitted, read MFU from bench data. --prefill-moe-mfu PREFILL_MOE_MFU Override prefill routed MoE/FFN MFU. If omitted, read MFU from bench data. --decode-bs DECODE_BS Decoding batchsize per GPU. If not specified, bs = tgs * tpot. --target-tgs TARGET_TGS Target tokens/s per GPU --target-tpot TARGET_TPOT TPOT in ms --target-isl TARGET_ISL Input sequence length, in tokens --target-osl TARGET_OSL Output sequence length, in tokens --use-fp8-gemm Use fp8 gemm --use-fp8-kv Use fp8 kvcache --decode-scheduler-overhead-ms DECODE_SCHEDULER_OVERHEAD_MS Override decode scheduler overhead in milliseconds. If omitted, use the existing model default. --enable-shared-expert-overlap Model Qwen3.5 MoE Decode shared and routed experts as parallel CUDA-stream paths. Only supported for the Qwen3.5 MoE HybridModel. --enable-deepep Enable DeepEP --enable-tbo Enable two batch overlap --sm-ratio SM_RATIO In TBO DeepEP normal mode, the SM ratio used for computation --prefill-only Only simulate prefill --decode-only Only simulate decoding ``` -------------------------------- ### main: run InferSim simulation Source: https://github.com/alibaba/infersim Entry point that constructs ModelConfig, selects Model vs HybridModel, and runs prefill/decoding. Raises ValueError if --enable-shared-expert-overlap is set but the model is not a Qwen3.5 MoE hybrid. Prints results to stdout. ```python def main(args): config = ModelConfig(args.config_path) enable_shared_expert_overlap = getattr( args, "enable_shared_expert_overlap", False ) if enable_shared_expert_overlap and not ( config.is_qwen3_5_moe and config.is_hybrid_linear ): raise ValueError( "--enable-shared-expert-overlap is only supported for the " "Qwen3.5 MoE HybridModel" ) print("\n{s:{c}^{n}}".format(s=" Simulator Result ", n=50, c="=")) ... if config.is_hybrid_linear: model = HybridModel(args, config) ... else: model = Model(args, config) model.print_weights_info() model.print_kvcache_info() model.print_flops_info() if not args.decode_only: model.prefill() if not args.prefill_only: model.decoding() ``` -------------------------------- ### Initialize Comm with DeepEP and run prefill/decode comm Source: https://github.com/alibaba/infersim Shows how to create a Comm instance with DeepEP enabled and measure prefill (normal mode) and decode (low-latency mode) communication times. Uses ModelConfig and gpu_map to configure the environment. ```python from config.model_config import ModelConfig from hardware.gpu import gpu_map from comm.comm import Comm config = ModelConfig("hf_configs/deepseek_v3_config.json") comm = Comm(config, gpu_map["H800"], world_size=128, num_nodes=16, enable_deepep=True) # Prefill comm (DeepEP normal mode) t_before, t_after = comm.prefill_comm(num_tokens=4096) print(f"dispatch {t_before * 1e6:.2f} us | combine {t_after * 1e6:.2f} us") # Decode comm (DeepEP low-latency mode) t_before, t_after = comm.decode_comm(num_tokens=64) print(f"low-latency dispatch {t_before * 1e6:.2f} us") ``` -------------------------------- ### Simulator output for Qwen3-30B-A3B decode Source: https://github.com/alibaba/infersim/blob/main/README.md Displays the simulator's output after running the decode script. It reports device type H20, world size 4, attention type MHA/GQA, model weights (per GPU params 15.19 GB), KV cache space (60.81 GB), FLOPs per token (9.46 GFLOPs), and decoding metrics including TPOT 38.00 ms and throughput 2632 TGS. ```text ================ Simulator Result ================ Device type: H20 World size: 4 Attn type: MHA/GQA Use FP8 GEMM: 0 Use FP8 KV: 0 ------------------Model Weights------------------- One attn params size (MB): 36.00 One expert params size (MB): 9.00 Per GPU params size (GB): 15.19 ---------------------KV Cache--------------------- KV cache space (GB): 60.81 Input seq len: 4096 Output seq len: 2048 Target decode batchsize: 100 Target per-token KV cache size (KB): 103.79 Current per-token KV cache size (KB): 96.00 ----------------------FLOPs----------------------- Num hidden layers: 48 Per-token per-layer attn core (GFLOPs): 0.08 Per-token per-layer MoE/FFN (GFLOPs): 0.08 Per-token per-layer others (GFLOPs): 0.04 Per-token attn core (GFLOPs): 4.03 Per-token MoE (GFLOPs): 3.62 Per-token others (GFLOPs): 1.81 Per-token total (GFLOPs): 9.46 ---------------------Decoding--------------------- Attn core MFU: 0.15 Attn core latency (us): 361.77 KV loading latency (us): 298.02 QKV_proj latency (us): 31.03 O_proj latency (us): 16.95 Routed experts/FFN MFU: 0.18 Routed experts/FFN latency (us): 269.28 Experts loading latency (us): 85.83 Comm before MoE/FFN (us): 4.24 Comm after MoE/FFN (us): 4.24 TPOT (ms): 38.00 Throughput (TGS): 2632 ``` -------------------------------- ### Run Model simulation with ModelConfig and argparse Source: https://github.com/alibaba/infersim Creates a Model instance with a Qwen3-8B config and prints weight, KV cache, and FLOPs info, then runs prefill and decoding. The prefill() method prints TTFT (ms) and prefill TGS; decoding() prints TPOT (ms) and decode TGS and flags SLO violations. ```python import argparse from config.model_config import ModelConfig from models.model import Model config = ModelConfig("hf_configs/qwen3-8B_config.json") args = argparse.Namespace( device_type="H20", world_size=1, tp_size=1, num_nodes=1, use_fp8_gemm=False, use_fp8_kv=False, target_isl=4096, target_osl=2048, decode_bs=32, target_tgs=2560, target_tpot=50, max_prefill_tokens=4096, enable_deepep=False, enable_tbo=False, sm_ratio=108 / 132, decode_scheduler_overhead_ms=None, prefill_attn_mfu=None, prefill_moe_mfu=None, prefill_only=False, decode_only=False, ) model = Model(args, config) model.print_weights_info() model.print_kvcache_info() model.print_flops_info() model.prefill() # prints TTFT (ms) and prefill TGS model.decoding() # prints TPOT (ms) and decode TGS; flags SLO violation ``` -------------------------------- ### Initialize Comm without DeepEP and measure all-reduce and TP all-reduce Source: https://github.com/alibaba/infersim Shows how to create a Comm instance with DeepEP disabled, falling back to all-reduce, and measure decode communication and TP ring all-reduce times. Uses ModelConfig and gpu_map to configure the environment. ```python from config.model_config import ModelConfig from hardware.gpu import gpu_map from comm.comm import Comm config = ModelConfig("hf_configs/qwen3-30B-A3B_config.json") comm = Comm(config, gpu_map["H20"], world_size=4, num_nodes=1, enable_deepep=False) t1, t2 = comm.decode_comm(num_tokens=100) # two fp16 all-reduces over NVLink tp_t = comm.tp_all_reduce(num_tokens=100, tp_size=2) # ring all-reduce; 0 if tp_size<=1 print(f"all-reduce comm: {1e6 * (t1 + t2):.2f} us, TP all-reduce: {1e6 * tp_t:.2f} us") ``` -------------------------------- ### Detect SLO violation programmatically with HybridModel Source: https://github.com/alibaba/infersim Uses HybridModel with a Qwen3.5-35B-A3B config and captures stdout to check for the "!Error: TPOT > SLO" signal. If present, prints a message to reduce GFLOPs or batch size. This example uses decode_only=True and enables FP8 GEMM. ```python import io from contextlib import redirect_stdout import argparse from config.model_config import ModelConfig from models.hybrid_model import HybridModel config = ModelConfig("hf_configs/qwen3.5-35B-A3B_config.json") args = argparse.Namespace( device_type="H20", world_size=1, tp_size=1, num_nodes=1, use_fp8_gemm=True, use_fp8_kv=False, target_isl=4096, target_osl=2048, decode_bs=224, target_tgs=2150, target_tpot=50, max_prefill_tokens=4096, enable_deepep=False, enable_tbo=False, sm_ratio=108 / 132, decode_scheduler_overhead_ms=None, enable_shared_expert_overlap=False, prefill_attn_mfu=None, prefill_moe_mfu=None, prefill_only=False, decode_only=True, ) model = HybridModel(args, config) buf = io.StringIO() with redirect_stdout(buf): model.print_weights_info() model.print_kvcache_info() model.print_flops_info() model.decoding() out = buf.getvalue() if "!Error: TPOT > SLO" in out: print("SLO violation detected — reduce GFLOPs or batch size") ``` -------------------------------- ### CLI Source: https://github.com/alibaba/infersim Command-line interface for the sparse MLA FP8 simulator. It builds a model config from a JSON file and calls the `sparse_mla_fp8` function with fixed batch size and head parameters, printing the estimated time and TFLOPS. ```APIDOC ## CLI (guarded by `if __name__ == "__main__":`) ### Description Command-line interface for the sparse MLA FP8 simulator. It builds a model config from a JSON file and calls the `sparse_mla_fp8` function with fixed batch size and head parameters, printing the estimated time and TFLOPS. ### Flags - **`--seq_len`** (int) - Required - Sequence length for query - **`--config_path`** (str) - Optional - Model config path (default: `../hf_configs/deepseek_v3.2_config.json`) - **`--gpu_type`** (str) - Required - GPU type (e.g. `H20`, `H800`) ### Behavior The CLI builds `config = ModelConfig(config_path)` and calls with `batch_size=128`, `num_heads=config.num_attention_heads`, `topk=config.index_topk`, `dim=config.kv_lora_rank`, `dim_rope=config.qk_rope_head_dim`, printing `Time: ... ms` and `TFLOPS: ...`. ``` -------------------------------- ### Comm class constructor Source: https://github.com/alibaba/infersim Initializes the communication model with configuration, GPU profile, world size, node count, and DeepEP enable flag. When enable_deepep is true, prefill_comm/decode_comm use dispatch/combine instead of all-reduce. ```python class Comm: def __init__( self, config: ModelConfig, gpu: GPU, world_size: int, num_nodes=1, enable_deepep=False, ): ``` -------------------------------- ### sparse_mla_fp8 Source: https://github.com/alibaba/infersim Simulates the sparse MLA FP8 attention kernel and returns estimated kernel time and achieved TFLOPS. It models MMA compute, FP8 dequantization, and KV-scale/weight loading based on SM count, clock frequency, and SM architecture micro-benchmarks. ```APIDOC ## Function: `sparse_mla_fp8` ### Description Simulates the sparse MLA FP8 attention kernel and returns estimated kernel time and achieved TFLOPS. It models MMA compute, FP8 dequantization, and KV-scale/weight loading based on SM count, clock frequency, and SM architecture micro-benchmarks. ### Signature ```python def sparse_mla_fp8( batch_size: int, num_heads: int, seq_len: int, topk: int, dim: int, gpu_type: str, dim_rope: int, ) -> tuple[float, float]: ``` ### Parameters - **batch_size** (int) - Required - Batch size (queries) - **num_heads** (int) - Required - MLA attention head count - **seq_len** (int) - Required - Query sequence length - **topk** (int) - Required - Sparse index top-k (e.g. `config.index_topk`) - **dim** (int) - Required - Nope (non-positional) KV dimension; `dim_rope` is separate - **gpu_type** (str) - Required - `gpu_map` key; must have `num_sm`, `frequency`, `sm_version` set (H20, H800) - **dim_rope** (int) - Required - RoPE KV dimension ### Returns - **tuple[float, float]** - `(time_ms, theoretical_max_tflops)` where `theoretical_max_tflops = compute_volume_flop / time / 1e12` ### Errors - **ValueError** - `"Unsupported SM version: {sm_version}"` when `gpu.sm_version not in DEQUANT_CYCLES` (i.e. any GPU other than SM 90 / Hopper: H200, GB200, and PRO5000 have `sm_version` `None` or `120` and will raise). GPUs without `frequency`/`num_sm` also fail arithmetically — the function is effectively limited to SM-90 devices such as H20/H800. ### Output Prints `time_load_and_dequant_per_block:...us, time_mma_per_block:...us`. ### Request Example ```python from kernel_sim.sparse_mla_fp8 import sparse_mla_fp8 from config.model_config import ModelConfig config = ModelConfig("hf_configs/deepseek_v3.2_config.json") time_ms, tflops = sparse_mla_fp8( batch_size=128, num_heads=config.num_attention_heads, seq_len=4096, topk=config.index_topk, dim=config.kv_lora_rank, gpu_type="H800", # SM 90 — supported dim_rope=config.qk_rope_head_dim, ) print(f"Time: {time_ms:.3f} ms | TFLOPS: {tflops:.3f}") ``` ### Error Example ```python from kernel_sim.sparse_mla_fp8 import sparse_mla_fp8 from config.model_config import ModelConfig config = ModelConfig("hf_configs/deepseek_v3.2_config.json") try: # PRO5000 has sm_version=120, which is not in DEQUANT_CYCLES sparse_mla_fp8( batch_size=1, num_heads=config.num_attention_heads, seq_len=1024, topk=config.index_topk, dim=config.kv_lora_rank, gpu_type="PRO5000", dim_rope=config.qk_rope_head_dim, ) except ValueError as e: print("ValueError:", e) # 'Unsupported SM version: 120' ``` ``` -------------------------------- ### Catch Errors in Consumer Code Source: https://github.com/alibaba/infersim Shows how to catch various exceptions when using Infersim components: config-level failures (FileNotFoundError, JSONDecodeError, ValueError, KeyError), runtime argument validation (argparse.ArgumentTypeError), kernel simulator limitations (ValueError for unsupported GPU), and missing GDN bench data (AssertionError). ```python from config.model_config import ModelConfig from models.hybrid_model import HybridModel from kernel_sim.sparse_mla_fp8 import sparse_mla_fp8 # 1. Config-level failures try: config = ModelConfig("hf_configs/qwen3.5-35B-A3B_config.json") except (FileNotFoundError, json.JSONDecodeError) as e: print("config unreadable:", e) except ValueError as e: print("invalid shapes:", e) # shared_expert_intermediate_size not multiple except KeyError as e: print("missing key:", e) # 2. Runtime argument validation (CLI-equivalent) from main import mfu_value try: mfu_value("1.2") except argparse.ArgumentTypeError as e: print("bad MFU:", e) # 3. Kernel simulator limitations try: sparse_mla_fp8(128, 128, 4096, 128, 512, "PRO5000", 64) except ValueError as e: print("unsupported GPU for sparse MLA sim:", e) # Unsupported SM version: 120 # 4. Missing GDN bench data (assertion) from mfu.mfu import get_linear_attn_decode_latency try: get_linear_attn_decode_latency(config, batchsize=64, device_type="H20") except AssertionError as e: print("GDN data missing:", e) ``` -------------------------------- ### Comm.__init__ Source: https://github.com/alibaba/infersim Initializes the Comm object with configuration, GPU profile, world size, node count, and DeepEP enablement. Sets up communication latency estimation for MoE dispatch/combine and all-reduce operations. ```APIDOC ## Comm.__init__ ### Description Initializes the Comm object with configuration, GPU profile, world size, node count, and DeepEP enablement. Sets up communication latency estimation for MoE dispatch/combine and all-reduce operations. ### Method Constructor ### Signature ```python Comm(config: ModelConfig, gpu: GPU, world_size: int, num_nodes=1, enable_deepep=False) ``` ### Parameters - **config** (ModelConfig) - Required - Provides `hidden_size` and (for low-latency dispatch) `num_experts_per_tok` - **gpu** (GPU) - Required - Hardware profile; `nvlink_bw`, `rdma_bw` used - **world_size** (int) - Required - Total GPU count - **num_nodes** (int) - Optional (default: 1) - Node count; `> 1` switches inter-node transfers to RDMA bandwidth - **enable_deepep** (bool) - Optional (default: False) - When true, `prefill_comm`/`decode_comm` use dispatch/combine instead of all-reduce ``` -------------------------------- ### Model class __init__ Source: https://github.com/alibaba/infersim Initializes the Model orchestrator with GPU mapping, args, and config. Used for dense/MoE non-hybrid architectures. ```python class Model: def __init__(self, args, config): self.gpu = gpu_map[args.device_type] self.args = args self.config = config ``` -------------------------------- ### a2f and f2a methods Source: https://github.com/alibaba/infersim Return seconds for all-to-all over RDMA: a2f uses FP8, f2a uses FP16. Both use inter_node=True. ```python def a2f(self, num_tokens): tensor_shape = [num_tokens, self.config.hidden_size] return self.size_bw_model(tensor_shape, use_fp8=True, inter_node=True) def f2a(self, num_tokens): tensor_shape = [num_tokens, self.config.hidden_size] return self.size_bw_model(tensor_shape, use_fp8=False, inter_node=True) ``` -------------------------------- ### print_weights_info method Source: https://github.com/alibaba/infersim Prints the 'Model Weights' block and sets kvcache_mem. Per-GPU expert count follows the split rule based on tp_size. ```python def print_weights_info(self): ``` -------------------------------- ### get_moe_gflops(config, tp_size) Source: https://github.com/alibaba/infersim Computes per-token per-layer MoE/FFN GFLOPs for a given model configuration and tensor parallelism size. The calculation accounts for TP sharding of intermediate_size and active experts per token. ```APIDOC ## Function: `get_moe_gflops(config, tp_size)` ### Description Computes per-token per-layer MoE/FFN GFLOPs. The ×3 covers the gate/up/down projections; `act` counts active experts per token (shared experts are always active). ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | config | ModelConfig | yes | — | `intermediate_size`, `num_shared_experts`, `num_experts_per_tok`, `hidden_size` | | tp_size | int | yes | — | TP size sharding `intermediate_size` | ### Return Value - **float** — per-token per-layer MoE/FFN GFLOPs. ### Request Example ```python from config.model_config import ModelConfig from flops.flops import get_attn_gflops, get_moe_gflops config = ModelConfig("hf_configs/deepseek_v3_config.json") attn_core, other = get_attn_gflops(config, avg_context_len=4096, tp_size=1, absorb=True) moe = get_moe_gflops(config, tp_size=1) total = (attn_core + other + moe) * config.num_hidden_layers print(f"per-token total: {total:.2f} GFLOPs") ``` ``` -------------------------------- ### Prefill MoE with MFU Override (Qwen3) Source: https://github.com/alibaba/infersim Benchmarks prefill MoE per layer with an explicit prefill_mfu=0.42 override, replacing the bench-data grouped-GEMM MFU. Uses H20 device and tp_size=1. ```python from config.model_config import ModelConfig from layers.moe import MoE config = ModelConfig("hf_configs/qwen3-30B-A3B_config.json") moe = MoE(config, use_fp8_gemm=False, tp_size=1, prefill_mfu=0.42) # Overrides the bench-data grouped-GEMM MFU with 0.42 t = moe.prefill_moe(seq_len=4096, device_type="H20", num_gpus=4) print(f"prefill MoE per layer: {1e6 * t:.2f} us") ``` -------------------------------- ### Prefill attention with MHA/GQA config (Qwen3-8B) and MFU override Source: https://github.com/alibaba/infersim Creates an attention module for a Qwen3-8B config (MHA/GQA) with FP8 disabled and a prefill MFU override of 0.5. Calls prefill_attn_core with a sequence length of 4096 and zero KV bytes, bypassing the bench-data lookup, and prints the time in microseconds. ```python from config.model_config import ModelConfig from layers.attn import create_attention config = ModelConfig("hf_configs/qwen3-8B_config.json") # MHA/GQA attn = create_attention( config, use_fp8_gemm=False, use_fp8_kv=False, tp_size=1, prefill_mfu=0.5 ) # Prefill with an explicit MFU override; the bench-data lookup is bypassed t = attn.prefill_attn_core(seq_len=4096, kvcache_bytes=0, device_type="H20") print(f"{t * 1e6:.2f} us") ``` -------------------------------- ### get_expected_active_experts(config, num_gpus, tp_size, num_tokens=None) Source: https://github.com/alibaba/infersim Estimates the expected number of distinct local routed experts that a uniformly routed batch of tokens will touch. When `num_tokens` is None, it returns the number of local experts; otherwise, it applies a coupon-collector estimate based on the top-k selection probability. ```APIDOC ## get_expected_active_experts(config, num_gpus, tp_size, num_tokens=None) ### Description Estimates the expected number of distinct local routed experts that a uniformly routed batch of tokens will touch. When `num_tokens` is None, it returns the number of local experts; otherwise, it applies a coupon-collector estimate based on the top-k selection probability. ### Method Function ### Signature ```python def get_expected_active_experts( config: ModelConfig, num_gpus: int, tp_size: int, num_tokens=None ): """Estimate local routed experts touched by a uniformly routed batch.""" ep_size = num_gpus // tp_size num_local_experts = config.num_routed_experts / ep_size if num_tokens is None: return num_local_experts topk = min(config.num_experts_per_tok, num_local_experts) probability_not_selected = (1 - topk / num_local_experts) ** num_tokens return num_local_experts * (1 - probability_not_selected) ``` ### Parameters - **config** (ModelConfig) - Required - Model configuration containing `num_routed_experts` and `num_experts_per_tok`. - **num_gpus** (int) - Required - World size. - **tp_size** (int) - Required - EP size derived as `num_gpus // tp_size`. - **num_tokens** (int | None) - Optional - Default: None. When None, all local experts are assumed active. ### Returns - **float** - Expected number of distinct local routed experts touched by a uniformly routed batch of `num_tokens` tokens (coupon-collector estimate). ``` -------------------------------- ### prefill method Source: https://github.com/alibaba/infersim Prints the 'Prefilling' block with TTFT and prefill TGS. Computes per-layer latency terms and assembles TTFT with TBO or default logic. ```python def prefill(self): ```