Interactive Components
Knowledge Markup Language · Unifies curriculum content, visualizations, numerical labs, and research evidence. Every component is globally registered in src/theme/MDXComponents.js and ready to use in any .md / .mdx note without an explicit import.
One lesson · seven-step learning loop
From motivation and mathematical intuition to reproducible research. Select components as needed rather than forcing every component into every lesson; all numerical demos run deterministically in the browser and are not actual PyTorch training runs.
Component library
Showing 74 of 74 components · All interactive demos run locally.
Knowledge
Concept structure, equations, and step-by-step derivations
Definition
Term, mathematical definition, and physical interpretation; legacy KML component.
Verification: Distinguish gradient, Jacobian, and derivative.MDX usage (global, no import)
<Definition title="Gradient" math="\nabla f(\mathbf{x})" />
Equation
Display referenceable equations with symbol descriptions and validity conditions.
Verification: Check matrix dimensions and vector orientation.MDX usage (global, no import)
<Equation math="\mathbf{y} = \mathbf{W}\mathbf{x} + \mathbf{b}" number="1" caption="Affine map" />
DerivationSteps
Step-by-step mathematical derivation showing the assumption at each step.
Define single-sample squared error loss.
Verification: Verify the final step against finite differences.MDX usage (global, no import)
<DerivationSteps nodes={[...]} descriptions={[...]} />
ConceptCompare
Compare related concepts along shared dimensions rather than memorizing definitions.
| Dimension | DDPM | Flow matching |
|---|---|---|
| Training target | noise ε (common parameterization) | conditional velocity u |
| Sampling example | reverse denoising steps | ODE integration |
| Shared goal | learn data distribution | learn data distribution |
Verification: Distinguish training targets from inference samplers.MDX usage (global, no import)
<ConceptCompare headers={["Dimension","DDPM","Flow matching"]} rows={[...]} />
PrerequisiteMap
Show prerequisite concepts and their roles rather than ordering by chapter alone.
Understand axes and tensor shapes first.
Verification: Identify any prerequisite node you cannot yet explain.MDX usage (global, no import)
<PrerequisiteMap nodes={[...]} descriptions={[...]} />
Pitfall
Highlight common silent bugs and how to diagnose them.
Silent broadcasting: prediction [B,1] − target [B] broadcasts to [B,B] instead of [B,1].
assert pred.shape == target.shape loss = ((pred - target)**2).mean()
Verification: Assert shapes before computing the loss.MDX usage (global, no import)
<Pitfall title="Silent broadcasting" message="..." />
Media & Visualization
Figures, function plots, and data-flow traces
Figure
Static figure with structured caption, source attribution, and alt text.
Verification: Captions should specify data provenance, units, and axes.MDX usage (global, no import)
<Figure src="https://d2l.ai/_images/mlp.svg" alt="MLP" caption="A multilayer perceptron" />
FunctionPlot
Use sliders to inspect how parameters shape function curves.
Verification: w controls the slope; b controls the intercept.MDX usage (global, no import)
<FunctionPlot functions={["relu", "sigmoid", "tanh"]} parameters={{ w: 1, b: 0 }} interactive />
Heatmap
Map matrix entries to color while preserving exact numerical values.
Verification: Color is not a substitute for precision; inspect the raw numbers.MDX usage (global, no import)
<Heatmap baseMatrix={[[1,-2,3],[0,1,2],[-1,2,-3]]} />
DataFlow
Trace model data flow and intermediate tensor shapes step by step.
Batch size B with 4 features per sample.
Verification: Verify the shape contract at every step.MDX usage (global, no import)
<DataFlow nodes={[...]} descriptions={[...]} />
AnimationStepper
Playable, pausable, and frame-by-frame numerical trajectory illustration.
Verification: Uniformly spaced trajectory schematic, not an actual optimizer run.MDX usage (global, no import)
<AnimationStepper totalFrames={9} interval={450} />
Learning & Verification
Prediction, independent verification, and mastery evidence
PredictionReveal
Predict first, then reveal the explanation; supports targeted checks without forced quizzes.
What is the output shape of [2,3] @ [3,4]?
Verification: Predict independently before revealing; does not auto-record mastery.MDX usage (global, no import)
<PredictionReveal prompt="What is the output shape of [2,3] @ [3,4]?" answer="[2,4]" />
HintStack
Progressive hints revealing the solution path after an independent attempt.
First identify the direct inputs to the loss.
Verification: Never reveal the full answer in the first hint.MDX usage (global, no import)
<HintStack hints={[...]} />
CodeContract
Specify input/output shape contracts and verification constraints for AI-assisted code.
def affine(x, W, b):
# x:[B,D], W:[H,D], b:[H]
assert x.shape[-1] == W.shape[-1]
return x @ W.T + b
# Independent reference: explicit sumsPython snippet — not executed here.Verification: Cross-check against an elementwise reference and nn.Linear.MDX usage (global, no import)
<CodeContract code="..." note="..." />
MasteryChecklist
L1–L5 self-assessment checklist separating conceptual and practical evidence.
Verification: Checking boxes does not substitute for actual evidence or Notion updates.MDX usage (global, no import)
<MasteryChecklist items={[...]} />
EvidenceRecord
Record structured evidence for notebooks, commits, and experiment metrics.
Verification: Do not mark complete without actual execution evidence.MDX usage (global, no import)
<EvidenceRecord lesson="0106" />
Tensor & Linear Algebra
Tensors, matrices, and axis operations
TensorGrid
Interactively inspect tensor indices, rank, shape, and numel.
Verification: Rank is the number of axes, not the number of elements.MDX usage (global, no import)
<TensorGrid />
TensorTransform
Compare reshape, transpose, and flatten against the original memory order.
Verification: Matching shapes do not guarantee identical element ordering.MDX usage (global, no import)
<TensorTransform />
BroadcastingLab
Right-align dimensions to check broadcasting compatibility and output values.
Verification: After alignment, every axis must match or have size 1.MDX usage (global, no import)
<BroadcastingLab />
MatrixMultiply
Visualize matrix multiplication via explicit dot products and numerical checks.
Verification: Recompute each output entry independently via dot products.MDX usage (global, no import)
<MatrixMultiply />
ReductionLab
Demonstrate axis semantics and keepdim behavior for sum and mean.
Verification: Check which axes collapse after reduction.MDX usage (global, no import)
<ReductionLab />
LinearTransformLab
2D linear mapping; observe rotation and scaling.
Verification: Compare against the first column of W (image of e₁).MDX usage (global, no import)
<LinearTransformLab />
TensorIndexSliceLab
Inspect row/column indexing and half-open slice values.
Verification: Python slice end indices are exclusive.MDX usage (global, no import)
<TensorIndexSliceLab />
ConcatStackLab
Compare cat vs stack output shapes and element ordering.
[[[1,2],[3,4]],[[5,6],[7,8]]]
Verification: cat joins along an existing axis; stack inserts a new axis.MDX usage (global, no import)
<ConcatStackLab />
Training & Probability
Optimization, gradients, probability, and generalization
ComputationalGraph
Display forward computation and local gradients.
Verification: Target t=1; check against the chain rule.MDX usage (global, no import)
<ComputationalGraph />
GradientCheck
Compare analytic gradients against central finite differences.
| Method | Value |
|---|---|
| Analytic | 4.32 |
| Finite difference | 4.32 |
| Absolute error | 9.999e-9 |
Verification: Smaller ε is not always more accurate due to floating-point rounding.MDX usage (global, no import)
<GradientCheck />
ActivationLab
Inspect activation functions alongside their derivatives.
Verification: Small derivatives can cause vanishing gradients.MDX usage (global, no import)
<ActivationLab />
SoftmaxLab
Vary logit and temperature to observe probability distributions.
Verification: Softmax normalizes along the class axis; temperature is not required for CE.MDX usage (global, no import)
<SoftmaxLab />
OptimizerLab
Compare SGD and momentum on the same 1D quadratic objective.
Verification: Identical initialization and budget; vary lr to observe divergence.MDX usage (global, no import)
<OptimizerLab />
ProbabilityLab
Numerical relationship between Gaussian density, variance, and NLL.
Verification: Probability density can exceed 1, and NLL can be negative.MDX usage (global, no import)
<ProbabilityLab />
GeneralizationLab
Compute actual training and held-out error with polynomial fitting.
Verification: Synthetic data; lower training error at higher degree does not imply generalization.MDX usage (global, no import)
<GeneralizationLab />
AutogradLab
Illustrate gradient accumulation at shared nodes and zero_grad semantics.
Verification: Paths to the same leaf add; explicit zeroing is required between backward passes.MDX usage (global, no import)
<AutogradLab />
TrainingLoopLab
Run live batch gradient descent for 1D linear regression in the browser.
Verification: Check train/validation separation and gradient sign; verify real PyTorch separately.MDX usage (global, no import)
<TrainingLoopLab />
GradientStabilityLab
Illustrate gradient product decay/explosion across repeated scalar linear layers.
Verification: Scalar chain is a simplified model; real gradients depend on Jacobian products.MDX usage (global, no import)
<GradientStabilityLab />
Architecture & Generative AI
Modern networks, generative models, and adaptation
ConvolutionLab
Compute 2×2 cross-correlation over a 3×3 input.
Verification: PyTorch Conv2d computes cross-correlation by default without flipping the kernel.MDX usage (global, no import)
<ConvolutionLab />
RepresentationLab
Illustrate compression and information loss via linear projection.
Verification: Fixed data comparing projection angles; not a trained autoencoder.MDX usage (global, no import)
<RepresentationLab />
ScaledAttentionLab
Compute single-query scaled dot-product attention with causal mask.
Verification: Masking precedes softmax; scaling factor is √dₖ.MDX usage (global, no import)
<ScaledAttentionLab />
TransformerTrace
Trace tensor shapes through a standard pre-norm Transformer block.
Verification: Generic MHA schematic; real models may use GQA, RoPE, or RMSNorm.MDX usage (global, no import)
<TransformerTrace />
LoRALab
Compare trainable parameter counts for low-rank updates ΔW = BA.
| Parameters | Count |
|---|---|
| Full W | 4096 |
| LoRA A+B | 512 |
| Trainable ratio | 12.5% |
Verification: Counts A/B for one linear layer only; does not represent total model VRAM.MDX usage (global, no import)
<LoRALab />
DiffusionLab
Observe DDPM forward corruption on a fixed illustrative noise sample.
Verification: ᾱ→1 recovers x₀; ᾱ→0 approaches pure noise.MDX usage (global, no import)
<DiffusionLab />
FlowMatchingLab
Linear conditional probability path and velocity target.
Verification: Distinguish the conditional target from the learned marginal velocity field.MDX usage (global, no import)
<FlowMatchingLab />
SequenceStateLab
Inspect memory and stability in a first-order linear state-space model.
Verification: Linear SSM only, not a full Mamba block.MDX usage (global, no import)
<SequenceStateLab />
TokenSamplingLab
Compare temperature scaling and top-k truncation on fixed logits.
Verification: Sampling distribution differs from training objective; no live tokenizer/LLM here.MDX usage (global, no import)
<TokenSamplingLab />
PatchEmbeddingLab
Visualize image patchification and resulting token counts.
Verification: Presence of a CLS token depends on the specific ViT variant.MDX usage (global, no import)
<PatchEmbeddingLab />
GraphMessagePassing
Compute neighbor mean aggregation on a 3-node undirected chain.
Verification: Shared aggregation is permutation-equivariant; no learned weights here.MDX usage (global, no import)
<GraphMessagePassing />
VAELatentLab
Inspect reparameterization z = μ + σε and the analytical KL term.
Verification: KL is the 1D Gaussian analytical value, excluding reconstruction loss.MDX usage (global, no import)
<VAELatentLab />
NormalizingFlowLab
Demonstrate invertible scalar transforms and change of variables.
Verification: Transform must be invertible; density scales by 1/|a|.MDX usage (global, no import)
<NormalizingFlowLab />
GuidanceLab
Illustrate classifier-free guidance extrapolation from two fixed predictions.
Verification: s=0 is unconditional, s=1 is conditional; larger s does not always improve quality.MDX usage (global, no import)
<GuidanceLab />
ContrastiveLossLab
Compute InfoNCE with one positive and two negative pairs.
Verification: Uses fixed cosine similarities; real encoder embeddings require separate verification.MDX usage (global, no import)
<ContrastiveLossLab />
GANObjectiveLab
Observe how discriminator output affects the non-saturating generator loss.
Verification: Shows objective value only, not adversarial training convergence.MDX usage (global, no import)
<GANObjectiveLab />
Robot Learning & Research
VLAs, dynamics, and reproducible research
VLATrace
Trace conceptual vision, language, and action data flow.
Specify visual observations and language instructions.
Verification: Actual π₀.₅ shapes, modules, and attention masks must be verified in source code.MDX usage (global, no import)
<VLATrace />
PolicyRollout
Compare feedback gains on a simplified 1D closed-loop system.
Verification: Discrete closed-loop pole is 1 − 0.2K; check stability bounds.MDX usage (global, no import)
<PolicyRollout />
PhysicsDynamicsLab
Compare energy drift between explicit Euler and symplectic Euler integrators.
Verification: Both structural priors and numerical integrators affect physical consistency.MDX usage (global, no import)
<PhysicsDynamicsLab />
AblationTable
Compute relative effect sizes between matched-budget baseline and variant.
| Model | MSE (illustrative) |
|---|---|
| Baseline | 0.25 |
| Variant | 0.2 |
| Relative reduction | 20% |
Verification: Always report seeds, variance, compute cost, and failure cases.MDX usage (global, no import)
<AblationTable />
ExperimentPlan
Pre-register hypothesis, control variables, metrics, and stopping criteria.
Verification: Define a falsifiable hypothesis before generating experiment code.MDX usage (global, no import)
<ExperimentPlan />
ResearchReproChecklist
Reproducibility and research report acceptance checklist.
Verification: Checklists are not evidence; link directly to notebooks and repositories.MDX usage (global, no import)
<ResearchReproChecklist />
WorldModelRollout
Compare true linear dynamics against a slightly mismatched model over multi-step rollouts.
Verification: One-step errors compound over the horizon; never substitute training loss for rollout evaluation.MDX usage (global, no import)
<WorldModelRollout />
Blog Content Engine
Unified layout, information, ECharts, and interactive simulation primitives for any note
Columns
Responsive multi-column layout that stacks cleanly on mobile screens.
Verification: Use for side-by-side comparisons or dual-panel explanations.MDX usage (global, no import)
<Columns cols={2} gap={16} />
Grid
Auto-fit responsive card grid based on minimum column width.
Verification: Adapts column count automatically to container width.MDX usage (global, no import)
<Grid minWidth={180} gap={12} />
Carousel
Paginated slide deck for step-by-step visuals or experiment snapshots.
Verification: Supports keyboard-accessible prev/next and dot indicators.MDX usage (global, no import)
<Carousel items={[...]} />
Tabs
Interactive tabbed container for comparing views, derivations, or implementations.
Verification: Keep tab labels short and mutually exclusive.MDX usage (global, no import)
<Tabs items={[{ label, content }]} />
MetricCard
Display key experiment metrics with optional trend delta and note.
Verification: Always pair headline metrics with baseline comparison and sample size.MDX usage (global, no import)
<MetricCard label="Success Rate" value="96.2%" delta="+12.4 percentage points" trend="up" />
Callout
Highlight key notes, tips, warnings, or danger notices in any note.
Verification: Supports info, tip, warning, and danger variants.MDX usage (global, no import)
<Callout type="info" title="Note" />
PaperCard
Structured research paper card with authors, venue, tags, and paper/code links.Attention Is All You Need
Verification: Link directly to the paper and official repository when available.MDX usage (global, no import)
<PaperCard title="..." authors="..." venue="..." year="2025" />
ComparisonCard
Side-by-side advantages and limitations summary card.
Advantages
- Exact closed-form gradients
- Fast local iteration
Limitations
- Assumes linear dynamics
- Requires tuning
Verification: Keep points concrete and symmetrical across columns.MDX usage (global, no import)
<ComparisonCard title="..." pros={[...]} cons={[...]} />
BarChart
Declarative ECharts bar chart from a simple { name, value } array.
Verification: State units and whether data is illustrative or measured.MDX usage (global, no import)
<BarChart data={[{ name: "PID", value: 65 }, { name: "MPC", value: 85 }, { name: "Proposed", value: 96 }]} unit="%" />
LineChart
Declarative ECharts multi-series line chart.
Verification: Label axes and compare against a matched baseline.MDX usage (global, no import)
<LineChart x={[1,2,3,4]} series={[{ name: "Loss", data: [1.2, 0.7, 0.4, 0.25] }]} />
PieChart
Declarative ECharts donut or pie chart for proportion breakdowns.
Verification: Ensure parts sum to a meaningful whole.MDX usage (global, no import)
<PieChart data={[{ name: "Core", value: 75 }, { name: "Research", value: 25 }]} />
Flowchart
Declarative horizontal or vertical process/architecture flowchart.
Verification: Keep node labels concise and ordered by data flow.MDX usage (global, no import)
<Flowchart nodes={["Input", "Controller", "Robot", "Feedback"]} />
Trajectory
Lightweight SVG 2D trajectory plot for robotics and dynamics notes.
Verification: Start node is blue; terminal node is teal.MDX usage (global, no import)
<Trajectory points={[[0,0],[1,0.8],[2,1.3],[3,1.1],[4,1.7]]} />
SecondOrderSimulator
Interactive 2nd-order control system step-response simulator with ζ and ωₙ sliders.
Verification: Observe overshoot and 2% settling time as ζ crosses 1.0.MDX usage (global, no import)
<SecondOrderSimulator dampingRatio={0.5} naturalFrequency={3} />
Calculator
Interactive tensor memory & parameter calculator with sliders.
Parameter Calculator
Verification: Verify unit conversions (elements × bytes per dtype).MDX usage (global, no import)
<Calculator title="Tensor Memory" fields={[...]} />
Checklist
Interactive verification checklist with live completion progress bar.
Verification Checklist
0%Verification: Local interactive check-off for readers.MDX usage (global, no import)
<Checklist title="Checklist" items={[...]} />
CodeDemo
Tabbed code and expected output viewer for multi-framework snippets.
import torch
x = torch.randn(4, 8)
w = torch.randn(8, 3)
print((x @ w).shape)# Output
torch.Size([4, 3])Verification: Verify outputs match an actual local Python run.MDX usage (global, no import)
<CodeDemo title="Code & Output" examples={[...]} />
Existing Knowledge Markup Language & Lesson 1.1–1.8 Labs
In addition to the v2 component library above, all existing Knowledge Markup Language
components (Card, CardGrid, Stat, Compare, Steps, Timeline, Term,
MathDerivation, AnnotatedFigure, Reference, Quiz, LearningObjectives, Hint,
Solution, Flashcard, TensorViewer, MatrixOperation, DataChart, AttentionMap,
ArchitectureDiagram, CoordinateFrame, PointCloudViewer, LossSurface,
RobotViewer, GradientDescentLab, AttentionLab, NeuralNetworkLab) and the
dedicated src/components/nn/ toolkit for Lessons 1.1–1.8 remain globally registered in
src/theme/MDXComponents.js for backward compatibility and continued local expansion.
See the full 1.1–1.8 mapping on the Lab Coverage Map and the site-wide Component Manual.
Quick MDX example (no import required)
<Definition title="Gradient" math="\nabla f(\mathbf{x})">…</Definition>
<TensorGrid />
<ScaledAttentionLab />
<PredictionReveal prompt="What is the output shape of [2,3] @ [3,4]?" answer="[2,4]" />
<EvidenceRecord lesson="0106" />