Phase 02 — Model Architecture Mastery Across Modalities

Difficulty: ⭐⭐⭐⭐☆
Estimated Time: 3 weeks (60–80 hours)
Roles Supported: All Senior Staff ML roles — architecture expertise underpins every optimization decision


Why This Phase Exists

You cannot optimize what you don't understand. Before a Senior Staff engineer at Qualcomm can ask "why does this model's accuracy degrade more under INT4 quantization than that one?", they need to know: GQA uses fewer KV heads → fewer unique weight rows → friendlier to per-group quantization. MoE models have sparse activation → different quantization strategies per expert. SSMs (Mamba) have recurrent structure → completely different memory access patterns than attention.

The JD requires "expertise in model architecture, backed by literature rationale and intuition" and "understanding of broad-spectrum model architectures across modalities." This phase builds that expertise through implementation — you will implement every major architectural variant that appears in production models (LLaMA, Mistral, Mixtral, ViT, DINO, LLaVA, Mamba) from scratch or near-scratch.

After this phase, when asked in an interview "how would you adapt your NPU tiling strategy for a Mixture-of-Experts model?", you can answer specifically because you understand the routing mechanism and its sparsity implications.


Concepts

  • Scaled Dot-Product Attention (SDPA): $\text{Attention}(Q,K,V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V$ — computational complexity $O(n^2 d)$, memory $O(n^2)$
  • Multi-Head Attention (MHA): split $d_{model}$ into $h$ heads, concatenate outputs — fully parallelizable across heads
  • Grouped Query Attention (GQA): $g$ query groups share one KV head pair — reduces KV cache size by factor $h/g$; used in LLaMA-3, Mistral
  • Multi-Query Attention (MQA): extreme GQA with $g=1$ — single KV head, all query heads; MQA = GQA with groups=1
  • Rotary Position Embeddings (RoPE): encode position via rotation of Q,K vectors in complex plane: $f_q(x_m) = R^m_d x_m$ — length extrapolation via RoPE scaling (LLaMA)
  • ALiBi (Attention with Linear Biases): position bias added to attention logits as $-m \cdot |i-j|$ — train short, generalize long
  • SwiGLU / GeGLU: gated feedforward: $\text{FFN}(x) = (\sigma(W_1 x) \odot W_2 x) W_3$ — used in PaLM, LLaMA; ~25% more params but better performance per FLOP
  • Pre-norm vs Post-norm: pre-norm (RMSNorm before attention) = more stable training; used in all modern LLMs
  • RMSNorm: $\hat{x} = \frac{x}{\text{RMS}(x)} \cdot \gamma$ where $\text{RMS}(x) = \sqrt{\frac{1}{n}\sum x_i^2}$ — no mean subtraction, faster than LayerNorm
  • Mixture of Experts (MoE): sparse activation — each token routes to top-K of E experts; active params per token = dense_params + (K/E × expert_params)
  • Vision Transformer (ViT): divide image into non-overlapping patches → linear projection → standard transformer; patch size controls trade-off between sequence length and feature resolution
  • DINO / DINOv2: self-supervised ViT — student-teacher distillation with no labels; produces strong dense features for segmentation/detection
  • CLIP: contrastive vision-language pretraining — align image and text embeddings via InfoNCE loss; zero-shot classification and image-text retrieval
  • LLaVA-style multimodal: visual tokens from CLIP vision encoder → linear projection → prepend to LLM token sequence → standard LLM forward
  • Mamba / SSMs (Structured State Space Models): recurrent models with selective state transitions; linear time in sequence length; competitive with transformers on long sequences

Labs

Lab 01 — Transformer with Full Architectural Variants

FieldValue
GoalImplement a decoder-only transformer where attention type (MHA/GQA/MQA), position encoding (RoPE/ALiBi/learned), FFN type (standard/SwiGLU/GeGLU), and normalization (LayerNorm/RMSNorm) are all swappable config options; benchmark perplexity on Wikitext-103
ConceptsGQA/MQA/MHA, RoPE, ALiBi, SwiGLU, RMSNorm, pre-norm, KV cache, causal masking
Steps1. Implement CausalSelfAttention supporting MHA, GQA, MQA via config; 2. Implement RoPE and ALiBi position encodings; 3. Implement SwiGLU and GeGLU FFN variants; 4. Implement RMSNorm; 5. Assemble configurable TransformerBlock and GPTModel; 6. Implement KV cache for autoregressive inference; 7. Benchmark perplexity on Wikitext-103 for 5 architecture configs
StackPyTorch 2.3+, datasets (HuggingFace), tiktoken
DatasetsWikitext-103 (datasets.load_dataset("wikitext", "wikitext-103-v1"))
OutputModel configurations A–E with perplexity table; KV cache correctness test (cached vs non-cached outputs match); GFlops comparison across configs
How to Testpython test_lab.py — validates: (1) GQA output matches naive expansion within 1e-5, (2) RoPE rotation is length-generalizable, (3) KV cache produces identical output to full attention, (4) perplexity on 100-token eval decreases with larger model
Talking PointsWhy does GQA reduce KV cache memory? How does RoPE enable position extrapolation? When would you prefer ALiBi over RoPE? What is the FLOP count of SwiGLU vs standard FFN?
Resume BulletImplemented configurable decoder-only transformer with GQA/RoPE/SwiGLU variants from scratch; benchmarked 5 architecture configs on Wikitext-103, demonstrating 23% perplexity improvement from architectural choices alone
ExtensionsAdd sliding window attention (Mistral); implement expert routing for MoE; add Flash-attention-compatible causal mask

Lab 02 — Mixture of Experts (MoE)

FieldValue
GoalImplement the MoE layer used in Mixtral and Switch Transformer: top-K routing, auxiliary load-balancing loss, and expert-utilization diagnostics
ConceptsConditional compute, TopKRouter, Switch Transformer aux loss $n_{experts}\sum_i f_i p_i$, expert collapse, top-1 vs top-2 routing
Steps1. Implement TopKRouter (linear routing + top-K selection + aux loss); 2. Implement ExpertLayer (w1 → GELU → w2); 3. Implement MoEBlock combining weighted expert outputs per token; 4. Implement compute_expert_utilization to detect load imbalance; 5. Verify aux loss pushes utilization toward uniform
StackPyTorch 2.3+
OutputWorking MoE block with passing tests; expert-utilization report showing balanced routing under aux loss
How to Testpytest test_lab.py — validates routing shapes, aux loss formula, top-K combination weights summing to 1, utilization balance
Talking PointsWhy does expert collapse happen and how does the aux loss prevent it? Why does Mixtral use top-2 instead of top-1? What is the quantization implication of sparse expert activation?
Resume BulletImplemented Mixtral-style MoE layer with Switch Transformer load balancing from scratch; diagnosed and prevented expert collapse via auxiliary loss and utilization monitoring
ExtensionsAdd expert-parallel sharding plan; implement capacity factor with token dropping; benchmark dense-equivalent FLOPs vs active FLOPs

→ Lab folder: lab-02-mixture-of-experts/

Lab 03 — State Space Models (S4 / Mamba)

FieldValue
GoalImplement the SSM recurrence, ZOH discretization, and Mamba's selective scan; demonstrate O(N) memory vs O(N²) attention
ConceptsSSM state equation $h_t = \bar{A}h_{t-1} + \bar{B}x_t$, Zero-Order Hold discretization, input-dependent (selective) $B, C, \Delta$, linear recurrence, hardware-efficient parallel scan
Steps1. Implement discretize_zoh ($\bar{A} = e^{\Delta A}$, $\bar{B} = (\bar{A}-I)A^{-1}B$); 2. Implement s4_recurrence sequential scan; 3. Implement SelectiveSSM with input-dependent parameters; 4. Assemble MambaBlock (in_proj + depthwise conv + SSM + gating); 5. Implement compare_memory_usage quantifying attention vs SSM memory
StackPyTorch 2.3+
OutputWorking Mamba block with passing tests; memory comparison table attention vs SSM across sequence lengths
How to Testpytest test_lab.py — validates ZOH math, recurrence outputs, selective parameter shapes, memory scaling claim
Talking PointsWhy is selectivity (input-dependent B/C/Δ) the key difference from S4? Why are SSMs attractive for edge/NPU long-context inference? What breaks when you quantize a recurrent state?
Resume BulletImplemented Mamba selective state space model from scratch including ZOH discretization and selective scan; demonstrated linear-memory long-context inference vs quadratic attention
ExtensionsImplement parallel associative scan; add Mamba-2 SSD formulation; hybrid attention+SSM block (Jamba-style)

→ Lab folder: lab-03-state-space-models/

Lab 04 — ViT + DINO Self-Distillation

Implemented at testable scale in lab-04-vit-dino/ — ViT from scratch, DINO loss with centering+sharpening, momentum teacher, multi-crop step, 13-test suite that runs on synthetic data in seconds. The full CIFAR-10 training run described below is the lab's extension target.

FieldValue
GoalImplement ViT from scratch and replicate the DINO self-supervised training loop (student-teacher with centering + sharpening); validate that attention maps show semantic segmentation behavior
ConceptsPatch embedding, positional embedding, class token, multi-head self-attention, DINO momentum teacher, InfoNCE/cross-entropy with temperature, centering, attention map visualization
Steps1. Implement PatchEmbed (conv2d with stride=patch_size); 2. Implement ViT encoder (standard; use Lab 01 attention); 3. Implement DINO loss: student-teacher cross-entropy with softmax + centering + sharpening; 4. Implement momentum update for teacher; 5. Train on CIFAR-10 for 30 epochs (1h on single GPU); 6. Visualize last-layer attention heads — they should segment objects
StackPyTorch 2.3+, torchvision, matplotlib
DatasetsCIFAR-10 (via torchvision); optional: STL-10 for better quality
OutputTrained ViT-Tiny/CIFAR10; attention map visualizations showing semantic segmentation; linear probe accuracy ≥80% on CIFAR-10 without labels
How to Testpython test_lab.py — checks: patch embedding output shape, CLS token aggregation, DINO loss decreasing monotonically over first 100 steps, attention entropy decreasing (heads specializing)
Talking PointsWhy does the teacher use momentum update instead of gradient update? What does the centering operation prevent? Why do ViT attention heads naturally segment objects without segmentation supervision?
Resume BulletImplemented ViT + DINO self-supervised training from scratch; achieved 82% linear-probe accuracy on CIFAR-10 with no labels; visualized emergent semantic segmentation in attention maps
ExtensionsReplace patch embedding with DeiT-style data augmentation; add register tokens (DINOv2); implement dense feature extraction for downstream segmentation

Lab 05 — Multimodal Bridge (CLIP → LLM Projection)

Implemented at testable scale in lab-05-multimodal-bridge/ — trainable MLP projector between a frozen vision tower and a frozen causal LM, with the loss masking and causal-shift logic identical to LLaVA's, 12-test suite, no downloads. The full CLIP + TinyLlama + LLaVA-Instruct version below is the extension target.

FieldValue
GoalBuild a LLaVA-style multimodal model: freeze a CLIP vision encoder, train a MLP projection that maps visual tokens to LLM embedding space, and demonstrate image-conditioned text generation
ConceptsCLIP ViT-L/14 feature extraction, projection MLP, visual token prepending, instruction fine-tuning format, frozen vs unfrozen components, multimodal loss masking
Steps1. Load openai/clip-vit-large-patch14 from HuggingFace (frozen); 2. Extract image features (patch tokens, not just CLS); 3. Implement 2-layer MLP projector with GELU; 4. Load a small LLM (e.g., TinyLlama-1.1B) and freeze; 5. Implement MultimodalModel.forward() that prepends image tokens before text; 6. Fine-tune projector only on LLaVA-Instruct-150K (image caption subset); 7. Evaluate on VQAv2 using accuracy metric
StackPyTorch 2.3+, transformers, datasets, Pillow
DatasetsLLaVA-Instruct-150K (image subset, ~50k samples); VQAv2 val (for evaluation)
OutputTrained projector weights; VQAv2 validation accuracy (target: >50%); qualitative demos of image Q&A
How to Testpython test_lab.py — checks: visual token dimension matches LLM embedding dim, attention mask correctly excludes image tokens from loss computation, generation outputs valid text for 5 sample images
Talking PointsWhy freeze the vision encoder and LLM during projector training? What are the trade-offs of training the full model vs projector-only? How would you scale this to a 70B LLM on a Qualcomm NPU?
Resume BulletBuilt LLaVA-style multimodal bridge (CLIP→LLM projection); trained MLP projector on 50K instruction pairs; achieved 54% VQAv2 accuracy with only projector parameters fine-tuned (0.1% of total params)
ExtensionsAdd Q-Former connector (BLIP-2 style); implement visual grounding via region features; add video token temporal pooling

Deliverables Checklist

  • Configurable transformer with 5 tested architecture configs and perplexity table
  • MoE block with balanced expert utilization under aux loss
  • Mamba block with ZOH discretization and selective scan, memory comparison vs attention
  • ViT + DINO lab passing (13 tests); (stretch) CIFAR-10 run with attention map visualizations
  • Multimodal bridge lab passing (12 tests); (stretch) CLIP+TinyLlama with VQAv2 score
  • All test_lab.py suites pass

Guides in This Phase

Interview Relevance

  • "What is the memory advantage of GQA over MHA at 32K context?" — you can compute: (h×2×n×d) vs (h/g × 2×n×d), show 8x reduction for g=8
  • "How does DINO work without labels?" — explain centering + sharpening, why teacher EMA is key, why augmentation multi-crop works
  • "What is the bottleneck in deploying LLaVA on an NPU?" — you understand the KV cache growth with visual tokens, the projection cost, and the LLM decode bottleneck
  • "Why does RoPE generalize to longer sequences than learned position embeddings?" — explain the frequency decomposition and length-independent rotation property