# Open-Source LLM Selection Guide: Dense vs. Mixture-of-Experts Architectures

    A practical guide to choosing between dense and Mixture-of-Experts open-source LLMs. Learn how total vs. activated parameters affect memory and speed, how to estimate VRAM and KV cache requirements, how to handle structured outputs, and how to build your own evaluation set for deployment decisions.

    1. Why Selection Matters More Than Chasing Leaderboards

    Public benchmarks reflect average performance on standardized test sets, but production requirements are often far more specific. A model that scores highly on math problems may fail to reliably produce well-formed JSON, or may not reach acceptable response times on a mid-range GPU.

    Selection should therefore start from your business constraints by answering four questions in order:

    1. Where will it be deployed? A server cluster, a single workstation, or on-device environments such as mobile phones.
    2. What are the latency and throughput floors? Do you need streaming output? Single-user or multi-user concurrency?
    3. What are the primary task types? Classification and extraction, multi-turn dialogue, code generation, long-document understanding, or multi-step tool calling.
    4. What compliance boundaries are acceptable? Does the license permit commercial use? Can data leave the local environment?

    Only after these four points are clear do parameter counts, architectures, and benchmark scores become meaningful for comparison.

    2. Understanding Parameter Scale: Total vs. Activated Parameters

    The parameter count in a model’s name usually refers to total parameters, but the number actually involved in computation during inference may be smaller. This distinction is key to understanding architectural differences.

    2.1 Dense Architectures

    A dense architecture uses all parameters in every forward pass. More parameters mean more computation per token and slower generation. The advantages are structural simplicity and predictable behavior—for the same parameter count, dense models generally deliver more consistent output quality.

    2.2 Mixture-of-Experts (MoE) Architectures

    An MoE architecture splits feed-forward layers into multiple expert sub-networks, with a router selecting only a few experts per token. This allows the total parameter count to be large while activated parameters per token remain small.

    Consider a model with roughly 25B total parameters and about 4B activated per token: its per-token compute is close to a 4B dense model, but its knowledge capacity is closer to that of a much larger model. The trade-off is that all expert weights must fit in VRAM—so memory usage is determined by total parameters, while speed is mainly determined by activated parameters.

    This distinction directly affects selection:

    Dimension Dense Mixture-of-Experts
    VRAM usage Determined by total parameters Determined by total parameters
    Compute per token Determined by total parameters Determined by activated parameters
    Generation speed Usually slower Usually faster
    Output stability Generally more predictable Depends on routing quality; variance may be higher
    Engineering complexity Low Higher; requires attention to expert load balancing

    3. Estimating VRAM and Memory

    Before deploying, estimate memory requirements. Estimation has two parts: model weights and the inference-time KV cache.

    3.1 Weight Footprint

    Weight memory = parameter count × bytes per parameter. At common precisions, FP16 uses 2 bytes, INT8 uses 1 byte, and INT4 uses roughly 0.5 bytes per parameter. Quantized weights also need a small extra allowance for quantization parameters.

    1. def estimate_weight_memory_gb(params_billion: float, bits_per_weight: int) -> float:
    2. """Estimate model weight memory in GiB (VRAM or RAM)."""
    3. total_bytes = params_billion * 1e9 * bits_per_weight / 8
    4. return total_bytes / (1024 ** 3)
    5. for bits in (16, 8, 4):
    6. print(f"25B parameters, {bits}-bit: ~{estimate_weight_memory_gb(25, bits):.1f} GiB")

    3.2 KV Cache Footprint

    The KV cache grows linearly with context length, and in long-context scenarios it can consume more memory than the weights themselves. The formula:

    KV cache bytes = 2 × number of layers × number of KV heads × head dimension × context length × bytes per element

    The factor of 2 accounts for caching both Key and Value. Layer counts and KV head counts vary significantly across models; some architectures use grouped-query attention to reduce KV head count, substantially lowering this overhead.

    1. def estimate_kv_cache_gb(layers: int, kv_heads: int, head_dim: int,
    2. context_len: int, bytes_per_elem: int = 2) -> float:
    3. total = 2 * layers * kv_heads * head_dim * context_len * bytes_per_elem
    4. return total / (1024 ** 3)

    In practice, also reserve headroom for the runtime environment, activations, and fragmentation—typically at least 10–20%.

    4. Inference Speed: Prefill vs. Decode

    Evaluate inference speed as two distinct phases.

    The prefill phase processes the input prompt. It is compute-heavy and mainly bounded by compute capacity, so it matters most for long inputs. The decode phase generates output tokens one at a time; each step reads the model weights, so it is typically bound by memory bandwidth.

    Decode speed has a rough upper bound:

    tokens per second ≈ effective memory bandwidth ÷ weight bytes read per token

    This explains why MoE architectures decode faster: each step only reads the activated experts’ weights. In real deployments, however, routing overhead, expert switching, and non-contiguous memory access push measured throughput below this theoretical bound—so always rely on measured data.

    When benchmarking speed, fix these conditions before comparing:

    • Context length—e.g., test at 2K, 8K, and 20K separately.
    • Batch size and concurrency level.
    • Quantization precision and inference framework version.
    • Output length—otherwise results lose comparability.

    5. Structured Output and Lightweight Agent Scenarios

    Small-parameter models often offer excellent cost-effectiveness for structured output, simple dialogue, and lightweight tool calling. What matters here is not knowledge breadth but reliably following a format.

    5.1 Basic Approaches to Constrained Output

    Layer one is prompt constraints: specify fields, types, and examples explicitly in the instruction. Layer two is decoding constraints: some inference frameworks can restrict output according to a grammar or JSON Schema. Layer three is programmatic validation: regardless of whether the first two layers are in place, validate again in application code.

    Here’s a validation example using only the standard library:

    1. import json
    2. REQUIRED_FIELDS = {"intent": str, "entities": list, "confidence": float}
    3. def parse_model_output(raw_text: str) -> dict:
    4. """Parse and validate a structured model response; raise on failure so callers can retry."""
    5. try:
    6. data = json.loads(raw_text)
    7. except json.JSONDecodeError as exc:
    8. raise ValueError(f"Output is not valid JSON: {exc}") from exc
    9. for field, expected_type in REQUIRED_FIELDS.items():
    10. if field not in data:
    11. raise ValueError(f"Missing field: {field}")
    12. if not isinstance(data[field], expected_type):
    13. raise ValueError(f"Field {field} has wrong type, expected {expected_type.__name__}")
    14. if not 0.0 <= data["confidence"] <= 1.0:
    15. raise ValueError("confidence out of [0, 1] range")
    16. return data

    5.2 Latency Budgeting for Agent Workflows

    The total time of a multi-step agent workflow is the sum of its steps, so assign a budget to each. For example, in a three-step flow—intent recognition, parameter extraction, and tool calling—with a 3-second total budget, set an explicit cap per step and fall back to rule-based logic or human handling on timeout.

    6. Licenses and Compliance

    The license determines whether a model can be used in commercial products, modified and redistributed, and whether attribution or notices are required. Have legal or compliance staff confirm:

    1. Whether the license terms permit commercial use and redistribution.
    2. Whether there are restrictions on use cases or user scale.
    3. Whether fine-tuned derivative models must comply with the same terms.
    4. Whether the training data provenance meets your organization’s audit requirements.

    License terms can change between versions. Always rely on the latest official text, and record the version you use for future traceability.

    7. Building Your Own Evaluation Set

    Public leaderboards cannot replace business-specific evaluation. Extract a batch of samples from real workloads, stratify them by task type, and define automatically checkable metrics for each task category.

    A practical process:

    1. Collect at least several hundred real inputs, covering common requests and edge cases.
    2. Annotate each sample with expected output; for open-ended tasks, use scoring rubrics.
    3. Run candidate models under identical settings, recording accuracy, format compliance rate, latency, and peak memory.
    4. Categorize failures: insufficient knowledge, format errors, or broken reasoning chains.
    1. def evaluate(model_fn, samples: list[dict]) -> dict:
    2. """Compute format compliance rate and field accuracy. model_fn takes input text and returns raw output."""
    3. format_ok, field_ok = 0, 0
    4. for sample in samples:
    5. raw = model_fn(sample["input"])
    6. try:
    7. result = parse_model_output(raw)
    8. except ValueError:
    9. continue
    10. format_ok += 1
    11. if result["intent"] == sample["expected_intent"]:
    12. field_ok += 1
    13. total = len(samples)
    14. return {
    15. "format_rate": format_ok / total,
    16. "intent_accuracy": field_ok / total,
    17. }

    Track both format compliance and business accuracy. A model with slightly higher accuracy but frequent format failures can be harder to use in engineering than one with slightly lower accuracy but stable output.

    8. Selection Strategies for Typical Scenarios

    On-device or offline scenarios: Prefer small dense models or low-bit quantized versions. Focus on peak memory and time-to-first-token, and verify runtime compatibility with the target device.

    Single-server scenarios: Mid-parameter MoE models often strike a good balance between throughput and quality—but reserve enough VRAM for the KV cache and load-test concurrency under long contexts.

    High-quality reasoning scenarios: Large dense models are typically more stable for complex reasoning, but per-request cost and latency are higher. They work best as a fallback or offline batch-processing capability rather than the default path for every request.

    Hybrid deployment: Route requests by task difficulty—send simple tasks to small models and escalate complex ones to larger models—to better balance overall cost and quality.

    9. Common Pitfalls

    Pitfall 1: Equating total parameters with capability. Parameter count is only one factor; training data, training methods, and post-training quality matter just as much.

    Pitfall 2: Deciding on a single speed metric. A fast-generating model with unstable output needs more retries, so its real end-to-end cost may not be lower.

    Pitfall 3: Ignoring the memory cost of long contexts. A configuration that performs well in short-context tests may fail to run at all under long contexts due to the KV cache.

    Pitfall 4: Substituting subjective impressions for data. Personal experience is valuable, but it should be converted into reproducible test samples and metrics to support team decisions.

    10. Conclusion

    Open-source LLM selection is a constrained optimization problem. Start by clarifying your deployment environment, latency requirements, task types, and compliance boundaries; narrow the candidates through memory estimation and speed analysis; then validate with your own evaluation set.

    Mastering the difference between total and activated parameters, prefill vs. decode behavior, and structured-output validation lets you make evidence-based comparisons across models—and turn selection into an engineering process you can continuously iterate on.