Skip to content
Merged
Show file tree
Hide file tree
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
74 changes: 72 additions & 2 deletions scripts/prune_layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,13 @@
``kda_layers`` and ``dsa_config.dsa_layers``, 1-based entries; the general
``layer_types`` list by position), ``num_nextn_predict_layers`` = 0 and no
MTP / draft tensors (``--keep-layer-tables`` leaves the tables as they are,
as some published cut-down checkpoints do);
as some published cut-down checkpoints do). A hybrid (Mamba) config's
per-layer pattern (Nemotron-H: ``hybrid_override_pattern``, the
``layers_block_type`` list, or both, which must agree) is the layer structure
itself and is always cut to N entries; a cut of a model with attention layers
must keep at least one (``*``, ``attention``, ``full_attention``), else the
script stops and names the smallest ``--layers`` that does; a character or
kind the script does not know stops it too;
* every other file of the checkpoint (tokenizer, processors, modeling code,
generation config) copied as it is.

Expand Down Expand Up @@ -57,6 +63,13 @@
"dsa_config": ("dsa_layers",)}
# config keys that list layer indices, 0-based (other families)
ZERO_BASED_LAYER_LISTS = ("moe_layers", "dense_layers", "sliding_window_layers", "full_attention_layers")
# hybrid (Mamba) configs: one entry per layer, the layer structure itself (Nemotron-H)
HYBRID_PATTERN = "hybrid_override_pattern" # a string, one character per layer
HYBRID_BLOCKS = "layers_block_type" # the newer configs' list of layer kinds
HYBRID_KINDS = {"M": "mamba", "*": "attention", "-": "mlp", "E": "moe"} # the pattern's characters
# the list's kinds (transformers 5 saves full_attention / linear_attention); other kinds are refused
HYBRID_BLOCK_KINDS = frozenset({"mamba", "attention", "full_attention", "linear_attention", "mlp", "moe"})
ATTENTION_KINDS = frozenset({"*", "attention", "full_attention"}) # softmax attention, in either form
HEADER_LEN = 8


Expand Down Expand Up @@ -170,15 +183,72 @@ def prune_config(config: dict[str, Any], layers: int, *, keep_tables: bool = Fal
text["layer_types"] = text["layer_types"][:layers]
if isinstance(text.get("first_k_dense_replace"), int):
text["first_k_dense_replace"] = min(int(text["first_k_dense_replace"]), layers)
cut_hybrid_pattern(text, layers)
if drop_vision:
out.pop("vision_config", None)
return out


def hybrid_tables(text: dict[str, Any]) -> list[tuple[str, list[str]]]:
"""``[(key, per-layer kinds)]`` of a hybrid (Mamba) config: Nemotron-H's
``hybrid_override_pattern`` string (one character per layer, :data:`HYBRID_KINDS`)
and / or the ``layers_block_type`` list of the newer Nemotron-H configs
(:data:`HYBRID_BLOCK_KINDS`); empty for any other config. A character or kind this
script does not know raises (a cut of a structure it cannot read would be a guess).
Both present: they must name the same layers."""
found: list[tuple[str, list[str]]] = []
pattern = text.get(HYBRID_PATTERN)
if isinstance(pattern, str) and pattern:
unknown = sorted({c for c in pattern if c not in HYBRID_KINDS})
if unknown:
raise PruneError(f"{HYBRID_PATTERN} has characters {unknown} this script does not know "
f"(known: {sorted(HYBRID_KINDS)}): not cutting a structure it cannot read")
found.append((HYBRID_PATTERN, [HYBRID_KINDS[c] for c in pattern]))
blocks = text.get(HYBRID_BLOCKS)
if isinstance(blocks, list) and blocks:
unknown = sorted({str(b) for b in blocks if not isinstance(b, str) or b not in HYBRID_BLOCK_KINDS})
if unknown:
raise PruneError(f"{HYBRID_BLOCKS} has kinds {unknown} this script does not know "
f"(known: {sorted(HYBRID_BLOCK_KINDS)}): not cutting a structure it cannot read")
found.append((HYBRID_BLOCKS, [str(b) for b in blocks]))
if len(found) == 2:
same = [_attention_as_one(k) for k in found[0][1]] == [_attention_as_one(k) for k in found[1][1]]
if not same:
raise PruneError(f"{HYBRID_PATTERN} and {HYBRID_BLOCKS} name different layers: not cutting either")
return found


def _attention_as_one(kind: str) -> str:
return "attention" if kind in ATTENTION_KINDS else kind


def cut_hybrid_pattern(text: dict[str, Any], layers: int) -> None:
"""Cut a hybrid config's per-layer pattern (each form present) to its first ``layers``
entries, in place. The pattern is the layer structure itself (Megatron builds a hybrid
model's layers from it, one per entry), so it is cut also under
``--keep-layer-tables``. A model with attention layers (:data:`ATTENTION_KINDS`) keeps
at least one: a cut without one raises, naming the first attention layer and the
smallest ``--layers`` that keeps it."""
tables = hybrid_tables(text)
for key, kinds in tables:
if len(kinds) < layers:
raise PruneError(f"{key} has {len(kinds)} entries, fewer than the {layers} layers to keep")
first = next((i for i, kind in enumerate(kinds) if kind in ATTENTION_KINDS), None)
if first is not None and first >= layers:
raise PruneError(f"the first {layers} layers of {key} have no attention layer (the first is layer "
f"{first}, 0-based): a hybrid cut needs one; keep at least --layers {first + 1}")
for key, _kinds in tables:
text[key] = text[key][:layers]


def kept_layer_kinds(config: dict[str, Any], layers: int) -> dict[int, str]:
"""For the report: ``dense`` / ``kda`` / ``mla`` per kept layer of a Kimi K3
config (empty for other families)."""
config, ``mamba`` / ``attention`` / ``mlp`` / ``moe`` per kept layer of a hybrid
(Nemotron-H) config (empty for other families)."""
text = config.get("text_config") if isinstance(config.get("text_config"), dict) else config
hybrid = hybrid_tables(text)
if hybrid:
return dict(enumerate(hybrid[0][1][:layers]))
linear = text.get("linear_attn_config") if isinstance(text.get("linear_attn_config"), dict) else {}
full = {int(i) for i in linear.get("full_attn_layers", [])}
dense_k = int(text.get("first_k_dense_replace", 0) or 0)
Expand Down
66 changes: 66 additions & 0 deletions tests/data/prune_layers/nemotron_3_nano_30b_a3b.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
{
"architectures": [
"NemotronHForCausalLM"
],
"attention_bias": false,
"attention_dropout": 0.0,
"auto_map": {
"AutoConfig": "configuration_nemotron_h.NemotronHConfig",
"AutoModel": "modeling_nemotron_h.NemotronHForCausalLM",
"AutoModelForCausalLM": "modeling_nemotron_h.NemotronHForCausalLM"
},
"bos_token_id": 1,
"chunk_size": 128,
"conv_kernel": 4,
"eos_token_id": 2,
"expand": 2,
"head_dim": 128,
"hidden_dropout": 0.0,
"hidden_size": 2688,
"hybrid_override_pattern": "MEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEM*EMEMEMEM*EMEMEMEME",
"initializer_range": 0.02,
"intermediate_size": 1856,
"layer_norm_epsilon": 1e-05,
"mamba_head_dim": 64,
"mamba_hidden_act": "silu",
"mamba_num_heads": 64,
"mamba_proj_bias": false,
"mamba_ssm_cache_dtype": "float32",
"max_position_embeddings": 262144,
"mlp_bias": false,
"mlp_hidden_act": "relu2",
"model_type": "nemotron_h",
"moe_intermediate_size": 1856,
"moe_shared_expert_intermediate_size": 3712,
"n_group": 1,
"n_groups": 8,
"n_routed_experts": 128,
"n_shared_experts": 1,
"norm_eps": 1e-05,
"norm_topk_prob": true,
"num_attention_heads": 32,
"num_experts_per_tok": 6,
"num_hidden_layers": 52,
"num_key_value_heads": 2,
"num_logits_to_keep": 1,
"pad_token_id": 0,
"partial_rotary_factor": 1.0,
"rescale_prenorm_residual": true,
"residual_in_fp32": false,
"rope_theta": 10000,
"routed_scaling_factor": 2.5,
"sliding_window": null,
"ssm_state_size": 128,
"tie_word_embeddings": false,
"time_step_floor": 0.0001,
"time_step_max": 0.1,
"time_step_min": 0.001,
"topk_group": 1,
"torch_dtype": "bfloat16",
"transformers_version": "4.55.4",
"use_bias": false,
"use_cache": true,
"use_conv_bias": true,
"use_mamba_kernels": true,
"vocab_size": 131072
}
54 changes: 54 additions & 0 deletions tests/data/prune_layers/nemotron_h_nano_4b.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"architectures": [
"NemotronHForCausalLM"
],
"attention_bias": false,
"attention_dropout": 0.0,
"head_dim": 128,
"auto_map": {
"AutoConfig": "configuration_nemotron_h.NemotronHConfig",
"AutoModelForCausalLM": "modeling_nemotron_h.NemotronHForCausalLM"
},
"bos_token_id": 1,
"chunk_size": 256,
"conv_kernel": 4,
"eos_token_id": 2,
"expand": 2,
"hidden_dropout": 0.0,
"hidden_size": 3136,
"hybrid_override_pattern": "M-M-M-MM-M-M*-M-M*-M-M-M*-M-M-MM*-MMM-M-M-",
"initializer_range": 0.02,
"intermediate_size": 12544,
"layer_norm_epsilon": 1e-05,
"mamba_head_dim": 80,
"mamba_hidden_act": "silu",
"mamba_num_heads": 96,
"mamba_proj_bias": false,
"max_position_embeddings": 262144,
"mlp_bias": false,
"mlp_hidden_act": "relu2",
"model_type": "nemotron_h",
"n_groups": 8,
"num_attention_heads": 40,
"num_hidden_layers": 42,
"num_key_value_heads": 8,
"num_logits_to_keep": 1,
"pad_token_id": 0,
"rescale_prenorm_residual": true,
"residual_in_fp32": false,
"rms_norm_eps": 1e-05,
"sliding_window": null,
"ssm_state_size": 128,
"tie_word_embeddings": false,
"time_step_floor": 0.0001,
"time_step_max": 0.1,
"time_step_min": 0.001,
"time_step_rank": 256,
"torch_dtype": "bfloat16",
"transformers_version": "4.53.0",
"use_bias": false,
"use_cache": true,
"use_conv_bias": true,
"use_mamba_kernels": true,
"vocab_size": 131072
}
148 changes: 148 additions & 0 deletions tests/test_prune_layers.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import importlib.util
import json
import re
import struct
import subprocess
import sys
Expand Down Expand Up @@ -220,3 +221,150 @@ def file(self, name):
assert pl.open_source("hf://org/model").repo == "org/model"
with pytest.raises(pl.PruneError, match="not a directory"):
pl.open_source(str(tmp_path / "missing"))


# -- hybrid (Mamba) configs: Nemotron-H ---------------------------------------------

NEMOTRON_H = REPO / "tests" / "data" / "prune_layers" / "nemotron_h_nano_4b.json" # its config.json, as published


def _nemotron_h() -> dict:
return json.loads(NEMOTRON_H.read_text())


def test_the_hybrid_pattern_is_cut_with_the_layers(pl):
"""Megatron builds a hybrid model's layers from hybrid_override_pattern, one per
character: the cut keeps exactly the first N characters (also under
--keep-layer-tables, which leaves only the index tables as they are)."""
cfg = _nemotron_h()
pattern = cfg["hybrid_override_pattern"]
assert cfg["num_hidden_layers"] == len(pattern) == 42 and pattern.index("*") == 12
for layers in (13, 16, 42):
out = pl.prune_config(cfg, layers)
assert out["num_hidden_layers"] == layers and out["hybrid_override_pattern"] == pattern[:layers]
assert pl.prune_config(cfg, layers, keep_tables=True)["hybrid_override_pattern"] == pattern[:layers]
assert cfg["hybrid_override_pattern"] == pattern # the input is not changed
kinds = pl.kept_layer_kinds(cfg, 14)
assert kinds[0] == "mamba" and kinds[1] == "mlp" and kinds[12] == "attention" and len(kinds) == 14


def test_a_hybrid_cut_without_an_attention_layer_is_refused(pl, tmp_path):
with pytest.raises(pl.PruneError, match=r"the first 12 layers of hybrid_override_pattern have no attention "
r"layer \(the first is layer 12, 0-based\).*--layers 13"):
pl.prune_config(_nemotron_h(), 12)
(tmp_path / "src").mkdir()
(tmp_path / "src" / "config.json").write_text(NEMOTRON_H.read_text())
_safetensors(tmp_path / "src" / "model.safetensors",
{f"backbone.layers.{i}.mixer.in_proj.weight": _tensor("w", i) for i in range(42)})
bad = subprocess.run([sys.executable, "-I", str(SCRIPT), str(tmp_path / "src"), str(tmp_path / "d"),
"--layers", "8", "--dry-run"], capture_output=True, text=True)
assert bad.returncode == 1 and "keep at least --layers 13" in bad.stderr and not (tmp_path / "d").exists()
# a hybrid model without attention layers (all Mamba / MLP) has nothing to keep
assert pl.prune_config({"num_hidden_layers": 4, "hybrid_override_pattern": "M-M-"}, 2)[
"hybrid_override_pattern"] == "M-"


def test_the_layers_block_type_list_is_cut_like_the_pattern(pl):
"""The newer Nemotron-H configs (Nemotron 3.5) list the layer kinds instead."""
blocks = ["mamba", "moe", "mamba", "moe", "mamba", "attention", "mamba", "moe"]
cfg = {"num_hidden_layers": 8, "layers_block_type": blocks, "num_nextn_predict_layers": 2,
"mtp_layers_block_type": ["attention", "moe"]}
out = pl.prune_config(cfg, 6)
assert out["layers_block_type"] == blocks[:6] and out["num_nextn_predict_layers"] == 0
assert pl.kept_layer_kinds(cfg, 6) == dict(enumerate(blocks[:6]))
with pytest.raises(pl.PruneError, match="first is layer 5.*--layers 6"):
pl.prune_config(cfg, 5)
with pytest.raises(pl.PruneError, match="has 3 entries, fewer than the 4 layers"):
pl.prune_config({"num_hidden_layers": 8, "hybrid_override_pattern": "M*M"}, 4)


def test_a_nemotron_h_checkpoint_is_cut_end_to_end(pl, tmp_path):
src = tmp_path / "src"
src.mkdir()
(src / "config.json").write_text(NEMOTRON_H.read_text())
tensors = {"backbone.embeddings.weight": _tensor("emb", 200), "backbone.norm_f.weight": _tensor("nf", 201),
"lm_head.weight": _tensor("head", 202)}
for i, kind in enumerate(_nemotron_h()["hybrid_override_pattern"]):
tensors[f"backbone.layers.{i}.norm.weight"] = _tensor("n", i)
name = {"M": "mixer.in_proj", "*": "mixer.q_proj", "-": "mixer.up_proj"}[kind]
tensors[f"backbone.layers.{i}.{name}.weight"] = _tensor("w", i)
_safetensors(src / "model.safetensors", tensors)
result = pl.prune(pl.LocalSource(src), tmp_path / "dest", 16, log=lambda *_: None)
cfg = json.loads((tmp_path / "dest" / "config.json").read_text())
assert cfg["num_hidden_layers"] == 16 and cfg["hybrid_override_pattern"] == "M-M-M-MM-M-M*-M-"
assert cfg["auto_map"] == _nemotron_h()["auto_map"] # the remote-code config the model needs stays
kept = set(json.loads((tmp_path / "dest" / "model.safetensors.index.json").read_text())["weight_map"])
assert {pl.layer_of(n) for n in kept} - {None} == set(range(16)) and "lm_head.weight" in kept
report = json.loads((tmp_path / "dest" / "PRUNE.json").read_text())
assert report["layer_kinds"]["12"] == "attention" and len(report["layer_kinds"]) == 16
assert result["layer_kinds"][13] == "mlp"


NEMOTRON_MOE = REPO / "tests" / "data" / "prune_layers" / "nemotron_3_nano_30b_a3b.json" # 'E' MoE layers


def test_a_layers_block_type_list_of_transformers_5_is_read_as_attention(pl):
"""transformers 5 saves the list with full_attention / linear_attention: full_attention
counts as the attention a cut must keep, linear_attention does not."""
blocks = ["mamba", "moe", "linear_attention", "moe", "mamba", "full_attention", "mamba", "moe"]
cfg = {"num_hidden_layers": 8, "layers_block_type": blocks}
assert pl.prune_config(cfg, 6)["layers_block_type"] == blocks[:6]
with pytest.raises(pl.PruneError, match="first is layer 5.*--layers 6"):
pl.prune_config(cfg, 5) # a linear_attention layer is no attention layer


def test_both_hybrid_forms_are_cut_and_must_agree(pl):
blocks = ["mamba", "mlp", "mamba", "full_attention", "mamba", "mlp"]
cfg = {"num_hidden_layers": 6, "hybrid_override_pattern": "M-M*M-", "layers_block_type": blocks}
out = pl.prune_config(cfg, 4)
assert out["hybrid_override_pattern"] == "M-M*" and out["layers_block_type"] == blocks[:4]
with pytest.raises(pl.PruneError, match="first is layer 3"):
pl.prune_config(cfg, 3)
other = dict(cfg, layers_block_type=["mamba", "moe", "mamba", "attention", "mamba", "mlp"])
with pytest.raises(pl.PruneError, match="name different layers"):
pl.prune_config(other, 4)


@pytest.mark.parametrize("pattern, symbol", [("M-D*M-", "D"), ("M-|*M-", "|"), ("M-/*M-", "/"), ("m-M*M-", "m")])
def test_an_unknown_pattern_character_is_refused(pl, pattern, symbol):
with pytest.raises(pl.PruneError, match=re.escape(f"characters ['{symbol}'] this script does not know")):
pl.prune_config({"num_hidden_layers": 6, "hybrid_override_pattern": pattern}, 4)
with pytest.raises(pl.PruneError, match=r"kinds \['sparse_attention'\] this script does not know"):
pl.prune_config({"num_hidden_layers": 2, "layers_block_type": ["mamba", "sparse_attention"]}, 2)


def test_a_nemotron_h_moe_checkpoint_keeps_every_expert_of_its_kept_layers(pl, tmp_path):
"""Nemotron 3 Nano 30B-A3B: 'E' layers are MoE layers; the cut keeps all their routed
and shared experts and drops every tensor of the layers after it."""
cfg = json.loads(NEMOTRON_MOE.read_text())
pattern = cfg["hybrid_override_pattern"]
experts = 4 # a few routed experts stand for the checkpoint's n_routed_experts
src = tmp_path / "src"
src.mkdir()
(src / "config.json").write_text(NEMOTRON_MOE.read_text())
tensors = {"backbone.embeddings.weight": _tensor("emb", 200), "backbone.norm_f.weight": _tensor("nf", 201),
"lm_head.weight": _tensor("head", 202)}
for i, kind in enumerate(pattern):
tensors[f"backbone.layers.{i}.norm.weight"] = _tensor("n", i)
if kind == "E":
tensors[f"backbone.layers.{i}.mixer.gate.weight"] = _tensor("g", i)
tensors[f"backbone.layers.{i}.mixer.shared_experts.up_proj.weight"] = _tensor("s", i)
for e in range(experts):
tensors[f"backbone.layers.{i}.mixer.experts.{e}.up_proj.weight"] = _tensor("u", i * 10 + e)
tensors[f"backbone.layers.{i}.mixer.experts.{e}.down_proj.weight"] = _tensor("d", i * 10 + e)
else:
tensors[f"backbone.layers.{i}.mixer.{'in_proj' if kind == 'M' else 'q_proj'}.weight"] = _tensor("w", i)
_safetensors(src / "model.safetensors", tensors)
layers = pattern.index("*") + 2 # through the first attention layer and the MoE layer after it
result = pl.prune(pl.LocalSource(src), tmp_path / "dest", layers, log=lambda *_: None)
out = json.loads((tmp_path / "dest" / "config.json").read_text())
assert out["hybrid_override_pattern"] == pattern[:layers] and out["num_hidden_layers"] == layers
assert out["n_routed_experts"] == cfg["n_routed_experts"] # the expert count is the model's, not cut
kept = set(json.loads((tmp_path / "dest" / "model.safetensors.index.json").read_text())["weight_map"])
moe = [i for i, kind in enumerate(pattern[:layers]) if kind == "E"]
assert moe and all(f"backbone.layers.{i}.mixer.experts.{e}.{w}.weight" in kept
for i in moe for e in range(experts) for w in ("up_proj", "down_proj"))
assert all(f"backbone.layers.{i}.mixer.shared_experts.up_proj.weight" in kept for i in moe)
assert not any(pl.layer_of(n) is not None and pl.layer_of(n) >= layers for n in kept)
assert result["layer_kinds"][moe[0]] == "moe" and result["layer_kinds"][layers - 2] == "attention"
assert len(kept) == len([n for n in tensors if pl.layer_of(n) is None or pl.layer_of(n) < layers])
Loading