Text Generation
Transformers
Safetensors
English
matriochka
matryoshka
nested-models
speculative-decoding
model-suite
distillation
custom_code
Instructions to use nthngdy/matryoshka-3B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use nthngdy/matryoshka-3B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="nthngdy/matryoshka-3B", trust_remote_code=True)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("nthngdy/matryoshka-3B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use nthngdy/matryoshka-3B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "nthngdy/matryoshka-3B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "nthngdy/matryoshka-3B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/nthngdy/matryoshka-3B
- SGLang
How to use nthngdy/matryoshka-3B with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "nthngdy/matryoshka-3B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "nthngdy/matryoshka-3B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "nthngdy/matryoshka-3B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "nthngdy/matryoshka-3B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use nthngdy/matryoshka-3B with Docker Model Runner:
docker model run hf.co/nthngdy/matryoshka-3B
Upload Matriochka cascade up to main
Browse files- modeling_matriochka.py +3 -117
modeling_matriochka.py
CHANGED
|
@@ -107,7 +107,7 @@ class MatriochkaConfig(PretrainedConfig):
|
|
| 107 |
"intermediate_size": 4 * hidden,
|
| 108 |
"vocab_size": base.vocab_size,
|
| 109 |
"max_position_embeddings": base.max_position_embeddings,
|
| 110 |
-
"rope_theta": base
|
| 111 |
"rms_norm_eps": base.rms_norm_eps,
|
| 112 |
"tie_word_embeddings": False,
|
| 113 |
})
|
|
@@ -147,11 +147,9 @@ class _MatriochkaSubModel(nn.Module):
|
|
| 147 |
prev_hidden_size=None signals index 0 (no predecessor).
|
| 148 |
"""
|
| 149 |
|
| 150 |
-
def __init__(self, llama_cfg: LlamaConfig, prev_hidden_size: Optional[int]
|
| 151 |
super().__init__()
|
| 152 |
self.prev_hidden_size = prev_hidden_size
|
| 153 |
-
if attn_implementation is not None:
|
| 154 |
-
llama_cfg._attn_implementation = attn_implementation
|
| 155 |
self.backbone = LlamaForCausalLM(llama_cfg)
|
| 156 |
|
| 157 |
if prev_hidden_size is not None:
|
|
@@ -214,17 +212,15 @@ class MatriochkaForCausalLM(PreTrainedModel):
|
|
| 214 |
|
| 215 |
config_class = MatriochkaConfig
|
| 216 |
base_model_prefix = "lm_model_dict"
|
| 217 |
-
_supports_sdpa = True
|
| 218 |
|
| 219 |
def __init__(self, config: MatriochkaConfig):
|
| 220 |
super().__init__(config)
|
| 221 |
self.lm_model_dict = nn.ModuleDict()
|
| 222 |
|
| 223 |
-
attn_implementation = getattr(config, "_attn_implementation", None)
|
| 224 |
prev_hidden: Optional[int] = None
|
| 225 |
for tag, sub_cfg_dict in zip(config.sub_model_tags, config.sub_model_configs):
|
| 226 |
llama_cfg = LlamaConfig(**sub_cfg_dict)
|
| 227 |
-
self.lm_model_dict[tag] = _MatriochkaSubModel(llama_cfg, prev_hidden
|
| 228 |
prev_hidden = sub_cfg_dict["hidden_size"]
|
| 229 |
|
| 230 |
self.post_init()
|
|
@@ -313,116 +309,6 @@ AutoConfig.register("matriochka", MatriochkaConfig)
|
|
| 313 |
AutoModelForCausalLM.register(MatriochkaConfig, MatriochkaForCausalLM)
|
| 314 |
|
| 315 |
|
| 316 |
-
# ---------------------------------------------------------------------------
|
| 317 |
-
# Upload helper
|
| 318 |
-
# ---------------------------------------------------------------------------
|
| 319 |
-
|
| 320 |
-
def upload_to_hub(
|
| 321 |
-
checkpoint_path: str,
|
| 322 |
-
repo_id: str,
|
| 323 |
-
shapes_config: List[Tuple[int, int, int]],
|
| 324 |
-
tags: List[str],
|
| 325 |
-
base_model_id: str = "HuggingFaceTB/SmolLM2-135M",
|
| 326 |
-
token: Optional[str] = None,
|
| 327 |
-
):
|
| 328 |
-
"""
|
| 329 |
-
Upload workflow.
|
| 330 |
-
|
| 331 |
-
Pushes one branch per tag, each containing the FULL CASCADE up to that tag:
|
| 332 |
-
main → [100M, 300M, 600M, 1B] (all sub-models)
|
| 333 |
-
1B → [100M, 300M, 600M, 1B] (same as main)
|
| 334 |
-
600M → [100M, 300M, 600M]
|
| 335 |
-
300M → [100M, 300M]
|
| 336 |
-
100M → [100M]
|
| 337 |
-
|
| 338 |
-
This means `from_pretrained(..., revision="300M")` downloads exactly the
|
| 339 |
-
weights needed to run the 300M cascade and nothing more.
|
| 340 |
-
|
| 341 |
-
Example
|
| 342 |
-
-------
|
| 343 |
-
from modeling_matriochka import upload_to_hub
|
| 344 |
-
upload_to_hub(
|
| 345 |
-
checkpoint_path="/data/ckpts/.../epoch=0-step=200000.ckpt",
|
| 346 |
-
repo_id="your-org/matriochka-lm",
|
| 347 |
-
shapes_config=[(16,8,64),(11,14,64),(8,22,64),(8,18,96)],
|
| 348 |
-
tags=["100M","300M","600M","1B"],
|
| 349 |
-
)
|
| 350 |
-
"""
|
| 351 |
-
import os, re, shutil, tempfile
|
| 352 |
-
from huggingface_hub import HfApi
|
| 353 |
-
|
| 354 |
-
api = HfApi(token=token)
|
| 355 |
-
this_file = os.path.abspath(__file__)
|
| 356 |
-
|
| 357 |
-
# ── 1. Build full config & model ───────────────────────────────────────
|
| 358 |
-
full_cfg = MatriochkaConfig.from_shape_list(shapes_config, tags, base_model_id)
|
| 359 |
-
full_model = MatriochkaForCausalLM(full_cfg)
|
| 360 |
-
|
| 361 |
-
# ── 2. Load Lightning checkpoint ───────────────────────────────────────
|
| 362 |
-
print(f"Loading checkpoint: {checkpoint_path}")
|
| 363 |
-
ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=False)
|
| 364 |
-
raw_sd = ckpt["state_dict"]
|
| 365 |
-
|
| 366 |
-
# Lightning prepends "model." — strip it.
|
| 367 |
-
# Checkpoint keys: lm_model_dict.100M.model.layers.0…
|
| 368 |
-
# Our keys: lm_model_dict.100M.backbone.model.layers.0…
|
| 369 |
-
def remap_key(k: str) -> str:
|
| 370 |
-
k = k.removeprefix("model.")
|
| 371 |
-
return re.sub(
|
| 372 |
-
r"^(lm_model_dict\.[^.]+\.)(?!backbone\.)",
|
| 373 |
-
r"\1backbone.",
|
| 374 |
-
k,
|
| 375 |
-
)
|
| 376 |
-
cleaned = {remap_key(k): v for k, v in raw_sd.items()}
|
| 377 |
-
|
| 378 |
-
missing, unexpected = full_model.load_state_dict(cleaned, strict=False)
|
| 379 |
-
if missing:
|
| 380 |
-
print(f"[WARN] {len(missing)} missing keys, e.g.: {missing[:3]}")
|
| 381 |
-
if unexpected:
|
| 382 |
-
print(f"[WARN] {len(unexpected)} unexpected keys, e.g.: {unexpected[:3]}")
|
| 383 |
-
|
| 384 |
-
# ── 3. Push each branch ────────────────────────────────────────────────
|
| 385 |
-
api.create_repo(repo_id, exist_ok=True, repo_type="model")
|
| 386 |
-
|
| 387 |
-
def _push(model: MatriochkaForCausalLM, cfg: MatriochkaConfig, branch: str):
|
| 388 |
-
cfg.auto_map = {
|
| 389 |
-
"AutoConfig": "modeling_matriochka.MatriochkaConfig",
|
| 390 |
-
"AutoModelForCausalLM": "modeling_matriochka.MatriochkaForCausalLM",
|
| 391 |
-
}
|
| 392 |
-
with tempfile.TemporaryDirectory() as tmpdir:
|
| 393 |
-
model.save_pretrained(tmpdir)
|
| 394 |
-
cfg.save_pretrained(tmpdir)
|
| 395 |
-
shutil.copy(this_file, os.path.join(tmpdir, "modeling_matriochka.py"))
|
| 396 |
-
if branch != "main":
|
| 397 |
-
try:
|
| 398 |
-
api.create_branch(repo_id, branch=branch, repo_type="model")
|
| 399 |
-
except Exception:
|
| 400 |
-
pass
|
| 401 |
-
api.upload_folder(
|
| 402 |
-
folder_path=tmpdir, repo_id=repo_id, repo_type="model",
|
| 403 |
-
revision=branch,
|
| 404 |
-
commit_message=f"Upload Matriochka cascade up to {branch}",
|
| 405 |
-
)
|
| 406 |
-
print(f"✓ {branch} → {repo_id} [{cfg.sub_model_tags}]")
|
| 407 |
-
|
| 408 |
-
# main = full stack
|
| 409 |
-
_push(full_model, full_cfg, "main")
|
| 410 |
-
|
| 411 |
-
# per-tag branches: truncated cascade
|
| 412 |
-
for tag in tags:
|
| 413 |
-
trunc_cfg = full_cfg.truncated(tag)
|
| 414 |
-
# Build a fresh truncated model and copy the relevant sub-model weights
|
| 415 |
-
trunc_model = MatriochkaForCausalLM(trunc_cfg)
|
| 416 |
-
trunc_sd = {
|
| 417 |
-
k: v for k, v in full_model.state_dict().items()
|
| 418 |
-
if any(k.startswith(f"lm_model_dict.{t}.") for t in trunc_cfg.sub_model_tags)
|
| 419 |
-
}
|
| 420 |
-
trunc_model.load_state_dict(trunc_sd, strict=True)
|
| 421 |
-
_push(trunc_model, trunc_cfg, tag)
|
| 422 |
-
|
| 423 |
-
print("All done!")
|
| 424 |
-
|
| 425 |
-
|
| 426 |
# ---------------------------------------------------------------------------
|
| 427 |
# Smoke-test (python modeling_matriochka.py)
|
| 428 |
# ---------------------------------------------------------------------------
|
|
|
|
| 107 |
"intermediate_size": 4 * hidden,
|
| 108 |
"vocab_size": base.vocab_size,
|
| 109 |
"max_position_embeddings": base.max_position_embeddings,
|
| 110 |
+
"rope_theta": getattr(base, "rope_theta", 10000.0),
|
| 111 |
"rms_norm_eps": base.rms_norm_eps,
|
| 112 |
"tie_word_embeddings": False,
|
| 113 |
})
|
|
|
|
| 147 |
prev_hidden_size=None signals index 0 (no predecessor).
|
| 148 |
"""
|
| 149 |
|
| 150 |
+
def __init__(self, llama_cfg: LlamaConfig, prev_hidden_size: Optional[int]):
|
| 151 |
super().__init__()
|
| 152 |
self.prev_hidden_size = prev_hidden_size
|
|
|
|
|
|
|
| 153 |
self.backbone = LlamaForCausalLM(llama_cfg)
|
| 154 |
|
| 155 |
if prev_hidden_size is not None:
|
|
|
|
| 212 |
|
| 213 |
config_class = MatriochkaConfig
|
| 214 |
base_model_prefix = "lm_model_dict"
|
|
|
|
| 215 |
|
| 216 |
def __init__(self, config: MatriochkaConfig):
|
| 217 |
super().__init__(config)
|
| 218 |
self.lm_model_dict = nn.ModuleDict()
|
| 219 |
|
|
|
|
| 220 |
prev_hidden: Optional[int] = None
|
| 221 |
for tag, sub_cfg_dict in zip(config.sub_model_tags, config.sub_model_configs):
|
| 222 |
llama_cfg = LlamaConfig(**sub_cfg_dict)
|
| 223 |
+
self.lm_model_dict[tag] = _MatriochkaSubModel(llama_cfg, prev_hidden)
|
| 224 |
prev_hidden = sub_cfg_dict["hidden_size"]
|
| 225 |
|
| 226 |
self.post_init()
|
|
|
|
| 309 |
AutoModelForCausalLM.register(MatriochkaConfig, MatriochkaForCausalLM)
|
| 310 |
|
| 311 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
# ---------------------------------------------------------------------------
|
| 313 |
# Smoke-test (python modeling_matriochka.py)
|
| 314 |
# ---------------------------------------------------------------------------
|