Upload 6 files
Browse filesFiles changed (6)
- README.mdAdded+90
- assets/ic_mixed.pngAdded
- calc_ic.pyAdded+77
- flops.pyAdded+439
- likelihood.pyAdded+89
- text_size.pyAdded+97
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990# AI-Flow-Information Capacity
<p align="center"> <!-- <a href="README.md">中文</a>   |   <a href="README_en.md">English</a> --> 🏆 <a href="https://huggingface.co/spaces/TeleAI-AI-Flow/InformationCapacityLeaderboard"> Leaderboard</a>    |    🖥️ <a href="https://github.com/TeleAI-AI-Flow/InformationCapacity">GitHub</a>    |    🤗 <a href="https://huggingface.co/datasets/TeleAI-AI-Flow/InformationCapacity">Hugging Face</a>   |    📑  <a href="https://www.arxiv.org/abs/2511.08066">Paper</a></p>
<p align="center"> <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.
Compared to existing metrics on LLM efficiency, a key difference of information capacity is that it considers the influence of **tokenizer efficiency**.An 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 49 models across 5 heterogeneous datasets and find consistent evidence regarding the influences of tokenizer efficiency, pretraining data, and the mixture-of-experts (MoE) architecture.
## Method
The 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 computation formula of information capacity is expressed as:$$ \text{IC} = \frac{\frac{1}{L-1} (C - \sum_{i=2}^{L} -\log p(x_i | x_{<i} ; M))+b}{ \log (N_M / (L-1))} . $$
## Usage
Step 1. Setup an environment viable for model inference.```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```
Step 3. Download test datasets.```shhf download TeleAI-AI-Flow/InformationCapacity --repo-type=dataset --include "datasets/**" --local-dir .```
Step 4. Run evaluation code.```shpython calc_ic.py -m path/to/model -d datasets/mixed_text.jsonl -l 1024 -b 1```
## Citation
```bibtex@misc{yuan2025informationcapacity, title={Information Capacity: Evaluating the Efficiency of Large Language Models via Text Compression}, author={Cheng Yuan and Jiawei Shao and Chi Zhang and Xuelong Li}, year={2025}, eprint={2511.08066}, archivePrefix={arXiv}, primaryClass={cs.AI}, url={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}, }```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import argparseimport torchfrom 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
def calculate_information_capacity( model_path: str, data_path: str, max_sample_length: int = 1024, batch_size: int = 1, numerator_bias: float = None, attention_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: if "mixed_text.jsonl" in data_path: numerator_bias = -24 elif "Ch-FineWeb-Edu.jsonl" in data_path: numerator_bias = -18.7 else: numerator_bias = -27 print(f"numerator_bias is not designated, default to {numerator_bias} based on the data_path") ts_results = calculate_text_size_per_token(data_path, model_path, target_token_length=max_sample_length) avg_ts = ts_results["mean_text_size"] for k, v in ts_results.items(): print(f"{k}: {v}")
nlls = calculate_negative_log_likelihood(model_path, data_path, max_sample_length, batch_size=batch_size, num_samples=ts_results["total_valid_lines"]) avg_nll = torch.nanmean(nlls).item() print(f"Average negative log-likelihood: {avg_nll}")
cfg_path = model_path + "/config.json" if attention_mechanism == "gqa": flops_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_length for k, v in flops_results.items(): print(f"{k}: {v}") ic = (avg_ts - avg_nll + numerator_bias) / log2(per_token_flops) print(f"\nInformation capacity: {ic}")
return ic
def main(): parser = argparse.ArgumentParser( description="Compute the information capacity of a language model." ) parser.add_argument("-m", "--model_path", type=str, required=True, help="Path to the model directory.") parser.add_argument("-d", "--data_path", type=str, required=True, help="Path to the dataset (JSONL format).") parser.add_argument("-l", "--max_sample_length", type=int, default=1024, help="Maximum token length for each sample.") parser.add_argument("-b", "--batch_size", type=int, default=1, help="Batch size for evaluation.") parser.add_argument("-n", "--numerator_bias", type=float, default=None, help="Optional numerator bias. If not set, inferred automatically.") parser.add_argument("-a", "--attention_mechanism", type=str, choices=["gqa", "mla"], default=None, help="Specify attention mechanism ('gqa' or 'mla'). If not set, inferred automatically.")
args = parser.parse_args()
calculate_information_capacity( model_path=args.model_path, data_path=args.data_path, max_sample_length=args.max_sample_length, batch_size=args.batch_size, numerator_bias=args.numerator_bias, attention_mechanism=args.attention_mechanism, )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439import jsonfrom pathlib import Pathfrom typing import Union, Dict, Optional
def gqa_model_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]: """ Compute theoretical FLOPs for an LLM with GQA given its Hugging Face config.json.
Assumptions (dense Transformer, forward only): - 2 FLOPs per multiply-add. - Attention = dense GQA: Q & O project to d_model; K/V project to n_kv_heads * d_k where d_k = d_model / n_heads. - Attention core cost includes QK^T and softmax(QK^T) @ V. - MLP = gated (SwiGLU-like): two "up" matmuls + one "down" matmul. (handles special cases of llama-4 and gpt-oss) - LM head (final logits) included; at prefill you can count logits for: * "all": logits for every prompt token (matches HF's default forward outputs), * "last": logits only for last prompt token (some gens do this), * "none": if you never materialize logits at prefill. At decode, logits are computed every step.
Returns (TFLOPs): dict with detailed breakdown for prefill, decode, totals. """ # ---- load config ---- if "Ruyi" in config_path: import re pattern = re.compile(r'(\d+(?:\.\d+)?)\s*(?:B|billion)', re.IGNORECASE) match = pattern.search(config_path) config_path = config_path.replace(match.group(0), "7B") 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 "gemma-3" in config_path: import re pattern = re.compile(r'(\d+(?:\.\d+)?)\s*(?:B|billion)', re.IGNORECASE) match = pattern.search(config_path) param_count = float(match.group(1)) if param_count >= 4: cfg = cfg["text_config"] cfg["vocab_size"] = 262208 if param_count == 4: cfg["num_attention_heads"] = 8; cfg["num_key_value_heads"] = 4 elif param_count == 12: cfg["num_attention_heads"] = 16; cfg["num_key_value_heads"] = 8 elif param_count == 27: cfg["num_attention_heads"] = 32; cfg["num_key_value_heads"] = 16 if "Llama-4" 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"))) if "Ruyi" not in config_path else int(match.group(1)) * 4 n_heads = int(cfg.get("num_attention_heads", cfg.get("n_head"))) n_kv_heads = int(cfg.get("num_key_value_heads", n_heads)) if "Llama-4" in config_path: d_ff = cfg["intermediate_size_mlp"] elif ("Qwen1.5" in config_path or "Qwen2-" in config_path) and "B-A" in config_path: d_ff = cfg["intermediate_size"] + cfg["shared_expert_intermediate_size"] else: d_ff = int(cfg.get("intermediate_size", cfg.get("ffn_hidden_size"))) # llama-4 uses intermediate_size_mlp for main mlp vocab_size = int(cfg["vocab_size"])
# per-head dimension (assume divisible) d_k = d_model // n_heads kv_dim = n_kv_heads * d_k
B = batch_size L = seq_len T = 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 each def proj_flops(L_tokens: int) -> int: q = 2 * B * L_tokens * d_model * d_model o = 2 * B * L_tokens * d_model * d_model k = 2 * B * L_tokens * d_model * kv_dim v = 2 * B * L_tokens * d_model * kv_dim return 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_k def attn_core_prefill_flops(L_tokens: int) -> int: return 4 * B * n_heads * (L_tokens ** 2) * d_k
def 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_ff def mlp_flops(L_tokens: int) -> int: # gpt-oss does not use gate function (6 → 4), registers per-expert intermediate size if "gpt-oss" in config_path: return 4 * B * L_tokens * d_model * d_ff * int(cfg["num_experts_per_tok"]) # llama-4 use 2-layer mlp without gating on attn score, before the main mlp elif "Llama-4" in config_path: return B * L_tokens * d_model * (6 * d_ff + 4 * int(cfg["intermediate_size"])) else: return 6 * B * L_tokens * d_model * d_ff
# LM head (final linear to vocab) for N tokens: 2 * B * N * d_model * vocab_size def 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)
if 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 = 0 else: 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 )
# Logits at each decode step lm_decode = lm_head_flops(T)
decode_total = stack_decode + lm_decode
# ---- packing results (TFLOPs) ---- toT = lambda x: x / 1e12
results = { # Inputs "batch_size": B, "seq_len": L, "gen_len": T, "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 breakdown "prefill_stack_TFLOPs": toT(stack_prefill), "prefill_proj_TFLOPs": toT(n_layers * proj_prefill_per_layer), "prefill_attn_core_TFLOPs": toT(n_layers * attn_prefill_per_layer), "prefill_mlp_TFLOPs": toT(n_layers * mlp_prefill_per_layer), "prefill_lm_head_TFLOPs": toT(lm_prefill), "prefill_total_TFLOPs": toT(prefill_total),
# Decode breakdown "decode_stack_TFLOPs": toT(stack_decode), "decode_proj_TFLOPs": toT(n_layers * T * proj_decode_per_layer_per_step), "decode_attn_core_TFLOPs": toT(n_layers * attn_decode_per_layer_total), "decode_mlp_TFLOPs": toT(n_layers * T * mlp_decode_per_layer_per_step), "decode_lm_head_TFLOPs": toT(lm_decode), "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
def mla_model_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" attention_type: Optional[str] = None, # "mha" | "mla" | None (auto-detect) mla_latents: Optional[int] = None, mla_mode: str = "reuse", # "reuse" | "recompute") -> Dict[str, float]: """ Compute theoretical FLOPs (TFLOPs) for DeepSeek-R1 (or similar) inference.
Key points & assumptions (be sure to read): - This function supports both classic dense Multi-Head Attention (MHA) and DeepSeek's Multi-Head Latent Attention (MLA). MLA reduces the attention core from O(L^2) to O(L * M) where M is the number of latent tokens (per head or global depending on implementation). See DeepSeek-V2/V3 papers. MLA also admits two execution schemes: 'reuse' (compute latent KV once at prefill and reuse during decode) and 'recompute' (recompute / update latents per step). The hardware analysis and community descriptions motivated these cost models. - MoE MLP: we model a single shared expert (always executed) plus `num_experts_per_tok` *activated* experts per token (as reported in the config). We expose separate FLOP entries for shared vs activated experts. - Projection FLOPs follow your previous convention: 2 FLOPs per multiply-add, and we keep the same projection accounting for Q/K/V/O. The attention *core* cost is replaced with MLA formulas when used. - Because MLA variants differ in implementation details across repos, you can pass `mla_latents` to set the latent length (if None a conservative default is used). The default is chosen to reflect a moderate compression (an inferrable but tunable value). - All counts are for forward-only inference, and result units are TFLOPs.
Parameters: mla_latents: recommended to pass a locale-specific sensible value (e.g., 64, 128, 256). If None, the function will pick a conservative default: min(256, max(1, seq_len // 16)). mla_mode: "reuse" (default) counts the one-time cost to build latents at prefill and then low-cost per-step decode attention against the smaller latent set. "recompute" falls back to recomputing compressed latents per decode step — yielding higher compute but lower memory footprint (useful to model alternate execution strategies). See hardware-centric analysis. """
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)
# ---- required hyperparams ---- d_model = int(cfg["hidden_size"]) n_layers = int(cfg["num_hidden_layers"]) n_heads = int(cfg["num_attention_heads"]) n_kv_heads = int(cfg.get("num_key_value_heads", n_heads)) d_ff = int(cfg.get("moe_intermediate_size", cfg.get("intermediate_size"))) vocab_size = int(cfg["vocab_size"])
# MoE-specific n_experts_total = int(cfg.get("n_routed_experts", cfg.get("num_experts", cfg.get("num_local_experts", 0)))) n_shared_experts = int(cfg.get("n_shared_experts", cfg.get("n_shared_experts", 0))) n_experts_per_tok = int(cfg.get("num_experts_per_tok", cfg.get("num_experts_per_tok", 0)))
# Detect/override attention type: cfg_model_type = cfg.get("model_type", "").lower() if attention_type is None: # If model type contains deepseek or config contains MLA-related fields, default to mla if "deepseek" in cfg_model_type or cfg.get("moa") or cfg.get("n_group") is not None: attention_type = "mla" else: attention_type = "mha"
# MLA default latent length (tunable). MLA papers/reports show M << L; choose conservative default. if mla_latents is None: mla_latents = int(cfg.get("kv_lora_rank", max(1, min(256, max(1, seq_len // 16)))))
# per-head dimension (assume divisible) d_k = d_model // n_heads kv_dim = n_kv_heads * d_k
B = batch_size L = seq_len T = gen_len
# ---- helpers (FLOPs, NOT TFLOPs) ---- # Linear projections per layer for a sequence of length L_tokens. # Keep original projection accounting for Q, O, K, V (this counts the input linear layers). def proj_flops(L_tokens: int) -> int: q = 2 * B * L_tokens * d_model * d_model # Wq : d_model x d_model o = 2 * B * L_tokens * d_model * d_model # Wo : d_model x d_model (output projection) # For K and V we keep the same "dense" projection accounting here. MLA adds separate # compression costs which we model in attention_core_mla below. k = 2 * B * L_tokens * d_model * kv_dim v = 2 * B * L_tokens * d_model * kv_dim return q + k + v + o
# Dense attention core (classic quadratic) def attn_core_prefill_mha(L_tokens: int) -> int: # approximate QK^T + softmax@V cost return 4 * B * n_heads * (L_tokens ** 2) * d_k
def attn_core_decode_mha(cache_len: int) -> int: return 4 * B * n_heads * cache_len * d_k
# MLA attention core (approximate): replace L^2 with L * M. # We model two things: # 1) core: Q @ K_latent^T and softmax@V_latent -> ~ 4 * B * n_heads * L * M * d_k # 2) one-time compression cost at prefill to build the latent K/V (approximation). # hardware analyses show there are two execution schemes: re-use (compress once) vs recompute. # We approximate the one-time compression cost as: 2 * B * L * d_model * (mla_latents / max(1,L)) # which simplifies to ~ 2 * B * d_model * mla_latents (a compact, tunable approximation). # See DeepSeek papers and hardware analysis for details. def attn_core_prefill_mla(L_tokens: int) -> int: M = mla_latents core = 4 * B * n_heads * L_tokens * M * d_k # one-time compress cost (approximation; tunable) compress = int(2 * B * d_model * M) return core + compress
def attn_core_decode_mla_reuse(L_tokens: int, T_steps: int) -> int: # If latents are reused, each decode step attends Q (1 token) against latent keys size M: # cost per step ~ 4 * B * n_heads * M * d_k return 4 * B * n_heads * d_k * (T_steps * mla_latents)
def attn_core_decode_mla_recompute(L_tokens: int, T_steps: int) -> int: # recomputing latents each step approximates back toward classic cost (worse-case). # fall back to the MHA-like growing-cache sum as conservative upper bound: return 4 * B * n_heads * d_k * (T_steps * L_tokens + (T_steps * (T_steps - 1)) // 2)
# MLP costs: # Single expert (SwiGLU-like gated): approx 6 * B * L * d_model * d_ff def single_expert_flops(L_tokens: int) -> int: return 6 * B * L_tokens * d_model * d_ff
# MoE MLP breakdown: shared experts (n_shared_experts) executed every token # plus activated experts (n_experts_per_tok) *per-token* (sparse routing). # Note: some implementations add extra routing overhead; we ignore the small routing bookkeeping cost here. def moe_mlp_flops_shared(L_tokens: int) -> int: # FLOPs for shared (always executed). If config says n_shared_experts>1, multiply accordingly. return n_shared_experts * single_expert_flops(L_tokens)
def moe_mlp_flops_activated(L_tokens: int) -> int: # Activated experts per token: each token runs n_experts_per_tok experts (sparse). return n_experts_per_tok * single_expert_flops(L_tokens)
# LM head def 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)
if attention_type == "mha": attn_prefill_per_layer = attn_core_prefill_mha(L) # no extra MLA compress cost mla_extra_prefill_per_layer = 0 elif attention_type == "mla": attn_prefill_per_layer = attn_core_prefill_mla(L) # the compression cost is included in attn_core_prefill_mla as 'compress' term mla_extra_prefill_per_layer = max(0, attn_prefill_per_layer - (4 * B * n_heads * (L ** 2) * d_k)) else: raise ValueError("attention_type must be one of {'mha','mla'}")
# MLP (MoE) mlp_prefill_shared_per_layer = moe_mlp_flops_shared(L) mlp_prefill_activated_per_layer = moe_mlp_flops_activated(L) mlp_prefill_per_layer = mlp_prefill_shared_per_layer + mlp_prefill_activated_per_layer
stack_prefill = n_layers * (proj_prefill_per_layer + attn_prefill_per_layer + mlp_prefill_per_layer)
if 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 = 0 else: raise ValueError("prefill_logits must be one of {'all','last','none'}")
prefill_total = stack_prefill + lm_prefill
# ---- DECODE (T steps) ---- proj_decode_per_layer_per_step = proj_flops(1) mlp_decode_per_layer_per_step_shared = moe_mlp_flops_shared(1) mlp_decode_per_layer_per_step_activated = moe_mlp_flops_activated(1) mlp_decode_per_layer_per_step = mlp_decode_per_layer_per_step_shared + mlp_decode_per_layer_per_step_activated
if attention_type == "mha": # attention grows with cache: L, L+1, ..., L+T-1 attn_decode_per_layer_total = 4 * B * n_heads * d_k * (T * L + (T * (T - 1)) // 2) mla_extra_decode_term = 0 else: # mla if mla_mode == "reuse": attn_decode_per_layer_total = attn_core_decode_mla_reuse(L, T) mla_extra_decode_term = 0 # compression cost already accounted in prefill elif mla_mode == "recompute": attn_decode_per_layer_total = attn_core_decode_mla_recompute(L, T) # recompute implies we pay full compress-like cost in decode as well; # approximate by adding the same compress cost per layer per decode (conservative) per_step_compress = int(2 * B * d_model * mla_latents) mla_extra_decode_term = n_layers * (per_step_compress * T) else: raise ValueError("mla_mode must be one of {'reuse','recompute'}")
stack_decode = n_layers * ( T * (proj_decode_per_layer_per_step + mlp_decode_per_layer_per_step) + attn_decode_per_layer_total ) + mla_extra_decode_term
lm_decode = lm_head_flops(T) decode_total = stack_decode + lm_decode
# ---- pack results (TFLOPs) ---- toT = lambda x: x / 1e12
results = { # Inputs / config readout "batch_size": B, "seq_len": L, "gen_len": T, "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, "num_experts_total": n_experts_total, "num_shared_experts": n_shared_experts, "num_experts_per_tok": n_experts_per_tok, "attention_type": attention_type, "mla_latents": mla_latents if attention_type == "mla" else None, "mla_mode": mla_mode if attention_type == "mla" else None, "prefill_logits_mode": prefill_logits,
# Prefill breakdown "prefill_stack_TFLOPs": toT(stack_prefill), "prefill_proj_TFLOPs": toT(n_layers * proj_prefill_per_layer), "prefill_attn_core_TFLOPs": toT(n_layers * attn_prefill_per_layer), "prefill_mlp_shared_TFLOPs": toT(n_layers * mlp_prefill_shared_per_layer), "prefill_mlp_activated_TFLOPs": toT(n_layers * mlp_prefill_activated_per_layer), "prefill_mlp_TFLOPs": toT(n_layers * mlp_prefill_per_layer), "prefill_lm_head_TFLOPs": toT(lm_prefill), "prefill_total_TFLOPs": toT(prefill_total),
# Decode breakdown "decode_stack_TFLOPs": toT(stack_decode), "decode_proj_TFLOPs": toT(n_layers * T * proj_decode_per_layer_per_step), "decode_attn_core_TFLOPs": toT(n_layers * attn_decode_per_layer_total), "decode_mlp_shared_TFLOPs": toT(n_layers * T * mlp_decode_per_layer_per_step_shared), "decode_mlp_activated_TFLOPs": toT(n_layers * T * mlp_decode_per_layer_per_step_activated), "decode_mlp_TFLOPs": toT(n_layers * T * mlp_decode_per_layer_per_step), "decode_lm_head_TFLOPs": toT(lm_decode), "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 results1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import jsonimport torchfrom torch.utils.data import IterableDataset, DataLoaderfrom transformers import AutoTokenizer, AutoModelForCausalLMfrom tqdm import tqdmfrom math import ceil
class JsonlIterableDataset(IterableDataset): """Sequential streaming dataset for jsonl lines of the form {"text": "..."}.""" def __init__(self, jsonl_path: str, tokenizer, target_token_length: int): super().__init__() self.jsonl_path = jsonl_path self.tokenizer = tokenizer if tokenizer.pad_token is None: tokenizer.pad_token = tokenizer.eos_token self.target_token_length = target_token_length
def __iter__(self): worker_info = torch.utils.data.get_worker_info() if worker_info is None: # Single-process data loading start, stride = 0, 1 else: # Multi-worker: split work evenly start = worker_info.id stride = worker_info.num_workers
with open(self.jsonl_path, "r", encoding="utf-8") as f: for idx, line in enumerate(f): if idx % stride != start: continue data = json.loads(line) text = data["text"]
tokens = self.tokenizer( text, truncation=True, padding="max_length", max_length=self.target_token_length, return_tensors="pt" ) yield { "input_ids": tokens["input_ids"].squeeze(0), "attention_mask": tokens["attention_mask"].squeeze(0), }
def calculate_negative_log_likelihood( model_path: str, jsonl_path: str, target_token_length: int, batch_size: int = 8, device: str = "cuda" if torch.cuda.is_available() else "cpu", num_workers: int = 2, num_samples: int = None,) -> torch.Tensor: """ Streaming, batched NLL computation for a large jsonl dataset using deterministic sequential access. """ tokenizer = AutoTokenizer.from_pretrained(model_path, device_map="auto", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained(model_path, device_map="auto", torch_dtype="auto", attn_implementation="flash_attention_2" if "TinyLlama" not in model_path else "sdpa", trust_remote_code=True) model.eval()
dataset = JsonlIterableDataset(jsonl_path, tokenizer, target_token_length) dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=num_workers)
entropies = []
for i, batch in enumerate(tqdm(dataloader, total=ceil(num_samples / batch_size) if num_samples is not None else None, desc=f"Calculating Entropy for {model_path.split('/')[-1]}")): if i % 100 == 0: torch.cuda.empty_cache()
input_ids = batch["input_ids"].to(device) attention_mask = batch["attention_mask"].to(device)
with torch.no_grad(): outputs = model(input_ids=input_ids, attention_mask=attention_mask, use_cache=False) logits = outputs.logits # (batch, seq_len, vocab_size)
# Per-token NLL logits = torch.softmax(logits[:, :, :len(tokenizer)].to(dtype=torch.float32), dim=-1) effective_probs = torch.gather(logits[:, :target_token_length, :], -1, input_ids[:, 1:].unsqueeze(-1)).squeeze(-1) entropy = -torch.log2(effective_probs) entropy[attention_mask[:, 1:] == 0] = torch.nan
entropies.append(entropy.cpu())
return torch.cat(entropies, dim=0)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import jsonimport numpy as npfrom transformers import AutoTokenizerfrom multiprocessing import Pool, cpu_countimport tqdm
# --- Global Tokenizer Initialization ---# This function initializes the tokenizer for each worker process.# We define it globally so it's available to the pool's initializer.tokenizer = None
def init_tokenizer(model_path, target_token_length=1024): """Initializer for each worker process.""" global tokenizer tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True) tokenizer.target_token_length = target_token_length
# --- Worker Function ---# This is the function that each worker process will execute.def process_line(line): """ Processes a single line from the JSONL file to count tokens. Returns the token count or None if an error occurs. """ try: # Load the JSON object from the line data = json.loads(line) text = data.get("text")
if text and isinstance(text, str): # The global tokenizer, initialized for this process, is used here ids = tokenizer.encode(text, truncation=True, max_length=tokenizer.target_token_length) ids = ids[1:] s = tokenizer.decode(ids) return len(s.encode('utf-8')) * 8 / len(ids) else: # Return None for lines without a valid 'text' field return None except (json.JSONDecodeError, AttributeError): # Return None for malformed JSON or other errors return None
def calculate_text_size_per_token(file_path, model_path, target_token_length=1024): """ Calculates token count statistics in a parallelized manner.
Args: file_path (str): The path to the JSONL file. """ init_tokenizer(model_path, target_token_length)
try: with open(file_path, 'r', encoding='utf-8') as f: lines = f.readlines() except FileNotFoundError: print(f"Error: The file '{file_path}' was not found.") return except Exception as e: print(f"An unexpected error occurred while reading the file: {e}") return if not lines: print("File is empty. No statistics to calculate.") return
# Determine the number of processes to use num_processes = cpu_count() // 2 print(f"Starting parallel processing with {num_processes} workers...")
token_counts = [] # Create a pool of worker processes # The initializer runs `init_tokenizer` once for each worker process. with Pool(processes=num_processes, initializer=init_tokenizer, initargs=(model_path, target_token_length)) as pool: # Use imap_unordered for efficiency, as order doesn't matter. results = list(tqdm.tqdm(pool.imap_unordered(process_line, lines), total=len(lines), desc="Processing lines"))
# Filter out the None results from failed lines token_counts = [count for count in results if count is not None]
if not token_counts: print("No valid text lines were found to calculate statistics.") return
# Calculate and print statistics counts_array = np.array(token_counts)
return { "file_path": {file_path}, "tokenizer": {tokenizer.name_or_path}, "vocab_size": {len(tokenizer)}, "max_sample_length": target_token_length, "total_valid_lines": len(counts_array), "mean_text_size": round(np.mean(counts_array), 2), "min_text_size": np.min(counts_array), "max_text_size": np.max(counts_array), }README.mdAdded+90
assets/ic_mixed.pngAdded

Large File Pointer Details
- SHA256: ac56cb53fd0a9ca5276febbd459b5b4e506138c42434dda3583e40a855defed2
- Pointer size: 131 Bytes
- Size of remote file: 212 kB
calc_ic.pyAdded+77
flops.pyAdded+439
likelihood.pyAdded+89
text_size.pyAdded+97