Sr. Content Developer at Microsoft, working remotely in PA, TechBash conference organizer, former Microsoft MVP, Husband, Dad and Geek.
159616 stories
·
33 followers

Top Album Releases Linked To Rise In Fatal Crashes

1 Share
An anonymous reader quotes a report from The Guardian: The release of a new album by Taylor Swift might be a cause for celebration among her fans, but such events have also been linked to a more sombre phenomenon: an increase in fatal car crashes. The team behind a new study say it sheds light on the impact of distracted driving. Writing in the journal Jama Network Open, [Vishal Patel, first author of the study based at Harvard Medical School] and colleagues report how they focused on the release of 10 major albums, launched between 2017 and 2022, selected for having the highest number of Spotify streams over a single day. [...] The team found streaming volume for the top 200 songs in the US was 43% higher on the date of major album releases compared with the days surrounding the releases -- although such data does not reveal whether the music was being streamed in a car. [...] The researchers used data from a population-based registry of fatal US motor vehicle crashes to look at the number of traffic fatalities on the dates these albums were released, as well as for the 10 days either side. After taking into account the day of the week upon which the album was released, as well as federal holidays, and time of year, the researchers found the number of US traffic fatalities showed a relative increase of 15.1% on the date of major album releases, compared with similar days either side. "This is equivalent to approximately 182 fatalities in the US attributable to the release days of the 10 included albums," the team writes. Patel said the release of a new album could distract drivers because accessing music is a search task, not a single button press. "You unlock the phone, open the app, find the release, read down a tracklist, tap the right song. That's several seconds of looking at a screen," he said, adding unfamiliar music also demands more attention, while research has suggested listening to new, high-energy music measurably degrades driving performance. The researchers add the rise in traffic fatalities was greater among certain groups -- such as younger drivers, male drivers, people who were driving alone, and people driving cars with a built-in infotainment platform. The authors say the results suggest that "online music streaming through smartphones may significantly contribute to distracted driving and traffic fatalities."

Read more of this story at Slashdot.

Read the whole story
alvinashcraft
8 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

Advanced Prompt Engineering for Software Developers: Frameworks, Patterns, and Best Practices

1 Share
Advanced Prompt Engineering for Software Developers: Frameworks, Patterns, and Best Practices

As foundation models become integral to modern software architecture, the ability to instruct large language models with precision and determinism has evolved into a vital engineering competency for developers across India and globally.

 

In this technical guide, we explore advanced prompt engineering methodologies, structural design patterns, context optimization strategies, and robust schema enforcement techniques to build production-grade AI-powered applications.

 

Advanced Prompt Engineering for Developers
Engineering robust system prompts, structured reasoning chains, and deterministic AI workflows.

 

Table of Contents

 

  • Understand the transition from conversational prompting to deterministic, software-driven prompt architecture.
  • Master core reasoning patterns including Few-Shot Learning, Chain-of-Thought (CoT), and ReAct orchestration.
  • Learn proven techniques for enforcing strict JSON outputs and strongly typed schema validation in production.
  • Optimize context windows and mitigate token bloat using semantic compression and strategic placement.
  • Implement defensive prompt design to prevent prompt injection attacks and eliminate model hallucinations.

The Transition from Casual Chatting to Deterministic AI Engineering

In the early days of generative models, prompting was often viewed as trial-and-error conversational art. Users experimented with phrasing until the model produced a visually pleasing answer. However, integrating models into enterprise software pipelines demands repeatability, predictable latencies, and strict adherence to data contracts.

 

Deterministic prompt engineering treats the language model as an untyped compute engine that requires explicit system instructions, well-defined state schemas, and rigorous constraint boundaries to function reliably alongside backend services.

 

Effective prompt engineering is not about finding magical keywords; it is about structuring context, defining operational boundaries, and eliminating ambiguity.

 

If you are exploring the latest developer tools to streamline this workflow, our review of top AI coding tools and IDE extensions covers the leading terminal assistants and prompt testing platforms available today.

 

Furthermore, mastering these techniques has become indispensable for career advancement. You can explore our insights on essential technical skills for career growth in modern tech to see why human-AI collaboration is shaping hiring priorities.

 

 

 

Core Prompting Patterns: Few-Shot, Chain-of-Thought, and ReAct

To extract high-accuracy logical reasoning from language models, software developers rely on several structured patterns that guide the model through intermediate cognitive steps before producing a final answer.

 

Selecting the appropriate prompting pattern depends on whether your task involves classification, multi-step algorithmic calculation, or dynamic external tool invocation.

 

Abstract software architecture and data streams
Architecting structured multi-step reasoning frameworks and dynamic tool integration.

 

Essential Prompting Design Patterns

  • Few-Shot In-Context Learning: Providing 3 to 5 clear input-output pairs inside the prompt establishes the exact stylistic tone, response syntax, and domain vocabulary far more effectively than lengthy descriptive explanations.
  • Chain-of-Thought (CoT) Prompting: Explicitly instructing the model to break down complex mathematical or architectural decisions into sequential logical steps drastically reduces arithmetic regressions and false assumptions.
  • Reasoning and Acting (ReAct): Interleaving cognitive reasoning traces with external tool invocations allows the model to observe execution outputs, reflect on runtime errors, and iteratively refine API calls until the goal is achieved.
  • Skeleton-of-Thought (SoT): Guiding the model to first outline a high-level response skeleton before expanding each section in parallel reduces output latency for long-form code generation and technical reports.

Combining these structural patterns ensures that the model maintains deep contextual awareness across complex, multi-stage engineering workflows.

 

 

 

Enforcing Structured JSON Outputs and Strict Schema Validation

When connecting language models to backend microservices, databases, or UI components, unstructured free-form text is completely unacceptable. Developers require strictly typed JSON objects that can be parsed and validated without runtime exceptions.

 

Modern foundation models support native JSON Schema enforcement and grammar-based decoding, guaranteeing that every generated token conforms strictly to your data model.

 

Best Practices for Structured Output Generation

  • Define Explicit TypeScript or Pydantic Interfaces: Embed verbatim interface definitions directly in your system prompts to clearly signal required fields, optional properties, and valid enum values.
  • Constrained Grammar Decoding: Utilize provider-level structured output parameters (such as response_format with JSON schemas) to restrict model token generation strictly to valid JSON grammar at the sampling layer.
  • Defensive Error Handling and Fallbacks: Always wrap parsing logic in try-catch blocks and implement secondary validation passes to catch schema mismatches before mutating production databases.

Adopting rigorous schema validation transforms language models from creative toys into dependable microservice building blocks.

 

 

 

Context Window Optimization and Token Efficiency

While modern foundation models boast context windows spanning hundreds of thousands of tokens, casually packing massive document repositories into a single prompt leads to substantial latency spikes, high API costs, and context degradation.

 

The infamous "needle-in-a-haystack" phenomenon demonstrates that models often pay higher attention to information positioned at the very beginning and the very end of a prompt, while occasionally overlooking critical details placed in the middle.

 

To maximize accuracy while preserving token budgets, developers should implement semantic chunking, dynamic context trimming, and hierarchical retrieval before injecting reference data into the active prompt window.

 

When engineering high-throughput backend services that handle concurrent prompt pipelines, consulting our guide on enterprise cloud-native software engineering practices will help ensure optimal memory allocation and low-latency execution.

 

 

 

Defensive Prompt Design and Security Hardening

In production applications where user inputs are directly passed into LLM pipelines, security vulnerabilities such as Direct and Indirect Prompt Injections pose significant operational risks.

 

Malicious actors can craft adversarial prompts designed to hijack system instructions, leak private API keys, or bypass safety guardrails.

 

Hardening Strategies for Enterprise System Prompts

  • Clear Delimiter Boundaries: Wrap untrusted user inputs inside distinct XML tags (e.g., <user_input>...</user_input>) and instruct the model to treat content inside those tags exclusively as raw data rather than executable instructions.
  • Explicit Negative Constraints: State what the model must NEVER do under any circumstance, including instructions to ignore attempts to reveal internal system rules or role overrides.
  • Secondary Guardrail Evaluators: Deploy lightweight classification models or heuristic filters to inspect incoming prompts and outgoing responses for anomalous patterns before returning data to the client.

Just as in traditional software development, following best practices for rigorous code reviews and quality assurance ensures that your prompt templates undergo thorough peer verification before reaching production environments.

 

 

 

Frequently Asked Questions (FAQ)

Here are answers to the most common questions software developers have regarding advanced prompt engineering:

 

1. Is prompt engineering still relevant with reasoning models like o1/o3?

Yes. While reasoning models perform internal chain-of-thought, prompt engineering remains critical for defining objective constraints, context structuring, tool interfaces, output schemas, and security boundaries.

 

2. What is the difference between Zero-Shot and Few-Shot prompting?

Zero-Shot prompting asks the model to perform a task with only descriptive instructions. Few-Shot prompting provides several concrete input-output examples inside the prompt to illustrate the exact desired output format and reasoning style.

 

3. How do XML delimiters help prevent prompt injection?

XML delimiters create clear structural boundaries between developer system instructions and untrusted user input, making it difficult for an attacker to override system rules with malicious injection payloads.

 

4. Can I use prompt engineering to guarantee 100% valid JSON?

While prompt formatting helps, using native provider features like JSON Schema mode and constrained grammar decoding is the only way to mathematically guarantee valid JSON output at the token generation level.

 

5. What is the "Lost in the Middle" phenomenon in LLM prompts?

It refers to the tendency of language models to pay the most attention to tokens located at the start and end of a large prompt context, while occasionally missing nuances positioned in the middle third.

 

6. How does temperature affect prompt reproducibility?

Setting temperature to 0.0 minimizes randomness and makes outputs largely deterministic and focused, which is ideal for code generation, data extraction, and structured classification tasks.

 

7. What is ReAct prompting?

ReAct stands for Reason + Act. It is a paradigm where the model alternates between generating an explicit thought step, executing an action (like calling a tool or API), and observing the result to refine its next step.

 

8. Should I write system prompts in English or regional languages?

System instructions and structural rules are best written in English because foundation models have the deepest pretraining in English, though they can seamlessly process inputs and generate outputs in regional Indian languages.

 

9. What is Chain-of-Thought (CoT) prompting?

Chain-of-Thought prompting encourages the model to generate intermediate reasoning steps before arriving at a final answer, significantly improving accuracy on complex logic, math, and code debugging tasks.

 

10. How can I measure and benchmark prompt improvements?

You can create automated evaluation datasets (evals) with diverse test cases and run automated scoring using assertion tests, schema validators, or LLM-as-a-judge frameworks to track accuracy improvements over time.

 

Mastering prompt engineering bridges the crucial gap between raw AI model capabilities and robust software engineering practices. By treating prompt templates with the same rigor, version control, and automated testing as traditional application code, developers can build dependable systems that consistently deliver accurate results.

 

As you design your next AI-enabled feature, experiment with clear XML delimiters, integrate structured JSON schema validation, and evaluate your prompt changes against comprehensive benchmark suites.

 

I would love to hear about the prompt design patterns and optimization strategies that have worked best in your development stack. Feel free to share your experiences, questions, and insights in the comments section below!

 

Read the whole story
alvinashcraft
8 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

Welcome back to The GitHub Podcast!

1 Share

The GitHub Podcast is back for Season 2! In the season opener, Cassidy Williams is joined by co-hosts Marlene Mhangami and GPS Peña-Siguenza. The trio revisits their favorite moments from Season 1, including Keeley Hammond's take on Electron and why “bloated JavaScript” hot takes don't hold up, Angie Jones's conversation on MCP and Goose, and the Tiny Wins team's work fixing the everyday "paper cuts" that make life easier for open source maintainers. From there, the hosts dig into their own winding paths into tech. GPS’ shares her journey from sysadmin to .NET and Cloud Advocacy to building a free open source platform that teaches cloud fundamentals (now used by nearly 7,000 people). Marlene traces her path from studying molecular biology to becoming a fixture in the Python community, and her early open source work on CuDF at NVIDIA, advocating for Ibis at Voltron Data, then starting the LangChain Azure repository at Microsoft. Cassidy rounds out the episode with insights to her front-end and React roots and her early days making tech memes on TikTok. Finally, each host shares an open source pick of the week: Mediabunny, Handy, and Cua.

Links mentioned in the episode:

Electron

MCP

Goose

Learn to Cloud

CUDF

Ibis

Langchain Azure

Mediabunny

Handy

https://github.com/trycua/cua

CUA

The GitHub Podcast is produced and edited by editaudio.


Hosted by Simplecast, an AdsWizz company. See pcm.adswizz.com for information about our collection and use of personal data for advertising.





Download audio: https://afp-920613-injected.calisto.simplecastaudio.com/98910087-00ff-4e95-acd0-a3da5b27f57f/episodes/a8f898b3-c909-4a73-a0a9-c26ad10dbcbf/audio/128/default.mp3?aid=rss_feed&awCollectionId=98910087-00ff-4e95-acd0-a3da5b27f57f&awEpisodeId=a8f898b3-c909-4a73-a0a9-c26ad10dbcbf&feed=ioCY0vfY
Read the whole story
alvinashcraft
9 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

How People Are Fixing AI's Problems

1 Share
From: AIDailyBrief
Duration: 25:33
Views: 2,006

AI is solving old problems while creating entirely new ones. NLW looks at how people and companies are responding to AI slop, rising token costs, uneven productivity, workforce deskilling, and the long-term challenge of preserving human expertise.

The AI Daily Brief helps you understand the most important news and discussions in AI.
Subscribe to the podcast version of The AI Daily Brief wherever you listen: https://pod.link/1680633614
Get it ad free at http://patreon.com/aidailybrief
Learn more about the show https://aidailybrief.ai/

Read the whole story
alvinashcraft
9 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

Introducing the Raspberry Pi Compute Module 5 Programming Jig

1 Share

Making a single device is hard; you have to prepare your hardware, your software, your documentation, and how you’re going to sell it. Once you clear all of those barriers, you stare down a new realm of problems — how do you make the next thousand?

For developers designing products based on Raspberry Pi Compute Module 5, we’ve made that problem space smaller with the new Raspberry Pi Compute Module 5 Programming Jig: a single-head provisioning system that programs your Compute Module 5 with an operating system and security configuration.

Simple, repeatable provisioning

The Programming Jig simplifies the provisioning workflow by taking the bulk of the configuration steps out of your hands; after setting up the jig’s software and connecting the ports you require, all you need to do is insert the Compute Module 5 into the module bay and press the clamp shut. No further interventions are required — the status LED will tell you when the unit has been programmed.

On the back of the Programming Jig, you’ll see a small set of ports, including Ethernet for the jig and the Compute Module 5 you want to program, and a USB programming port to manually update the jig software. There are also two activity LEDs — one for the jig and one for the module — that signal what the devices are doing.

To go even faster, you can connect both the JIG ETH and DUT ETH ports to the same network.

Built around Raspberry Pi OS

To automate many aspects of production — including secure boot implementation, full disk encryption, and bare operating system installation — the Raspberry Pi Compute Module 5 Programming Jig needs capable software. So, we built it around our OS construction tool, rpi-image-gen, and our automated provisioning software, rpi-sb-provisioner.

The jig’s OS ties in to other Raspberry Pi software, notably Raspberry Pi Imager. The recently released v2.0.11 promotes the Compute Module writing functionality to public availability, and this can be used to customise the jig’s OS to your requirements — including configuring Wi-Fi, security, and user settings.

Using the same OS components as our other platforms makes a wide range of customisation scripts and functions available for provisioning purposes. More than that, you also get the benefit of ongoing development and new features in Raspberry Pi OS, Raspberry Pi Connect, and rpi-sb-provisioner.

Available now

The Raspberry Pi Compute Module 5 Programming Jig is priced at $600 and is available to order now through our global network of Approved Resellers.

You can find instructions for the Programming Jig on our documentation page. Our rpi-image-gen and rpi-sb-provisioner tools are available on the Raspberry Pi software sources page.

The post Introducing the Raspberry Pi Compute Module 5 Programming Jig appeared first on Raspberry Pi.

Read the whole story
alvinashcraft
9 minutes ago
reply
Pennsylvania, USA
Share this story
Delete

The tokenomics of self-hosted LLMs

1 Share

Paying a cloud API per million tokens is straightforward until the invoice arrives. But when you move to self-hosted large language models (LLMs), the economics flip upside down: you pay for raw compute regardless of whether your GPUs are processing requests or idling.

For platform engineers and machine learning operations (MLOps) leads, tokenomics, the economics of how tokens are produced and what they effectively cost, requires looking at both what you spend and how much you serve.

Calculating cost per token for self-hosted LLMs comes down to controlling 2 main levers: spending less and serving more.

A simple formula

At its core, cost per token over a period of time is:

Cost per token = operating cost ÷ tokens processed

To improve that metric, you can reduce the overall cost, increase the number of tokens processed, or both.

Suppose your LLM infrastructure costs about US$50,000 per month and you process 500 million tokens in that month:

US$50,000 ÷ 500M tokens ≈ 10 cents per million tokens

If you cut monthly costs to US$40,000 without changing usage, cost per million tokens drops to about 8 cents. If, instead, you keep the US$50,000 spending but grow usage to 1,000M tokens, cost per million tokens drops to about 5 cents. Both paths improve the metric.

Self-hosted LLM cost breakdown

Cost can be broken down into a few high-level categories:

  • Hardware/infrastructure
  • Software
  • People
  • Other

Hardware and infrastructure costs

In a cloud model, hardware and infrastructure costs are generally straightforward because they appear on a monthly provider bill. You pay a fixed hourly rate for your instance type, plus additional fees for storage and network egress.

However, if you are self-hosting your own hardware, things can get a little more complicated. Let's say you purchased a node for US$500,000 as a capital expenditure. To understand the cost of that node for a single month, you would need to understand the expected lifespan of that node and depreciate the cost of it over that period of time. In simpler terms, if you expect to use that node for 4 years, you can take US$500,000/48 to get a monthly cost of about US$10,400. In addition to the nodes themselves, you probably also need to factor in other hardware such as networking hardware.

For both scenarios, you might also want to factor in the cost of other hardware in the cluster, such as your control planes. If you are running your GPU workloads in a multi-tenant environment with other use cases, you might wish to spread these costs across all of your use cases.

Software and personnel costs

Software is another area to factor in. If you are using Red Hat OpenShift AI, the most common stock-keeping unit (SKU) purchased by customers is Red Hat OpenShift AI Enterprise, which includes entitlements for Red Hat OpenShift, Red Hat OpenShift AI, and accelerators on that node. While some customers might choose to pay for the individual pieces of software separately, these are the main software costs from Red Hat.

The cost of the people needed to deploy, support, and manage your LLM infrastructure is an often overlooked aspect of running your own LLMs. Organizations frequently have a dedicated team managing multiple OpenShift clusters, and a portion of that team's time can be allocated and tracked toward the cost of running your own LLMs. Enterprise AI platforms reduce engineering labor by standardizing model delivery. Instead of developers building custom container images and updating vLLM runtimes manually, automated platform catalogs handle runtime maintenance, but people remain part of the true operating cost.

For a complete total cost of ownership (TCO), also account for facility overhead: power consumption, cooling, datacenter staffing, and physical rack footprint.

Optimizing costs to reduce LLM cost per token

To lower the US$50,000 monthly spending from our example, start by targeting your biggest infrastructure costs.

Platform teams often default to top-tier GPU instances out of caution. But locking up an 8xH100 node for a low-traffic internal chatbot drains budget unnecessarily. Matching GPU capacity to actual usage profiles, such as swapping a p5.48xlarge for a budget-friendly g6e.48xlarge with eight L40S GPUs, keeps costs grounded.

Autoscaling both the model server replicas and the nodes in the cloud environment can also have a dramatic effect on the cost of running an LLM. Letting instances scale down to a minimum number of replicas while usage is low, and automatically scaling them back up when traffic is heavier, is an effective way to reduce overall costs while still maintaining required service level objectives (SLOs).

For self-hosted environments, you can still take advantage of autoscaling to reduce how much hardware a specific model is using and free up those resources for other use cases, such as overnight batch training jobs, to spread the cost of the hardware across multiple workloads. Additionally, while you are committed to the hardware you have purchased, spending more time up front to understand what models you plan to deploy, and how many requests or tokens you need to serve, can help you right-size before making hardware purchases.

Software choices also affect people cost. Platforms like OpenShift AI make it easier to source models and run supported vLLM releases from a container registry, which reduces the time teams spend building and maintaining custom inference images, and this time savings helps to improve operating costs.

Tokens processed

Tokens processed can be evaluated from two different lenses: your theoretical maximum (how many tokens the system could process) and your actual tokens processed (how many you did process over a period of time).

You can derive the theoretical maximum by performing load testing with tools such as GuideLLM, which simulates realistic workloads and ramps up concurrent connections until performance starts to degrade. Based on that result, you can estimate the theoretical maximum number of tokens you can process in a period of time. For example, if you were able to process 1M tokens per minute, you could theoretically process 1,440M tokens per day.

In most scenarios, you won't be able to sustain that level of maximum load 24x7. However, the theoretical maximum is still useful for right-sizing and capacity planning. For example, it helps you decide how many replicas you need to meet real-world demand. If you have built a system that can process 1,440M tokens per day, but you are only processing 50M, you might be over-provisioned relative to demand, which keeps the cost side of the formula high relative to the tokens side.

Measuring real-world token processing is a better metric for deriving cost per token. Returning to our example: US$50,000 ÷ 500M tokens is your true cost per token for that month, not US$50,000 divided by the theoretical maximum you could have served if the system ran flat-out.

Red Hat OpenShift AI helps make it easy to measure your real-world token usage through its integration with Red Hat OpenShift metrics and Prometheus, and helps track usage by individuals and teams with Models-as-a-Service.

Optimizing tokens processed

The biggest effect on cost per token usually comes from increasing overall usage, not from squeezing more peak throughput out of an underutilized system. If your system can process 1,440M tokens per day but you are only processing 500M, consolidating internal AI workloads onto a shared cluster fills idle GPU cycles. Running background batch processing alongside interactive chat directly increases token volume without adding hardware cost. In our monthly example, growing from 500M to 1,000M tokens at the same US$50,000 spending halves the cost per million tokens.

It also helps to better use the system in non-peak hours. Shifting batch workloads to off-peak hours can raise the number of tokens processed without adding hardware, while keeping performance high for peak interactive traffic.

Teams often turn next to optimizing the model deployment itself by tuning serving configuration, batching, and related settings to raise throughput. That work primarily increases theoretical maximum capacity, not actual tokens processed. If you optimize a deployment from 1,440M to 1,800M tokens per day of capacity (+25%) but real-world usage stays at 500M, the cost per token doesn't change.

Those optimizations still matter as enablers: higher capacity can absorb additional use cases without new hardware, or let you scale down to fewer resources if demand is already met. Treat them as a way to either grow the tokens side or shrink the cost side, not as an automatic win on cost per token by themselves.

Tuning with vLLM and llm-d

By default, vLLM balances throughput against request latency with zero setup. However, tuning settings such as batch size and block allocation for your specific workload unlocks significantly higher throughput while staying within your SLO thresholds.

Llm-d also offers a number of performance tuning options that can positively affect cost per token. Capabilities such as intelligent routing create more opportunities to take advantage of key-value (KV) cache hits when you have multiple vLLM replicas. Additionally, KV cache offloading allows you to use CPU memory to expand the KV cache beyond what can be stored in vRAM, and prefill and decode disaggregation can help reduce bottlenecks in vLLM for larger-scale deployments.

The impact of model choice

The model you choose pulls on both sides of the formula. Larger models usually raise the cost side through more GPUs per replica. They can also change how many tokens you can serve per dollar on the tokens side through throughput and latency characteristics.

A model such as Llama-3.1-8B-Instruct is significantly smaller than Llama-3.3-70B-Instruct. The 8B model can easily fit on a single H100, or a more budget-friendly GPU like an L40S, while the 70B model might require up to four H100s to serve a single instance. Choosing the smaller model when quality is "good enough" for the use case can cut hardware costs sharply while also enabling higher total throughput, and, if that frees budget or capacity for more traffic, the cost per token improves further.

Quantization is another lever. An FP8 (8-bit floating-point) version of the 70B model can be deployed on four H100s instead of four, reducing the required hardware while aiming to preserve much of the model's quality.

Quantization cuts GPU memory requirements—for instance, compressing FP16 weights to FP8—allowing you to double batch sizes on identical GPUs or host models on fewer accelerator cards.

Input tokens, cached tokens, and output tokens

When dealing with cloud providers, you will often see different prices depending on the type of tokens being processed. Even when you self-host, those same token types still have different effective costs because they consume the GPU differently. Your mix of input, cached, and output tokens therefore shapes the real cost per token, even when you are not paying a published per-token rate.

Evaluating input and cached tokens

Input tokens are generally processed in a single pass. Model servers like vLLM can take advantage of continuous batching here, so input-heavy workloads are often highly parallelized and relatively efficient per token.

Cached tokens are tokens already computed and available in the GPU's KV cache (the key-value cache vLLM uses to avoid recomputing values for repeated context). vLLM can reuse cached tokens when queries share common system prompts, or in multi-turn conversations where chat history is resent with each request. Cached tokens are generally inexpensive because the value is looked up rather than recomputed on the GPU.

Projects such as llm-d can increase the chance of a KV cache hit in multi-replica deployments through intelligent routing that sends related requests to replicas more likely to already hold the relevant cache, which improves total throughput and can reduce the effective cost when your traffic has shared context.

Output tokens are highly iterative: each token is predicted one at a time. That process generally makes output tokens more expensive in GPU time than input or cached tokens, so output-heavy workloads push the effective cost per token higher for the same headline token count.

Optimizing output tokens with speculative decoding

Why are output tokens so expensive? GPUs must generate them sequentially, one by one. Speculative decoding solves this bottleneck by letting a lightweight draft model guess ahead while the primary model verifies predictions in parallel. Accepted tokens are kept, and rejected ones are regenerated. The result is faster output generation with the same final text, raising the number of useful tokens served per unit of GPU time when verification succeeds often enough.

Final thoughts

Self-hosted LLM pricing is less about a sticker price per million tokens and more about understanding what you spend and how much you serve. Cost per token is operating costs (hardware, software, people, and whatever else you include) divided by tokens processed over the same period. You improve that number by cutting spending through right-sizing and autoscaling, by increasing real-world usage so idle capacity is put to work, or by choosing models and serving techniques that better match your workload.

The most useful takeaway is to measure both sides of the equation. Track actual tokens processed, not just the theoretical maximum throughput, and account for how input, cached, and output tokens behave differently. With that visibility, model choice, quantization, speculative decoding, and routing for cache hits become deliberate levers rather than guesswork, and you can compare self-hosted economics against managed APIs on equal footing.

The post The tokenomics of self-hosted LLMs appeared first on Red Hat Developer.

Read the whole story
alvinashcraft
10 minutes ago
reply
Pennsylvania, USA
Share this story
Delete
Next Page of Stories