File size: 7,654 Bytes
81d60af
 
8d21309
 
 
 
81d60af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b342230
8d21309
9181528
 
 
 
 
8d21309
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b342230
 
81d60af
 
 
 
 
 
 
8d21309
81d60af
 
8d21309
81d60af
 
8d21309
81d60af
8d21309
 
81d60af
8d21309
81d60af
 
 
8d21309
 
81d60af
 
 
 
 
 
 
 
 
 
8d21309
81d60af
 
 
 
 
 
 
 
8d21309
81d60af
8d21309
 
81d60af
 
 
 
 
8d21309
81d60af
 
 
8d21309
 
81d60af
 
 
8d21309
 
81d60af
 
 
 
 
 
 
 
8d21309
81d60af
 
 
8d21309
 
81d60af
 
 
8d21309
81d60af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d21309
81d60af
 
 
 
8d21309
81d60af
 
 
8d21309
81d60af
8d21309
 
 
 
81d60af
 
 
 
 
8d21309
81d60af
 
 
 
8d21309
81d60af
 
8d21309
b342230
81d60af
b342230
81d60af
 
8d21309
81d60af
 
 
8d21309
81d60af
 
 
 
 
 
 
 
 
 
 
 
 
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# ui/tab_inspect.py
"""
Tab1: Model Structure Inspection
- Read all shard headers
- Display raw key structure
- Auto-build LayerProfile and display inferred results
"""

import gradio as gr
import requests
import pandas as pd

from core.fetcher import (
    load_all_shard_headers,
    get_file_url,
    check_quantization,
    http_error_msg,
)
from core.layer_profile import (
    scan_model_structure,
    summarize_structure,
    extract_config_params,
)

SIDEBAR_MD = """
### βœ… Recommended Models
google/gemma-4-e2b  
google/gemma-4-e4b-it  
google/gemma-4-31b-it  
Qwen/Qwen2.5-14B-Instruct  
deepseek-ai/DeepSeek-R1-Distill-Qwen-14B  
meta-llama/Meta-Llama-3-8B (Need access rightοΌ‰   

---

### Layer Index
- Layer index = **N** in `layers.{N}` of safetensors keys
- Raw index, **not re-numbered per component**
- Multi-modal models (e.g. Gemma-4):
  - `layers.0~11` may contain audio / vision / text layers
  - All components output separately, distinguished by prefix

### Example: Gemma-4-E2B
| Component | Layer Range |
|-----------|-------------|
| audio_tower | 0 ~ 11 |
| language_model | 0 ~ 34 |
| vision_tower | 0 ~ 15 |

### Example: Gemma-4-31B
| Component | Layer Range |
|-----------|-------------|
| language (local) | 0 ~ 59 |
| language (global) | 5, 11, 17 … 59 |
| vision_tower | 0 ~ 26 |
"""


def inspect_model(
    model_id: str,
    hf_token: str,
    progress=gr.Progress()
) -> tuple[str, pd.DataFrame]:
    """
    Returns (inspection log text, layer structure DataFrame)
    """
    if not model_id.strip():
        return "❌ Please enter a model ID.", None

    token = hf_token.strip() or None
    log   = [f"πŸ”¬ Structure Inspection: {model_id}\n{'═'*80}\n"]

    # ── Quantization check ────────────────────────────────────────────────────
    progress(0.05, desc="Checking quantization...")
    blocked, qmsg = check_quantization(model_id, token)
    log.append(f"[Quantization Check]\n{qmsg}\n{'─'*80}\n")
    if blocked:
        return "".join(log), None

    # ── config.json ───────────────────────────────────────────────────────────
    progress(0.10, desc="Reading config...")
    config_params = {}
    try:
        r = requests.get(
            f"https://huggingface.co/{model_id}/resolve/main/config.json",
            headers={"Authorization": f"Bearer {token}"} if token else {},
            timeout=15
        )
        if r.status_code == 200:
            config_params = extract_config_params(r.json())
            log.append(
                f"πŸ“‹ Config:\n"
                f"   model_type = {config_params.get('model_type')}\n"
                f"   hidden     = {config_params.get('hidden_size')}\n"
                f"   n_heads    = {config_params.get('num_attention_heads')}\n"
                f"   n_kv       = {config_params.get('num_key_value_heads')}\n"
                f"   head_dim   = {config_params.get('head_dim')}\n"
                f"{'─'*80}\n"
            )
    except Exception as e:
        log.append(f"⚠️  Could not read config.json: {e}\n")

    # ── Load all shard headers ─────────────────────────────────────────────────
    progress(0.20, desc="Loading shard headers...")
    try:
        all_headers = load_all_shard_headers(model_id, token)
    except requests.exceptions.HTTPError as e:
        return http_error_msg(e, model_id), None
    except Exception as e:
        return "".join(log) + f"❌ Failed to load headers: {e}\n", None

    total_keys = sum(len(h) for h, _ in all_headers.values())
    log.append(
        f"πŸ“¦ Shards: {len(all_headers)}  "
        f"Total keys: {total_keys}\n"
        f"{'─'*80}\n"
    )

    # ── Scan layer structure ───────────────────────────────────────────────────
    progress(0.50, desc="Scanning layer structure...")
    profiles = scan_model_structure(all_headers, config_params)

    if not profiles:
        sample = []
        for h, _ in list(all_headers.values())[:1]:
            sample = list(h.keys())[:30]
        return (
            "".join(log) +
            "⚠️  No Q/K/V layers found. First 30 keys:\n" +
            "\n".join(sample), None
        )

    # ── Generate structure text ────────────────────────────────────────────────
    progress(0.80, desc="Generating report...")
    struct_text = summarize_structure(profiles)
    log.append(struct_text)

    # ── Build overview DataFrame ───────────────────────────────────────────────
    rows = []
    for (prefix, layer_idx), p in sorted(profiles.items()):
        rows.append({
            "prefix":     prefix,
            "layer":      layer_idx,
            "d_model":    p.d_model,
            "head_dim":   p.head_dim,
            "dim_source": p.head_dim_source,
            "n_q":        p.n_q_heads,
            "n_kv":       p.n_kv_heads,
            "kv_shared":  p.kv_shared,
            "complete":   p.complete,
            "q_shape":    str(p.q.shape) if p.q else "",
            "k_shape":    str(p.k.shape) if p.k else "",
            "v_shape":    str(p.v.shape) if p.v else "K=V",
        })

    df = pd.DataFrame(rows)

    progress(1.0, desc="Done")
    return "".join(log), df


# ─────────────────────────────────────────────
# Tab1 UI
# ─────────────────────────────────────────────

def build_tab_inspect():
    with gr.Tab("πŸ”¬ Inspect"):
        gr.Markdown("""
        **Step 1: Inspect model structure** β€” auto-detect components, head_dim, and K=V shared layers.
        Results are used by the **Analyze** tab.

        > No weights are downloaded β€” structure is inferred from safetensors headers only.
        """)

        with gr.Row():
            with gr.Column(scale=3):
                inspect_model_id = gr.Textbox(
                    label="HuggingFace Model ID",
                    placeholder="google/gemma-4-e2b",
                    value="google/gemma-4-e2b"
                )
                inspect_token = gr.Textbox(
                    label="HF Access Token (leave empty for public models)",
                    type="password"
                )
                inspect_btn = gr.Button("πŸ” Inspect Structure", variant="secondary")

            with gr.Column(scale=1):
                gr.Markdown(SIDEBAR_MD)

        inspect_log = gr.Textbox(
            label="Inspection Log",
            lines=30, max_lines=200
        )
        inspect_table = gr.Dataframe(
            label="Layer Structure Overview",
            headers=[
                "prefix", "layer", "d_model", "head_dim", "dim_source",
                "n_q", "n_kv", "kv_shared", "complete",
                "q_shape", "k_shape", "v_shape"
            ]
        )

        inspect_btn.click(
            fn=inspect_model,
            inputs=[inspect_model_id, inspect_token],
            outputs=[inspect_log, inspect_table]
        )

    return inspect_model_id, inspect_token