File size: 3,944 Bytes
2f04653
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python3
"""Create a tiny random-weight `qwen3_5_moe` checkpoint with the *same architecture
family* as Phai-A1-35B (hybrid GatedDeltaNet + gated attention + routed/shared MoE),
for offline tests of the vLLM plugin and the trainer on small GPUs.

    python scripts/make_tiny_model.py --out runs/tiny-qwen35moe

The tokenizer/chat template are copied from the real model (needs it in the HF cache
or network access); weights are random, so generations are gibberish by design.
"""
from __future__ import annotations

import argparse
import json
import shutil
from pathlib import Path

import torch

BASE = "ramachandrajoshi/Phai-A1-35B-1M-FP8"
TOKENIZER_FILES = ["tokenizer.json", "tokenizer_config.json", "chat_template.jinja", "generation_config.json"]


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default="runs/tiny-qwen35moe")
    ap.add_argument("--layers", type=int, default=12)
    ap.add_argument("--hidden", type=int, default=256)
    ap.add_argument("--experts", type=int, default=16)
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--lm-scale", type=float, default=4.0,
                    help="scale lm_head so the random model has peaked (but bf16-resolvable) logits")
    args = ap.parse_args()

    from huggingface_hub import hf_hub_download
    from transformers import Qwen3_5MoeConfig, Qwen3_5MoeForConditionalGeneration

    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    real = json.loads(Path(hf_hub_download(BASE, "config.json")).read_text())
    real.pop("quantization_config", None)

    t = real["text_config"]
    L = args.layers
    t.update(
        hidden_size=args.hidden,
        num_hidden_layers=L,
        layer_types=["full_attention" if (i + 1) % 4 == 0 else "linear_attention" for i in range(L)],
        num_attention_heads=4,
        num_key_value_heads=2,
        head_dim=64,
        linear_num_key_heads=4,
        linear_num_value_heads=8,
        linear_key_head_dim=32,
        linear_value_head_dim=32,
        num_experts=args.experts,
        num_experts_per_tok=4,
        moe_intermediate_size=128,
        shared_expert_intermediate_size=128,
        mtp_num_hidden_layers=0,
        max_position_embeddings=32768,
    )
    t["rope_parameters"] = {**t["rope_parameters"], "factor": 1, "rope_type": "default",
                            "original_max_position_embeddings": 32768}
    t["rope_parameters"].pop("factor", None)
    # rotary_dim = head_dim * partial_rotary_factor = 16  =>  mrope sections must sum to 8
    t["rope_parameters"]["mrope_section"] = [3, 3, 2]
    v = real["vision_config"]
    v.update(depth=1, hidden_size=64, intermediate_size=128, num_heads=2, out_hidden_size=args.hidden)
    real["hidden_size"] = args.hidden

    cfg = Qwen3_5MoeConfig(**{k: val for k, val in real.items() if k not in ("architectures", "transformers_version")})
    cfg.architectures = ["Qwen3_5MoeForConditionalGeneration"]
    torch.manual_seed(args.seed)
    model = Qwen3_5MoeForConditionalGeneration(cfg).to(torch.bfloat16)
    # Make the random model a bit less degenerate: scale residual-writing projections down.
    with torch.no_grad():
        for n, p in model.named_parameters():
            if p.ndim >= 2 and any(k in n for k in ("o_proj", "out_proj", "down_proj")):
                p.mul_(0.5)
        # Peaked output distribution so greedy decoding is not dominated by ties/noise.
        model.lm_head.weight.mul_(args.lm_scale)
    model.save_pretrained(out, safe_serialization=True)
    for f in TOKENIZER_FILES:
        try:
            shutil.copy(hf_hub_download(BASE, f), out / f)
        except Exception as e:  # noqa: BLE001
            print(f"warning: could not copy {f}: {e}")
    n = sum(p.numel() for p in model.parameters())
    print(f"wrote {out} ({n/1e6:.1f}M params, {L} layers, layer_types={t['layer_types']})")


if __name__ == "__main__":
    main()