Support Qwen3.5 evaluations
Browse filesFiles changed (3)
- README.md+28-28
- calc_ic.py+7-3
- flops.py+149-1
8 unmodified lines910111213141516171 unmodified line19202122232425262728293031323334353637383940414243444546474820 unmodified lines69707172737475767778798081828384858687888990918 unmodified lines<img src="assets/ic_mixed.png" width="700" /></p>**Information Capacity** evaluates an LLM's **efficiency** based on text compression performance relative to computational complexity, harnessing the inherent correlation between **compression** and **intelligence**.Larger models can predict the next token more accurately, leading to higher compression gains but at increased computational costs.Consequently, a series of models with varying sizes exhibits **consistent** information capacity, which can be used to compare model capability across model series and predict model performance within a series.It also facilitates dynamic routing of different-sized models for efficient handling of tasks with varying difficulties, which is especially relevant to the device-edge-cloud infrastructure detailed in the **AI Flow** framework.With the rapid evolution of edge intelligence, we believe that this hierarchical network will replace the mainstream cloud-centric computing scheme in the near future.1 unmodified lineAn effective tokenizer can represent a given text with fewer tokens, thus reducing both the input and output token counts.This reduction not only lowers computational costs and inference delay but also facilitates long-context memory and in-depth reasoning.Tokenizer efficiency exhibits growing significance in light of the exploding input length and the widespread usage of test-time scaling, but is often **neglected** in LLM evaluations.We assess the information capacity of 52 models across 5 heterogeneous datasets and find consistent evidence regarding the influences of tokenizer efficiency, pretraining data, and the mixture-of-experts (MoE) architecture.## DataPrevious studies have established that the correlation between compression and intelligence weakens when the evaluation corpus significantly deviates from the domain of downstream tasks.Thus, we construct five heterogeneous datasets to provide a holistic assessment of LLM capabilities: Mixed text, FinePDFs-en, Ch-FineWeb-Edu, FineWeb-Edu, and NextCoder.The Mixed text dataset is collected by us, while other datasets are sampled from publicly available open-source datasets.* **Mixed text**: We compile a multilingual text corpus from diverse sources, including books, webpages, code, and published papers, to facilitate a comprehensive evaluation on LLMs' compression efficiency.* **FinePDFs-en**: The FinePDFs dataset consists of about 3T tokens sourced exclusively from publicly available PDF files. We only select from the English subset to better examine the influence of the corpus distribution. <a href="https://huggingface.co/datasets/HuggingFaceFW/finepdfs"> [Huggingface] </a>* **Ch-FineWeb-Edu**: The Chinese Fineweb Edu dataset is a high-quality Chinese pretraining corpus of 90 million samples in the education domain, selected by a strategy similar to that of FineWeb-Edu. <a href="https://huggingface.co/datasets/opencsg/chinese-fineweb-edu"> [Huggingface] </a>* **FineWeb-Edu**: The FineWeb-Edu dataset contains 1.3T tokens of educational English webpages filtered from the FineWeb dataset, based on the annotations generated by Llama-3-70B-Instruct. <a href="https://huggingface.co/datasets/HuggingFaceFW/fineweb-edu"> [Huggingface] </a>* **NextCoder**: The NextCoder dataset consists of 127K unique code samples generated by GPT-4o and Llama-3.3-70B-Instruct across 8 programming languages: Python, Java, C++, C, Rust, JavaScript, Go, and Kotlin. <a href="https://huggingface.co/datasets/microsoft/NextCoderDataset"> [Huggingface] </a>## UsageStep 1. Setup an environment viable for model inference.```shpip install numpy torch transformers tqdm flash_attn huggingface_hub```Step 2. Clone this repo.```shGIT_LFS_SKIP_SMUDGE=1 git clone https://huggingface.co/datasets/TeleAI-AI-Flow/InformationCapacitycd InformationCapacity```20 unmodified linesurl={https://arxiv.org/abs/2511.08066},}@misc{an2025aiflowperspectivesscenarios,title={AI Flow: Perspectives, Scenarios, and Approaches},author={Hongjun An and Wenhan Hu and Sida Huang and Siqi Huang and Ruanjun Li and Yuanzhi Liang and Jiawei Shao and Yiliang Song and Zihan Wang and Cheng Yuan and Chi Zhang and Hongyuan Zhang and Wenhao Zhuang and Xuelong Li},year={2025},eprint={2506.12479},archivePrefix={arXiv},primaryClass={cs.AI},url={https://arxiv.org/abs/2506.12479},}@misc{shao2025aiflownetworkedge,title={AI Flow at the Network Edge},author={Jiawei Shao and Xuelong Li},year={2025},eprint={2411.12469},archivePrefix={arXiv},primaryClass={eess.SP},url={https://arxiv.org/abs/2411.12469},}```8 unmodified lines91011121314151617181 unmodified line202122232425262728293031323334353637383940414243444546474820 unmodified lines69707172737475767778798081828384858687888990918 unmodified lines<img src="assets/ic_mixed.png" width="700" /></p>**Information Capacity** evaluates an LLM's **efficiency** based on text compression performance relative to computational complexity, leveraging the inherent correlation between **compression** and **intelligence**.Larger models can predict the next token more accurately, leading to higher compression gains but at increased computational costs.Consequently, a series of models with varying sizes exhibits **consistent** information capacity, which can be used to compare model capability across model series and predict model performance within a series.This consistency opens up the possibility of cross-scale performance prediction before actual pretraining, offering a computationally efficient alternative to conventional scaling-law fitting approaches.It also facilitates dynamic routing of different-sized models for efficient handling of tasks with varying difficulties, which is especially relevant to the device-edge-cloud infrastructure detailed in the **AI Flow** framework.With the rapid evolution of edge intelligence, we believe that this hierarchical network will replace the mainstream cloud-centric computing scheme in the near future.1 unmodified lineAn effective tokenizer can represent a given text with fewer tokens, thus reducing both the input and output token counts.This reduction not only lowers computational costs and inference delay but also facilitates long-context memory and in-depth reasoning.Tokenizer efficiency exhibits growing significance in light of the exploding input length and the widespread usage of test-time scaling, but is often **neglected** in LLM evaluations.We assess the information capacity of 56 models across 5 heterogeneous datasets and find consistent evidence regarding the influences of tokenizer efficiency, pretraining data, and the mixture-of-experts (MoE) architecture.## MethodThe model intelligence is measured by the data size savings achieved from the LLM's probability prediction.The original size of a text sample in the given dataset is denoted as $C$, which is transformed into a sequence of $L$ tokens by the tokenizer of an LLM $M$.The symbol length of the $i$-th token derived from entropy coding is approximately $-\log p(x_i | x_{<i} ; M)$, and the compression gain is the difference between the original data size and the summed symbol length of all tokens.The computational complexity is measured by the inference floating-point operations (FLOPs) $N_M$ on a logarithmic scale according to the scaling law.We introduce a negative bias $b$ in the numerator so that different-sized models in a series have nearly identical information capacities, thus enabling convenient comparison across different model sizes and architectures.In summary, the information capacity is defined as:$\text{Information Capacity} = \frac{C - \sum_{i} -\log p(x_i | x_{<i} ; M)}{ \log N_M}$.## UsageStep 1. Setup an environment that can run model inference, for example:```shpip install numpy torch transformers tqdm flash_attn huggingface_hub```Step 2. Clone this repo.```shgit clone https://github.com/TeleAI-AI-Flow/InformationCapacity.gitcd InformationCapacity```20 unmodified linesurl={https://arxiv.org/abs/2511.08066},}@misc{an2026aiflowperspectivesscenarios,author={Hongjun An and Wenhan Hu and Sida Huang and Siqi Huang and Ruanjun Li and Yuanzhi Liang and Jiawei Shao and Yiliang Song and Zihan Wang and Cheng Yuan and Chi Zhang and Hongyuan Zhang and Wenhao Zhuang and Xuelong Li},journal={Vicinagearth},title={{AI} Flow: perspectives, scenarios, and approaches},year={2026},volume={3},number={1},pages={1-32},}@misc{shao2026aiflownetworkedge,title={{AI} Flow at the Network Edge},author={Shao, Jiawei and Li, Xuelong},journal={IEEE Network},year={2026},volume={40},number={1},pages={330-336},}```
2 unmodified lines34567894 unmodified lines1415161718192021222315 unmodified lines3940414243442 unmodified linesfrom math import log2from text_size import calculate_text_size_per_tokenfrom likelihood import calculate_negative_log_likelihoodfrom flops import gqa_model_theoretical_flops, mla_model_theoretical_flopsdef calculate_information_capacity(model_path: str,4 unmodified linesattention_mechanism: str = None,) -> float:if attention_mechanism is None:attention_mechanism = "mla" if "deepseek" in model_path.lower() else "gqa"else:attention_mechanism = attention_mechanism.lower()if attention_mechanism != "gqa" and attention_mechanism != "mla":raise NotImplementedError("attention_mechanism argument should be either gqa or mla")if numerator_bias is None:15 unmodified linesflops_results = gqa_model_theoretical_flops(cfg_path, gen_len=max_sample_length)elif attention_mechanism == "mla":flops_results = mla_model_theoretical_flops(cfg_path, gen_len=max_sample_length)per_token_flops = flops_results["decode_total_TFLOPs"] * 1e12 / max_sample_lengthfor k, v in flops_results.items(): print(f"{k}: {v}")2 unmodified lines34567894 unmodified lines14151617181920212223242515 unmodified lines41424344454647482 unmodified linesfrom math import log2from text_size import calculate_text_size_per_tokenfrom likelihood import calculate_negative_log_likelihoodfrom flops import gqa_model_theoretical_flops, mla_model_theoretical_flops, qwen3_5_theoretical_flopsdef calculate_information_capacity(model_path: str,4 unmodified linesattention_mechanism: str = None,) -> float:if attention_mechanism is None:if "deepseek" in model_path.lower(): attention_mechanism = "mla"elif "qwen3.5" in model_path.lower(): attention_mechanism = "qwen3_5"else: attention_mechanism = "gqa"else:attention_mechanism = attention_mechanism.lower()if attention_mechanism != "gqa" and attention_mechanism != "mla" and attention_mechanism != "qwen3_5":raise NotImplementedError("attention_mechanism argument should be either gqa or mla")if numerator_bias is None:15 unmodified linesflops_results = gqa_model_theoretical_flops(cfg_path, gen_len=max_sample_length)elif attention_mechanism == "mla":flops_results = mla_model_theoretical_flops(cfg_path, gen_len=max_sample_length)elif attention_mechanism == "qwen3_5":flops_results = qwen3_5_theoretical_flops(cfg_path, gen_len=max_sample_length)per_token_flops = flops_results["decode_total_TFLOPs"] * 1e12 / max_sample_lengthfor k, v in flops_results.items(): print(f"{k}: {v}")
435 unmodified lines436437438439435 unmodified lines"avg_decode_TFLOPs_per_token": toT(decode_total / max(T, 1)),}return results435 unmodified lines436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587435 unmodified lines"avg_decode_TFLOPs_per_token": toT(decode_total / max(T, 1)),}return resultsdef qwen3_5_theoretical_flops(config_path: Union[str, Path],seq_len: int = 0,gen_len: int = 1024,batch_size: int = 1,prefill_logits: str = "all", # "all" | "last" | "none") -> Dict[str, float]:# ---- load config ----cfg_path = Path(config_path)if cfg_path.is_dir():cfg_path = cfg_path / "config.json"with open(cfg_path, "r") as f:cfg = json.load(f)if "Qwen3.5" in config_path:cfg = cfg["text_config"]# ---- required hyperparams ----d_model = int(cfg["hidden_size"])n_layers = int(cfg.get("num_hidden_layers", cfg.get("n_layer")))n_heads = int(cfg.get("num_attention_heads", cfg.get("n_head")))n_kv_heads = int(cfg.get("num_key_value_heads", n_heads))d_ff = cfg.get("intermediate_size")if d_ff is None: d_ff = cfg.get("moe_intermediate_size") * cfg.get("num_experts_per_tok") # For MoE variantsd_ff = int(d_ff)vocab_size = int(cfg["vocab_size"])linear_num_key_heads = cfg.get("linear_num_key_heads")linear_num_value_heads = cfg.get("linear_num_value_heads")linear_key_head_dim = cfg.get("linear_key_head_dim")linear_value_head_dim = cfg.get("linear_value_head_dim")# n_activated_experts = int(cfg.get("num_experts_per_tok", 1)) + int(cfg.get("n_shared_experts", 0))# per-head dimension (assume divisible)d_k = d_model // n_headskv_dim = n_kv_heads * d_kB = batch_sizeL = seq_lenT = gen_len# ---- helpers (FLOPs, not TFLOPs) ----# Projections per layer for a sequence of length L# Q: 2 * B * L * d_model * d_model# O: same# K,V: 2 * B * L * d_model * kv_dim eachdef proj_flops(L_tokens: int) -> int:q = 2 * B * L_tokens * d_model * d_modelo = 2 * B * L_tokens * d_model * d_modelk = 2 * B * L_tokens * d_model * kv_dimv = 2 * B * L_tokens * d_model * kv_dimreturn q + k + v + o# Attention core per layer# Prefill (quadratic): QK^T + (softmax@V) ≈ 4 * B * n_heads * L^2 * d_k# Decode (one step over cache length C): ≈ 4 * B * n_heads * C * d_kdef attn_core_prefill_flops(L_tokens: int) -> int:return 4 * B * n_heads * (L_tokens ** 2) * d_kdef attn_core_decode_flops(cache_len: int) -> int:return 4 * B * n_heads * cache_len * d_k# MLP per layer# Two up matmuls + one down: 2*B*L*d_model*d_ff + 2*B*L*d_model*d_ff + 2*B*L*d_ff*d_model = 6*B*L*d_model*d_ffdef mlp_flops(L_tokens: int) -> int:if "gpt-oss" in config_path: return 4 * B * L_tokens * d_model * d_ff * int(cfg["num_experts_per_tok"]) # gpt-oss does not use gate function (6 → 4), registers per-expert intermediate sizeelif "Llama-4" in config_path: return B * L_tokens * d_model * (6 * d_ff + 4 * int(cfg["intermediate_size"])) # llama-4 use 2-layer mlp without gating on attn score, before the main mlpelse: return 6 * B * L_tokens * d_model * d_ff# LM head (final linear to vocab) for N tokens: 2 * B * N * d_model * vocab_sizedef lm_head_flops(num_tokens: int) -> int:return 2 * B * num_tokens * d_model * vocab_size# ---- prefill (length L) ----proj_prefill_per_layer = proj_flops(L)attn_prefill_per_layer = attn_core_prefill_flops(L)mlp_prefill_per_layer = mlp_flops(L)# stack_prefill = n_layers * (proj_prefill_per_layer + attn_prefill_per_layer + mlp_prefill_per_layer)stack_prefill = n_layers // 4 * (proj_prefill_per_layer + attn_prefill_per_layer) # only 1/4 of layers use full attentiondef linear_layer_flops(L_tokens):# proj + gated deltanet, excluding MLPreturn L_tokens * d_model * (linear_num_key_heads * linear_key_head_dim * 4 + linear_num_value_heads * linear_value_head_dim * 6 + 4 * linear_num_key_heads)stack_prefill += n_layers // 4 * 3 * linear_layer_flops(L) # remaining 3/4 linear-attention layersstack_prefill += n_layers * mlp_prefill_per_layer # MLP is the same across all layersif prefill_logits == "all":lm_prefill = lm_head_flops(L)elif prefill_logits == "last":lm_prefill = lm_head_flops(1)elif prefill_logits == "none":lm_prefill = 0else:raise ValueError("prefill_logits must be one of {'all','last','none'}")prefill_total = stack_prefill + lm_prefill# ---- decode (T steps) ----# For each step, projections/MLP are for 1 new token.proj_decode_per_layer_per_step = proj_flops(1)mlp_decode_per_layer_per_step = mlp_flops(1)# Attention core sums over growing cache lengths: L, L+1, ..., L+T-1# Sum_{t=0..T-1} 4 * B * n_heads * (L + t) * d_k = 4 * B * n_heads * d_k * (T*L + T*(T-1)/2)attn_decode_per_layer_total = 4 * B * n_heads * d_k * (T * L + (T * (T - 1)) // 2)# stack_decode = n_layers * (# T * (proj_decode_per_layer_per_step + mlp_decode_per_layer_per_step) + attn_decode_per_layer_total# )stack_decode = n_layers // 4 * (T * (proj_decode_per_layer_per_step) + attn_decode_per_layer_total)stack_decode += n_layers // 4 * 3 * linear_layer_flops(T)stack_decode += n_layers * T * mlp_decode_per_layer_per_step# Logits at each decode steplm_decode = lm_head_flops(T)decode_total = stack_decode + lm_decode# ---- packing results (TFLOPs) ----toT = lambda x: x / 1e12results = {# Inputs"batch_size": B,"seq_len": L,"gen_len": T,# "n_activated_experts": n_activated_experts,"hidden_size": d_model,"num_layers": n_layers,"num_heads": n_heads,"num_kv_heads": n_kv_heads,"intermediate_size": d_ff,"vocab_size": vocab_size,"prefill_logits_mode": prefill_logits,"prefill_total_TFLOPs": toT(prefill_total),"decode_total_TFLOPs": toT(decode_total),# Totals"request_total_TFLOPs": toT(prefill_total + decode_total),"avg_decode_TFLOPs_per_token": toT(decode_total / max(T, 1)),}return results
README.md+28-28
calc_ic.py+7-3
flops.py+149-1