File size: 9,605 Bytes
c443e62
 
 
 
cf92986
c443e62
 
 
 
 
 
 
 
 
cf92986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c443e62
1ff708a
c443e62
1ff708a
 
 
 
 
 
 
 
 
 
c443e62
 
 
 
 
 
 
cf92986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c443e62
6906b73
cf92986
 
1ff708a
cf92986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6906b73
c443e62
cf92986
 
 
 
 
 
 
c443e62
1ff708a
 
 
 
 
db0eecf
1ff708a
db0eecf
c443e62
 
 
 
 
 
cf92986
c443e62
 
cf92986
 
 
1ff708a
cf92986
 
 
 
 
1ff708a
db0eecf
1ff708a
db0eecf
cf92986
 
 
 
 
 
 
 
 
 
 
 
 
c443e62
cf92986
 
 
c443e62
cf92986
 
 
c443e62
6cf26d6
cf92986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ff708a
6cf26d6
cf92986
 
 
 
 
 
 
1ff708a
db0eecf
1ff708a
 
 
 
 
 
 
 
 
 
 
 
 
 
db0eecf
1ff708a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c443e62
 
 
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import streamlit as st
import matplotlib.pyplot as plt
import pandas as pd
import torch
from transformers import AutoConfig, AutoTokenizer

# Page configuration
st.set_page_config(
    page_title="Transformer Visualizer",
    page_icon="🧠",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Custom CSS styling
st.markdown("""
<style>
    .reportview-container {
        background: linear-gradient(45deg, #1a1a1a, #4a4a4a);
    }
    .sidebar .sidebar-content {
        background: #2c2c2c !important;
    }
    h1, h2, h3, h4, h5, h6 {
        color: #00ff00 !important;
    }
    .stMetric {
        background-color: #333333;
        border-radius: 10px;
        padding: 15px;
    }
    .architecture {
        font-family: monospace;
        color: #00ff00;
        white-space: pre-wrap;
        background-color: #1a1a1a;
        padding: 20px;
        border-radius: 10px;
        border: 1px solid #00ff00;
    }
    .token-table {
        margin-top: 20px;
        border: 1px solid #00ff00;
        border-radius: 5px;
    }
</style>
""", unsafe_allow_html=True)

# Model database
MODELS = {
    "BERT": {"model_name": "bert-base-uncased", "type": "Encoder", "layers": 12, "heads": 12, "params": 109.48},
    "GPT-2": {"model_name": "gpt2", "type": "Decoder", "layers": 12, "heads": 12, "params": 117},
    "T5-Small": {"model_name": "t5-small", "type": "Seq2Seq", "layers": 6, "heads": 8, "params": 60},
    "RoBERTa": {"model_name": "roberta-base", "type": "Encoder", "layers": 12, "heads": 12, "params": 125},
    "DistilBERT": {"model_name": "distilbert-base-uncased", "type": "Encoder", "layers": 6, "heads": 12, "params": 66},
    "ALBERT": {"model_name": "albert-base-v2", "type": "Encoder", "layers": 12, "heads": 12, "params": 11.8},
    "ELECTRA": {"model_name": "google/electra-small-discriminator", "type": "Encoder", "layers": 12, "heads": 12, "params": 13.5},
    "XLNet": {"model_name": "xlnet-base-cased", "type": "AutoRegressive", "layers": 12, "heads": 12, "params": 110},
    "BART": {"model_name": "facebook/bart-base", "type": "Seq2Seq", "layers": 6, "heads": 16, "params": 139},
    "DeBERTa": {"model_name": "microsoft/deberta-base", "type": "Encoder", "layers": 12, "heads": 12, "params": 139}
}

def get_model_config(model_name):
    config = AutoConfig.from_pretrained(MODELS[model_name]["model_name"])
    return config

def plot_model_comparison(selected_model):
    model_names = list(MODELS.keys())
    params = [m["params"] for m in MODELS.values()]
    
    fig, ax = plt.subplots(figsize=(10, 6))
    bars = ax.bar(model_names, params)
    
    index = list(MODELS.keys()).index(selected_model)
    bars[index].set_color('#00ff00')
    
    ax.set_ylabel('Parameters (Millions)', color='white')
    ax.set_title('Model Size Comparison', color='white')
    ax.tick_params(axis='x', rotation=45, colors='white')
    ax.tick_params(axis='y', colors='white')
    ax.set_facecolor('#2c2c2c')
    fig.patch.set_facecolor('#2c2c2c')
    
    st.pyplot(fig)

def visualize_architecture(model_info):
    architecture = []
    model_type = model_info["type"]
    layers = model_info.get("layers", model_info.get("layers", 12))  # Handle key variations
    heads = model_info["heads"]
    
    architecture.append("Input")
    architecture.append("β”‚")
    architecture.append("β–Ό")
    
    if model_type == "Encoder":
        architecture.append("[Embedding Layer]")
        for i in range(layers):
            architecture.extend([
                f"Encoder Layer {i+1}",
                "β”œβ”€ Multi-Head Attention",
                f"β”‚  └─ {heads} Heads",
                "β”œβ”€ Layer Normalization",
                "└─ Feed Forward Network",
                "β”‚",
                "β–Ό"
            ])
        architecture.append("[Output]")
    
    elif model_type == "Decoder":
        architecture.append("[Embedding Layer]")
        for i in range(layers):
            architecture.extend([
                f"Decoder Layer {i+1}",
                "β”œβ”€ Masked Multi-Head Attention",
                f"β”‚  └─ {heads} Heads",
                "β”œβ”€ Layer Normalization",
                "└─ Feed Forward Network",
                "β”‚",
                "β–Ό"
            ])
        architecture.append("[Output]")
    
    elif model_type == "Seq2Seq":
        architecture.append("Encoder Stack")
        for i in range(layers):
            architecture.extend([
                f"Encoder Layer {i+1}",
                "β”œβ”€ Self-Attention",
                "└─ Feed Forward Network",
                "β”‚",
                "β–Ό"
            ])
        architecture.append("β†’β†’β†’ [Context] β†’β†’β†’")
        architecture.append("Decoder Stack")
        for i in range(layers):
            architecture.extend([
                f"Decoder Layer {i+1}",
                "β”œβ”€ Masked Self-Attention",
                "β”œβ”€ Encoder-Decoder Attention",
                "└─ Feed Forward Network",
                "β”‚",
                "β–Ό"
            ])
        architecture.append("[Output]")
    
    return "\n".join(architecture)

def visualize_attention_patterns():
    fig, ax = plt.subplots(figsize=(8, 6))
    data = torch.randn(5, 5)
    ax.imshow(data, cmap='viridis')
    ax.set_title('Attention Patterns Example', color='white')
    ax.set_facecolor('#2c2c2c')
    fig.patch.set_facecolor('#2c2c2c')
    st.pyplot(fig)

def get_hardware_recommendation(params):
    if params < 100:
        return "CPU or Entry-level GPU (e.g., GTX 1060)"
    elif 100 <= params < 200:
        return "Mid-range GPU (e.g., RTX 2080, RTX 3060)"
    else:
        return "High-end GPU (e.g., RTX 3090, A100) or TPU"

def main():
    st.title("🧠 Transformer Model Visualizer")
    
    selected_model = st.sidebar.selectbox("Select Model", list(MODELS.keys()))
    model_info = MODELS[selected_model]
    config = get_model_config(selected_model)
    tokenizer = AutoTokenizer.from_pretrained(model_info["model_name"])
    
    col1, col2, col3, col4 = st.columns(4)
    with col1:
        st.metric("Model Type", model_info["type"])
    with col2:
        st.metric("Layers", model_info.get("layers", model_info.get("layers", "N/A")))
    with col3:
        st.metric("Attention Heads", model_info["heads"])
    with col4:
        st.metric("Parameters", f"{model_info['params']}M")
    
    tab1, tab2, tab3, tab4, tab5, tab6 = st.tabs([
        "Model Structure", "Comparison", "Model Attention", 
        "Tokenization", "Hardware", "Memory"
    ])
    
    with tab1:
        st.subheader("Architecture Diagram")
        architecture = visualize_architecture(model_info)
        st.markdown(f"<div class='architecture'>{architecture}</div>", unsafe_allow_html=True)
        
        st.markdown("""
        **Legend:**
        - **Multi-Head Attention**: Self-attention mechanism with multiple parallel heads
        - **Layer Normalization**: Normalization operation between layers
        - **Feed Forward Network**: Position-wise fully connected network
        - **Masked Attention**: Attention with future token masking
        """)
    
    with tab2:
        st.subheader("Model Size Comparison")
        plot_model_comparison(selected_model)
    
    with tab3:
        st.subheader("Model-specific Visualizations")
        visualize_attention_patterns()
    
    with tab4:
        st.subheader("πŸ“ Tokenization Visualization")
        input_text = st.text_input("Enter Text:", "Hello, how are you?")
        
        col1, col2 = st.columns(2)
        with col1:
            st.markdown("**Tokenized Output**")
            tokens = tokenizer.tokenize(input_text)
            st.write(tokens)
        with col2:
            st.markdown("**Token IDs**")
            encoded_ids = tokenizer.encode(input_text)
            st.write(encoded_ids)
        
        st.markdown("**Token-ID Mapping**")
        token_data = pd.DataFrame({
            "Token": tokens,
            "ID": encoded_ids[1:-1] if tokenizer.cls_token else encoded_ids
        })
        st.dataframe(token_data, height=150, use_container_width=True)
        
        st.markdown(f"""
        **Tokenizer Info:**
        - Vocabulary size: `{tokenizer.vocab_size}`
        - Special tokens: `{tokenizer.all_special_tokens}`
        - Padding token: `{tokenizer.pad_token}`
        - Max length: `{tokenizer.model_max_length}`
        """)

    with tab5:
        st.subheader("πŸ–₯️ Hardware Recommendation")
        params = model_info["params"]
        recommendation = get_hardware_recommendation(params)
        
        st.markdown(f"**Recommended hardware for {selected_model}:**")
        st.info(recommendation)
        
        st.markdown("""
        **Recommendation Criteria:**
        - <100M parameters: Suitable for CPU or entry-level GPUs
        - 100-200M parameters: Requires mid-range GPUs
        - >200M parameters: Needs high-end GPUs/TPUs
        """)

    with tab6:
        st.subheader("πŸ’Ύ Memory Usage Estimation")
        params = model_info["params"]
        memory_mb = params * 4  # 1M params β‰ˆ 4MB in FP32
        memory_gb = memory_mb / 1024
        
        st.metric("Estimated Memory (FP32)", 
                 f"{memory_mb:.1f} MB / {memory_gb:.2f} GB")
        
        st.markdown("""
        **Memory Notes:**
        - Based on 4 bytes per parameter (FP32 precision)
        - Actual usage varies with:
          - Batch size
          - Sequence length
          - Precision (FP16/FP32)
          - Optimizer states (training)
        """)

if __name__ == "__main__":
    main()