Guide to Reducing Costs for Ultra-Large LLMs: Calculate Costs Before Optimizing Architecture

    This article explores cost optimization strategies for ultra-large language models (LLMs), emphasizing the importance of accurate cost calculation before optimizing system architecture. It covers model selection by scale, a monthly cost estimation formula, and enterprise-level architecture design, including semantic caching and cloud-native configuration.

    With the rapid development of artificial intelligence, the parameter scale of large language models (LLMs) continues to grow. Recently, the open-source community has seen Mixture of Experts (MoE) models with hundreds of billions or even trillions of parameters, some of which approach closed-source flagship models in public benchmarks. However, benchmarking methodologies vary significantly. Before citing performance conclusions, it is necessary to verify the model name, total and activated parameter counts, benchmark dataset, and release date.

    For enterprises, model capability is only the first step. API call costs, system architecture integration, and engineering practices equally determine whether an LLM can truly support business operations. This article starts with cost accounting and then explores architectural methods for cost reduction.

    1. Model Scale and Performance Status

    Over the past year, the release pace of open-source LLMs has noticeably accelerated. Progress has been made in model architecture, training data quality, and distributed training algorithms. Ultra-large models demonstrate strong performance in long-context understanding, multi-step reasoning, and task planning.

    For enterprises, LLMs are no longer just conversational tools. They are beginning to undertake tasks such as business document comprehension, structured and unstructured data processing, intelligent customer service, code generation assistance, and industry analysis. These scenarios demand much higher accuracy and stability than demo environments.

    2. Calculate Costs First: Balancing Performance and Expenses

    When vendors release new versions, they often lower API unit prices. However, after a price drop, business call volumes typically increase, meaning the total final cost may not actually decrease. Rising costs usually stem from the following three reasons:

    1. Amplified Call Volume: Lower unit prices encourage more business teams to integrate. As a business moves from a pilot phase to full-scale deployment, request volumes might grow by tens of times or more.
    2. Prompt Bloat: To improve answer quality, developers often stuff business context, conversation history, and sample data into the prompt. This increases the input token count, driving up the cost per request.
    3. Redundant Calls: Similar questions repeatedly hitting the model backend lead to wasted computational resources.

    1. Model Selection by Scale

    Model selection should not rely solely on benchmark scores. The table below provides a qualitative comparison. For specific values, refer to the current official pricing and documentation from each vendor.

    Dimension Ultra-Large Models (Trillion-level MoE, etc.) Medium-Scale Models Small or Distilled Models
    Complex Reasoning and Multi-step Planning Strong Medium Average, depends on task design
    Cost per Call Usually highest Medium Usually lowest
    Context Window Usually large Depends on specific model Depends on specific model
    Response Latency Usually longer Medium Usually shorter
    Applicable Scenarios Long document analysis, complex reasoning, low-frequency high-value tasks General Q&A, content generation Classification, extraction, high-frequency simple Q&A

    2. Monthly Cost Formula

    To determine whether an architecture optimization is worthwhile, you can estimate monthly costs using the following formula:

    C = N × [(1 − h) × (1 + r) × (L_in × p_in + L_out × p_out) / 10⁶ + h × c_hit]

    The variables are defined as follows:

    • N: Total monthly requests.
    • h: Cache hit rate; when a hit occurs, the model is not called.
    • r: Retry rate, the proportion of additional calls made after a failure.
    • L_in, L_out: Average number of input and output tokens.
    • p_in, p_out: Price per million tokens for input and output.
    • c_hit: Average cost per cache hit, including vector computation and storage.

    Example (numbers are hypothetical and for demonstration only): Assume 1 million monthly requests, a cache hit rate of 30%, a retry rate of 2%, an average input of 2000 tokens, an average output of 500 tokens, an input price of $2 per million tokens, an output price of $8 per million tokens, and a cache hit cost of $0.0002 per call.

    • Without cache or retries: The cost per call is (2000×2 + 500×8)/10⁶ = 0.008, making the monthly cost $8,000.
    • With cache and retries: The number of cache misses is 1,000,000 × 70% × 1.02 = 714,000. The model cost is 714,000 × 0.008 = $5,712. The cost for hit entries is 300,000 × 0.0002 = $60. The total is $5,772.

    Under these assumptions, the monthly cost drops by about 28%. The actual effect depends on the cache hit rate; a lower hit rate yields fewer savings.

    3. Applicable Boundaries

    Ultra-large models are suitable for long document analysis, complex reasoning, and low-frequency, high-value tasks. High-frequency tasks like classification, information extraction, and fixed-template Q&A should prioritize small or distilled models. The two can be used in combination: small models handle the majority of requests, escalating to a large model only when they cannot process the request.

    3. Enterprise Cost-Reduction Architecture Design

    When integrating LLMs, enterprises should not directly forward business requests to the model API. Components such as caching, retrieval, and rate limiting should be integrated into the request pipeline.

    1. Semantic Caching

    For high-frequency questions with similar semantics, semantic caching can directly return historical answers. The basic flow involves converting the question into a vector, calculating the cosine similarity with cached vectors, and returning a hit if it exceeds a threshold.

    Below is a minimal runnable example. It uses character bigram hashing as the vectorization method purely to demonstrate the flow. In a production environment, this should be replaced with a semantic vector model, and the cache should be stored in Redis or a vector database, as the in-memory structure in this example does not support multi-process sharing.

    1. # Dependencies: pip install numpy openai
    2. import os
    3. import time
    4. import hashlib
    5. from dataclasses import dataclass
    6. import numpy as np
    7. def embed_text(text: str, dim: int = 512) -> np.ndarray:
    8. """Demo vectorization: Counts hash distribution of character bigrams. Replace with a semantic vector model in production."""
    9. vec = np.zeros(dim, dtype=np.float32)
    10. s = text.strip()
    11. for i in range(len(s) - 1):
    12. idx = int(hashlib.md5(s[i:i + 2].encode("utf-8")).hexdigest(), 16) % dim
    13. vec[idx] += 1.0
    14. norm = np.linalg.norm(vec)
    15. return vec / norm if norm > 0 else vec # After normalization, the dot product is the cosine similarity
    16. def call_llm(prompt: str) -> str:
    17. """Calls an OpenAI-compatible interface. Keys and URLs are read from environment variables, not hardcoded."""
    18. from openai import OpenAI
    19. client = OpenAI(
    20. api_key=os.environ["LLM_API_KEY"],
    21. base_url=os.environ.get("LLM_BASE_URL"),
    22. timeout=30,
    23. )
    24. resp = client.chat.completions.create(
    25. model=os.environ.get("LLM_MODEL", "your-model"),
    26. messages=[{"role": "user", "content": prompt}],
    27. )
    28. return resp.choices[0].message.content
    29. @dataclass
    30. class CacheEntry:
    31. vec: np.ndarray
    32. response: str
    33. created_at: float
    34. class SemanticCache:
    35. def __init__(self, threshold: float = 0.95, ttl_seconds: int = 3600, max_size: int = 10000):
    36. self.threshold = threshold
    37. self.ttl = ttl_seconds
    38. self.max_size = max_size
    39. self.entries: list[CacheEntry] = []
    40. def _evict(self) -> None:
    41. now = time.time()
    42. self.entries = [e for e in self.entries if now - e.created_at < self.ttl]
    43. if len(self.entries) > self.max_size:
    44. self.entries = self.entries[-self.max_size:]
    45. def get(self, query_vec: np.ndarray) -> str | None:
    46. self._evict()
    47. if not self.entries:
    48. return None
    49. matrix = np.stack([e.vec for e in self.entries])
    50. sims = matrix @ query_vec
    51. best = int(np.argmax(sims))
    52. return self.entries[best].response if sims[best] >= self.threshold else None
    53. def put(self, query_vec: np.ndarray, response: str) -> None:
    54. self.entries.append(CacheEntry(query_vec, response, time.time()))
    55. def answer(query: str, cache: SemanticCache) -> tuple[str, bool]:
    56. qv = embed_text(query)
    57. hit = cache.get(qv)
    58. if hit is not None:
    59. return hit, True
    60. resp = call_llm(query)
    61. cache.put(qv, resp)
    62. return resp, False

    The cache threshold should not be guessed based on experience; it should be determined through offline evaluation:

    • Manually label a batch of question pairs (e.g., 2,000 pairs), marking whether the two questions share the same intent.
    • Scan thresholds step-by-step from 0.85 to 0.98, calculating the precision (the proportion of hits where the intent truly matches) and hit rate for each level.
    • Select the threshold that meets the business precision floor (e.g., no less than 98%) while yielding the highest hit rate.

    Cache invalidation must also be designed. After knowledge base updates, prompt modifications, or model version switches, old caches should be cleared or isolated by version number. For time-sensitive questions, the TTL should be set shorter.

    2. Cloud-Native Service Configuration

    Container Platforms and Auto-scaling: Deploy the LLM gateway and business backend on a container platform, scaling based on request queue length or GPU utilization. Scale-down operations should include a cooldown period to avoid traffic jitter.