<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mikhail Berkov on Medium]]></title>
        <description><![CDATA[Stories by Mikhail Berkov on Medium]]></description>
        <link>https://medium.com/@uhasker?source=rss-ecf95b4b6977------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lUs4NbA2I4sA0DqWt2Ei1A.jpeg</url>
            <title>Stories by Mikhail Berkov on Medium</title>
            <link>https://medium.com/@uhasker?source=rss-ecf95b4b6977------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:08:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@uhasker/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Scaling Self-Hosted AI to 100,000 Messages per Day]]></title>
            <link>https://medium.com/@uhasker/scaling-self-hosted-ai-to-100-000-messages-per-day-5ab271724c83?source=rss-ecf95b4b6977------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ab271724c83</guid>
            <dc:creator><![CDATA[Mikhail Berkov]]></dc:creator>
            <pubDate>Mon, 27 Jul 2026 15:31:27 GMT</pubDate>
            <atom:updated>2026-07-27T16:12:03.050Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Where we explain how AIS.chat serves teachers and students across Germany, and what its architecture teaches us about running LLM infrastructure at scale.</em></p><p>Self-hosting a chatbot for yourself is easy. You spin up a UI, point it at a model API, and you’re done in an afternoon.</p><p>Self-hosting a chatbot for an entire country’s school system is a different problem. Suddenly you have to think about tens of thousands of concurrent users, multi-tenancy, quotas, data protection, provider outages, and the fact that everything happens at exactly 8:15 in the morning.</p><p>In this article, we will look at <a href="https://github.com/FWU-DE/ais-chat">AIS.chat</a> — an open-source platform that does exactly this — and extract the architectural patterns that let a self-hosted AI application scale past <strong>100,000 messages per day</strong>.</p><h3>What is AIS.chat?</h3><p>In January 2025, the <a href="https://de.wikipedia.org/wiki/Institut_f%C3%BCr_Film_und_Bild_in_Wissenschaft_und_Unterricht">Medieninstitut der Länder (FWU)</a> — the media institute jointly owned by Germany’s federal states — commissioned DeutschlandGPT GmbH to provide and operate a central AI platform for teachers and students in Germany. Since May 2026, the resulting application has been operated under the name <a href="https://de.wikipedia.org/wiki/AIS.chat">AIS.chat</a>.</p><p>AIS.chat is a <a href="https://de.wikipedia.org/wiki/White_Label">white-label</a> derivative based on the open-source codebase of DeutschlandGPT. It is available to all teachers and students in Germany, and the chatbot is already in production use in several federal states (Bundesländer).</p><p>Two things make it particularly interesting for our purposes:</p><ol><li><strong>The entire codebase is open source</strong> (AGPL-3.0) at <a href="https://github.com/FWU-DE/ais-chat">github.com/FWU-DE/ais-chat</a>, so we can inspect every architectural decision.</li><li><strong>It runs at real scale, under real constraints</strong> — over <strong>400,000 users in production</strong>, public-sector data protection requirements, multi-tenant operation across federal states, and the brutally spiky traffic patterns of the school day.</li></ol><h3>What Does 100,000 Messages per Day Actually Mean?</h3><p>Let’s do the math first, because the number is less scary — and more scary — than it sounds.</p><p>AIS.chat serves a base of more than 400,000 registered users. Not all of them are active every day, but they collectively generate over 100,000 messages per day — about <strong>1.2 messages per second</strong> on average. Any web framework can handle that.</p><p>With 400,000 users, however, averages are meaningless. What matters is what happens when a meaningful fraction of them shows up at the same time — and in a school system, they do exactly that.</p><p>But school traffic is not average. Almost all usage happens on weekdays between roughly 8:00 and 16:00, with sharp peaks at the start of lessons. Concentrate 100,000 messages into a few busy hours with morning spikes, and you’re suddenly looking at <strong>peak loads of 10–30 messages per second</strong>.</p><p>And here is the part that actually hurts: <strong>an LLM message is not a normal web request.</strong></p><p>A normal API request takes 50 milliseconds. A chat completion streams tokens for 10–60 seconds. At 20 messages per second with an average response time of 20 seconds, you are holding <strong>around 400 concurrent open streaming connections</strong> — each one occupying sockets, memory, and a slot at your model provider.</p><p><strong>The scaling problem of self-hosted AI is therefore not throughput. It is long-lived concurrency.</strong> Every architectural decision below follows from this fact.</p><h3>The Architecture in One Paragraph</h3><p>AIS.chat is a TypeScript monorepo with three deployable applications: a <strong>Next.js chat app</strong> for students and teachers, a <strong>Next.js admin app</strong> for configuration, and a <strong>Fastify proxy API</strong> that sits between the applications and the LLM providers, handling access control and billing. Around them sit two <strong>PostgreSQL</strong> databases, <strong>Valkey</strong> for session storage, an <strong>S3-compatible object store</strong> for file uploads, <strong>Keycloak</strong> for identity, and <strong>Bifrost</strong> as an LLM gateway that routes requests to the actual model providers.</p><p>That’s a lot of boxes. Let’s go through the decisions that matter for scale, one at a time.</p><h3>Principle 1: Keep the Application Layer Stateless</h3><p>The single most important property of the chat app is that <strong>any instance can serve any request</strong>.</p><p>This sounds trivial, but it requires discipline. State constantly tries to sneak into your application servers: user sessions, uploaded files, cached model lists. The moment a request <em>must</em> land on a specific server, horizontal scaling breaks.</p><p>AIS.chat pushes every kind of state out of the application:</p><ul><li><strong>Sessions</strong> live in <a href="https://valkey.io/">Valkey</a> (the open-source Redis fork), not in server memory. The repo even ships a Docker Compose override to test <strong>Valkey in cluster mode</strong>, so the session store itself can scale horizontally too.</li><li><strong>Files</strong> live in S3-compatible object storage (RustFS in the local setup), not on server disks.</li><li><strong>Configuration and chat history</strong> live in PostgreSQL.</li></ul><p>The result: when the 8:15 spike hits, you scale by adding identical containers behind a load balancer. Nothing needs to be warmed up, migrated, or pinned.</p><blockquote><strong><em>Technical Completeness Note:</em></strong><em> Streaming responses still tie a client to one server for the duration of a single response — that’s unavoidable with server-sent events. Statelessness means the </em>next<em> request can go anywhere, which is what matters for load balancing.</em></blockquote><h3>Principle 2: Put a Proxy API Between Users and Models</h3><p>Here is a mistake many self-hosted deployments make: the frontend talks directly to the model provider, with the provider API key baked into the backend configuration.</p><p>This works for one team. It falls apart for one country.</p><p>AIS.chat instead routes everything through its own <strong>proxy API</strong> (a Fastify service, internally called <em>knotenpunkt</em>, German for “node” or “junction”). Every model request passes through it, which gives you a single place to implement:</p><ul><li><strong>Access control</strong> — which tenant may use which model?</li><li><strong>Billing and quotas</strong> — who consumed how many tokens?</li><li><strong>API key management</strong> — each tenant gets its own key to the proxy; provider keys never leave the backend.</li></ul><p>The proxy’s own database schema tells the multi-tenancy story concisely: it manages <strong>organizations, projects, API keys, and LLM models</strong>. In the AIS.chat deployment, a <em>project</em> corresponds to a federal state — Bavaria is DE-BY, and so on. Each federal state gets its own API key, its own model assignments, and its own usage accounting.</p><p><strong>If you remember one thing from this section: your users should authenticate against <em>your</em> API, and only your API should hold provider credentials.</strong> Everything else — quotas, billing, migrations between providers — becomes possible once this indirection exists.</p><h3>Principle 3: Use an LLM Gateway, Because Providers Fail</h3><p>Behind the proxy API sits one more layer: <a href="https://github.com/maximhq/bifrost">Bifrost</a>, an LLM gateway. Model definitions are created in the admin app, and their provider credentials are synced to Bifrost, which performs the actual routing to the upstream providers.</p><p>Why two layers? Because they solve different problems. The proxy API answers “<em>may</em> this request happen, and who pays for it?” The gateway answers “<em>where</em> should this request go, and what happens if that target is down?”</p><p>A gateway gives you the operational features you desperately want at 100,000 messages per day:</p><ul><li><strong>Provider redundancy</strong> — the seed configuration alone references multiple providers (IONOS-hosted models running in German datacenters alongside OpenAI models like GPT-4o mini and GPT-5 nano). If one provider degrades, traffic can move.</li><li><strong>Load distribution</strong> — spread requests across providers or keys instead of hitting one rate limit.</li><li><strong>A uniform interface</strong> — the application speaks one API regardless of which provider serves the tokens.</li></ul><p>For a public education platform, the provider mix is also a compliance instrument: sensitive workloads can be pinned to models hosted in Germany, while other workloads use whatever is most capable or cheapest.</p><p>The clearest example of this is the <a href="https://www.telekom.com/de/medien/medieninformationen/detail/telekom-und-deutschlandgpt-bringen-ki-an-die-schulen-1091576"><strong>BildungsLLM</strong></a> — a language model built by DeutschlandGPT specifically for use in schools and operated by Deutsche Telekom. It is based on the open-source model Llama 3.3 70B, further trained on DeutschlandGPT’s own and synthetic data, optimized for German, and designed for <em>guided learning instead of ready-made answers</em>: it walks students toward a solution rather than simply handing it to them. Guard functionalities check both inputs and outputs against ethical guidelines, safety requirements, and content restrictions.</p><p>Operationally, the BildungsLLM checks every sovereignty box at once: it runs in Deutsche Telekom’s datacenters on the Open Telekom Cloud, all data is processed exclusively in Germany under GDPR, and interactions with the model are not stored, preserving student anonymity. To the AIS.chat stack, it is simply one more provider behind the gateway — which is precisely the payoff of Principle 3: <strong>a didactically specialized, sovereign model can be added, routed to, and scaled without touching a single line of application code.</strong></p><h3>Principle 4: Separate Databases Along Failure Domains</h3><p>AIS.chat deliberately runs <strong>two separate PostgreSQL databases</strong>: one for the chat application (users, conversations, settings) and one for the proxy API (tenants, API keys, models, usage).</p><p>Why not one database? Because the two workloads have completely different profiles. The chat database absorbs high-frequency writes from every active conversation. The API database is small, read-heavy, and absolutely critical — if it goes down, no request can be authorized.</p><p>Separating them means the noisy workload cannot take down the critical one, each can be scaled and backed up on its own schedule, and the proxy API remains an independently deployable service. <strong>Draw your database boundaries where your failure domains are, not where your ORM finds it convenient.</strong></p><h3>Principle 5: You Cannot Scale What You Cannot See</h3><p>Two unglamorous details in the repository reveal how the platform is actually operated:</p><ol><li><strong>A dedicated monitoring stack</strong> — the Docker setup ships an observability configuration built on <strong>OpenTelemetry</strong> and <strong>Jaeger</strong> for distributed tracing. When a student’s message travels through the chat app, the proxy API, the gateway, and a provider, tracing tells you <em>which</em> hop added the latency.</li><li><strong>Load tests as a first-class citizen</strong> — the project uses <a href="https://grafana.com/docs/k6/latest/">k6</a> for load testing. At this scale you don’t discover your limits in production on a Monday morning; you discover them in a load test on a Thursday afternoon.</li></ol><p>Neither of these features will ever appear in a product screenshot. Both are the difference between “scales in theory” and “scales during the first period of class.”</p><h3>Putting It All Together</h3><p><strong>To sum it up — here is how a message flows through a self-hosted AI platform at scale:</strong></p><p><strong>A student sends a message to one of many identical, stateless chat app instances (session in Valkey, files in S3). The app calls the proxy API with the tenant’s API key, where access is checked and usage is recorded. The proxy forwards the request to the Bifrost gateway, which routes it to a healthy model provider. Tokens stream back through the same path, and OpenTelemetry traces the whole journey.</strong></p><p>None of the individual pieces are exotic. That is exactly the point. Scaling self-hosted AI to 100,000 messages per day is not about a secret trick — it is about statelessness, indirection through a proxy, provider redundancy, sensible failure domains, and observability, applied consistently.</p><p>And because AIS.chat is open source, you don’t have to take any of this on faith. Clone <a href="https://github.com/FWU-DE/ais-chat">the repository</a>, run docker compose -f devops/docker/docker-compose.yml up -d, and you have the entire stack — Keycloak, both databases, Valkey, object storage, proxy and gateway — running locally in a few minutes.</p><p>In a future article, we will go one level deeper and look at how multi-tenancy is modeled in the database and what a k6 load test for streaming LLM traffic looks like in practice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ab271724c83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embedding Similarity Explained: How to Measure Text Semantics]]></title>
            <link>https://medium.com/thinking-sand/embedding-similarity-explained-how-to-measure-text-semantics-2932a0d899c9?source=rss-ecf95b4b6977------2</link>
            <guid isPermaLink="false">https://medium.com/p/2932a0d899c9</guid>
            <category><![CDATA[vector-embeddings]]></category>
            <category><![CDATA[dot-product]]></category>
            <category><![CDATA[semantic-search]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[cosine-similarity]]></category>
            <dc:creator><![CDATA[Mikhail Berkov]]></dc:creator>
            <pubDate>Fri, 08 Aug 2025 09:28:12 GMT</pubDate>
            <atom:updated>2025-08-11T20:22:43.274Z</atom:updated>
            <content:encoded><![CDATA[<p>Embedding similarity is the backbone of modern AI applications that understand meaning rather than just matching words. By representing text as vectors, it allows you to measure how semantically close two pieces of content are — even when they share no common terms. This powerful capability enables more accurate search, smarter recommendations, and deeper insights from your data.</p><h3>What are Embeddings?</h3><p>Embeddings are a way to represent text as a semantically meaningful vector of numbers. The core idea is that if two texts are similar, then their vector representations should be similar as well.</p><p>For example, the embeddings of “I love programming in Python” and “I like coding in a language whose symbol is a snake” should be similar despite the fact that the texts have practically no words in common. This is called <strong>semantic similarity</strong> as opposed to syntactic similarity which is about the similarity of the sentence structure and the words used.</p><p>Depending on the use case, you can embed words, sentences, paragraphs, or even entire documents.</p><p>The concept of embeddings — and their similarities — is useful for many applications:</p><ul><li><strong>Semantic search</strong>: You can use embeddings to find the most similar texts to a given query</li><li><strong>Clustering</strong>: You can use embeddings to cluster texts into different groups based on their semantic similarity</li><li><strong>Recommendation systems</strong>: You can use embeddings to recommend similar items to a given item</li></ul><p>Later, we’ll also explore how to use embeddings to build RAG pipelines that enhance the quality of your LLM applications.</p><p>So how are embeddings generated? Interestingly, large language models (LLMs) can produce them as a byproduct of their architecture.</p><p>After the tokenizer has converted the text into tokens, a so-called embedding layer transforms every token into a high-dimensional vector. These vectors are continuously refined through the transformer layers until an “unembedding layer” produces the final output — the logits over the vocabulary. Since an LLM is trained to predict the next token, its embedding layer automatically learns to represent tokens in a semantically meaningful way.</p><p>Alternatively, you can use specialized embedding models trained specifically to produce high-quality embeddings.</p><p>OpenAI provides a range of embedding models, the most important of which are the text-embedding-3-small and text-embedding-3-large models.</p><p>You can use them like this:</p><pre>import os, requests<br><br>response = requests.post(<br>    &quot;https://api.openai.com/v1/embeddings&quot;,<br>    headers={<br>        &quot;Authorization&quot;: f&quot;Bearer {os.getenv(&#39;OPENAI_API_KEY&#39;)}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    },<br>    json={<br>        &quot;input&quot;: &quot;Your text string goes here&quot;,<br>        &quot;model&quot;: &quot;text-embedding-3-small&quot;<br>    }<br>)<br><br>response_json = response.json()<br>embedding = response_json[&quot;data&quot;][0][&quot;embedding&quot;]<br>print(embedding[:5])<br>print(len(embedding))</pre><p>This will output something along the lines of:</p><pre>[0.005132983, 0.017242905, -0.018698474, -0.018558515, -0.047250036]<br>1536</pre><p>Note that embeddings are typically high-dimensional.</p><p>For example, the text-embedding-3-small model produces 1536-dimensional embeddings while the text-embedding-3-large model produces 3072-dimensional embeddings.</p><p>In general, higher-dimensional embeddings capture more nuanced relationships but can be slower to compute and more memory-intensive to store.</p><h3>Embedding Similarity</h3><p>Remember, the core idea behind embeddings is that semantically similar texts should have similar vector representations. But how can we actually calculate the similarity between two embeddings?</p><p>Embeddings are vectors, and vector similarity is commonly measured using <strong>cosine similarity</strong>, defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*f1oST2EiEgOOpOr_PWRLpg.png" /></figure><p>where θ is the angle between the vectors v and w, v * w is the dot product of the vectors and ||v|| and ||w|| are their norms.</p><p>As a reminder, the dot product (also called the inner product) of two vectors is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*quC_i1b0ObFojzaZhQK8MA.png" /></figure><p>And the norm of a vector is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*R-JSXnXb_HozYN_jEaGCQQ.png" /></figure><p>The cosine similarity is:</p><ul><li>equal to 1 if the vectors have the same direction,</li><li>equal to 0 if the vectors are orthogonal,</li><li>equal to -1 if the vectors have opposite directions.</li></ul><p>Generally speaking, the closer the cosine similarity is to 1, the more similar the vectors are. The closer it is to -1, the more dissimilar they are.</p><p>Here is an example implementation of cosine similarity:</p><pre>def get_norm(v):<br>  return math.sqrt(sum(x ** 2 for x in v))<br><br>def get_dot_product(v, w):<br>  return sum(v[i] * w[i] for i in range(len(v)))<br><br>def get_cosine_similarity(v, w):<br>  return get_dot_product(v, w) / (get_norm(v) * get_norm(w))<br><br>v = [1, 0]<br>w = [1, 1]<br><br>print(get_norm(v)) # 1.0<br>print(get_norm(w)) # 1.41...<br>print(get_dot_product(v, w)) # 1<br>print(get_cosine_similarity(v, w)) # 0.707...</pre><p>This is how the cosine similarity between the two vectors looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCvoWFqMavcqpKGW-W30SQ.png" /></figure><p>Note that you typically shouldn’t use plain Python implementations for mathematical operations like norms or dot products.</p><p>Instead, rely on libraries like NumPy or SciPy because the latter will <strong>vectorize</strong> the operations which is much more efficient than using regular Python loops.</p><p>Developers often use the dot product — or even Euclidean distance — to measure similarity instead of the cosine similarity. This works because embeddings are usually normalized to unit length.</p><p>Let’s verify that this is true for the embeddings produced by OpenAI:</p><pre>import math<br><br>def get_norm(embedding):<br>    return math.sqrt(sum(x ** 2 for x in embedding))<br><br># Here embedding is some embedding from OpenAI (for example, you can use the embedding from the previous section)<br>print(get_norm(embedding)) # 1.0</pre><p>If two embeddings are normalized to unit length — that is, their norms are 1 — their cosine similarity is equal to their dot product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*CdeI-UIhARXClpxdDAQVxQ.png" /></figure><p>Similarly, the Euclidean distance of two unit-length vectors becomes a monotonic transformation of the cosine similarity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*3OIq4X465XlGZFAUWX1kVg.png" /></figure><p>Therefore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*lnw5Zc3qUDdbsAzZnFbjow.png" /></figure><p>This means that for unit-length embeddings, ranking by cosine similarity is equivalent to ranking by dot product or Euclidean distance. However, this equivalence holds only for unit-length vectors.</p><p>Therefore, when using similarities other than the cosine similarity, you should always verify that the embeddings produced by the embedding model you are using are normalized to unit length.</p><p><em>If you found this helpful, give it a few 👏 (you can hit up to 50!) and tap </em><strong><em>Subscribe</em></strong><em> to get more insights in your feed.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2932a0d899c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thinking-sand/embedding-similarity-explained-how-to-measure-text-semantics-2932a0d899c9">Embedding Similarity Explained: How to Measure Text Semantics</a> was originally published in <a href="https://medium.com/thinking-sand">Thinking Sand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The top_k and top_p Parameters Explained]]></title>
            <link>https://medium.com/thinking-sand/the-top-k-and-top-p-parameters-explained-bfaecc8cd342?source=rss-ecf95b4b6977------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfaecc8cd342</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[openai-api]]></category>
            <category><![CDATA[sampling]]></category>
            <category><![CDATA[probability-distributions]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Mikhail Berkov]]></dc:creator>
            <pubDate>Thu, 07 Aug 2025 18:58:59 GMT</pubDate>
            <atom:updated>2025-08-08T09:28:28.662Z</atom:updated>
            <content:encoded><![CDATA[<p>When generating text with AI, controlling randomness is key to balancing creativity and coherence. This article explains <strong>top-k</strong> and <strong>top-p</strong> (nucleus) sampling — two popular techniques that shape output quality and diversity. With clear Python examples and tuning tips, you’ll learn how to apply these methods to get results that match your goals.</p><h3>Top-k Sampling</h3><p>So far, we have covered <a href="https://medium.com/thinking-sand/llm-sampling-explained-selecting-the-next-token-b897b5984833">greedy sampling and probabilistic sampling</a>.</p><p>Greedy sampling is deterministic and always picks the most likely token. Probabilistic sampling is non-deterministic and picks a token from the distribution potentially adjusted by the temperature parameter.</p><p>Sometimes, we want a middle ground: sampling probabilistically while constraining the selection to avoid low-quality tokens.</p><p>In <strong>top-k sampling</strong>, we consider only the top k most probable tokens and then sample from this restricted set:</p><pre>import random<br><br>def sample_top_k(probabilities, k):<br>    top_k_probabilities = sorted(probabilities, key=lambda item: item[&quot;prob&quot;], reverse=True)[:k]<br>    return random.choices(top_k_probabilities, weights=[item[&quot;prob&quot;] for item in top_k_probabilities], k=1)[0]</pre><p>Let’s use this function in a simple example:</p><pre>from collections import defaultdict<br><br>probabilities = [<br>    {&quot;token&quot;: &quot;Apple&quot;, &quot;prob&quot;: 0.5},<br>    {&quot;token&quot;: &quot;Banana&quot;, &quot;prob&quot;: 0.3},<br>    {&quot;token&quot;: &quot;Cherry&quot;, &quot;prob&quot;: 0.1},<br>    {&quot;token&quot;: &quot;Durian&quot;, &quot;prob&quot;: 0.05},<br>    {&quot;token&quot;: &quot;Elderberry&quot;, &quot;prob&quot;: 0.05},<br>]<br><br>counts = defaultdict(int)<br>for _ in range(1000):<br>    counts[sample_top_k(probabilities, k=3)[&quot;token&quot;]] += 1<br><br>print(counts)</pre><p>This will output something like:</p><pre>{&#39;Cherry&#39;: 110, &#39;Banana&#39;: 312, &#39;Apple&#39;: 578}</pre><p>Note that we only select from the top 3 tokens — everything else is ignored.</p><p>The parameter k is a hyperparameter that you can tune for your task. The higher k is, the more diverse the output will be.</p><h3>Top-p Sampling</h3><p>Top-k sampling is a simple and effective way to limit the tokens considered. However, since k is fixed, it can be problematic: in some cases, the top k tokens may capture 99% of the probability mass, while in others, only 30%.</p><p>To address this, we can use <strong>top-p sampling</strong> (also known as nucleus sampling).</p><p>In top-p sampling, we include just enough tokens to capture a certain probability mass p. We then sample from this set:</p><pre>import random<br><br>def sample_top_p(probabilities, p):<br>    sorted_probabilities = sorted(probabilities, key=lambda item: item[&quot;prob&quot;], reverse=True)<br><br>    top_p_probabilities = []<br>    cumulative_prob = 0<br><br>    for item in sorted_probabilities:<br>        top_p_probabilities.append(item)<br>        cumulative_prob += item[&quot;prob&quot;]<br>        if cumulative_prob &gt;= p:<br>            break<br><br>    return random.choices(top_p_probabilities, weights=[item[&quot;prob&quot;] for item in top_p_probabilities], k=1)[0]</pre><p>Let’s use this function in a simple example:</p><pre>from collections import defaultdict<br><br>logprobs = [<br>    {&quot;token&quot;: &quot;Apple&quot;, &quot;prob&quot;: 0.5},<br>    {&quot;token&quot;: &quot;Banana&quot;, &quot;prob&quot;: 0.3},<br>    {&quot;token&quot;: &quot;Cherry&quot;, &quot;prob&quot;: 0.1},<br>    {&quot;token&quot;: &quot;Durian&quot;, &quot;prob&quot;: 0.05},<br>    {&quot;token&quot;: &quot;Elderberry&quot;, &quot;prob&quot;: 0.05},<br>]<br><br>counts = defaultdict(int)<br>for _ in range(1000):<br>    counts[sample_top_p(logprobs, p=0.9)[&quot;token&quot;]] += 1<br><br>print(counts)</pre><p>Here, we include all tokens whose cumulative probability meets or exceeds p=0.9. This means that the tokens “Apple”, “Banana” and “Cherry” are included, while “Durian” and “Elderberry” are not.</p><p>We can see this in the output:</p><pre>{&#39;Banana&#39;: 356, &#39;Apple&#39;: 531, &#39;Cherry&#39;: 113}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWubwlvBkcCgBEkXgvPg3g.png" /></figure><p>Let’s what happens if we set p=0.8:</p><pre>counts = defaultdict(int)<br>for _ in range(1000):<br>    counts[sample_top_p(logprobs, p=0.8)[&quot;token&quot;]] += 1<br><br>print(counts)</pre><p>This will output something like:</p><pre>{&#39;Apple&#39;: 624, &#39;Banana&#39;: 376}</pre><p>In this case, only the “Apple” and “Banana” tokens are sampled because their cumulative probability is already p=0.8.</p><p>As with k, p is a tunable hyperparameter. The higher p is, the more diverse the output will be.</p><p>In practice, top-p sampling is often preferred over top-k because it’s adaptive — it dynamically includes enough high-probability tokens to capture most of the probability mass.</p><p>You can specify the value of p using the top_p parameter in the OpenAI API:</p><pre>import os, requests<br><br>response = requests.post(<br>    &quot;https://api.openai.com/v1/chat/completions&quot;,<br>    headers={<br>        &quot;Authorization&quot;: f&quot;Bearer {os.getenv(&#39;OPENAI_API_KEY&#39;)}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    },<br>    json={<br>        &quot;model&quot;: &quot;gpt-4o&quot;,<br>        &quot;messages&quot;: [<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;How are you?&quot;}<br>        ],<br>        &quot;top_p&quot;: 0.9<br>    }<br>)<br><br>response_json = response.json()<br>content = response_json[&quot;choices&quot;][0][&quot;message&quot;][&quot;content&quot;]<br>print(content)</pre><p>It is generally recommended to specify either the temperature or the top_p parameter, but not both.</p><p><em>If you found this helpful, give it a few 👏 (you can hit up to 50!) and tap </em><strong><em>Subscribe</em></strong><em> to get more insights in your feed.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfaecc8cd342" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thinking-sand/the-top-k-and-top-p-parameters-explained-bfaecc8cd342">The top_k and top_p Parameters Explained</a> was originally published in <a href="https://medium.com/thinking-sand">Thinking Sand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering LLM Temperature: A Step-by-Step Guide]]></title>
            <link>https://medium.com/thinking-sand/mastering-llm-temperature-a-step-by-step-guide-81e9f27fef77?source=rss-ecf95b4b6977------2</link>
            <guid isPermaLink="false">https://medium.com/p/81e9f27fef77</guid>
            <category><![CDATA[llm-temperature]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[temperature]]></category>
            <category><![CDATA[logprobs]]></category>
            <category><![CDATA[probability-distributions]]></category>
            <dc:creator><![CDATA[Mikhail Berkov]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 16:05:11 GMT</pubDate>
            <atom:updated>2025-08-06T16:14:49.761Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding how the temperature parameter works is key to controlling the balance between creativity and reliability in language model outputs. This article explains how temperature reshapes probability distributions, what effect different values have, and how to choose the right setting for your use case — with clear examples, math, and code to guide you.</p><h3>The Temperature Parameter</h3><p>The <strong>temperature</strong> parameter plays a key role in probabilistic sampling. It controls the randomness of the output: higher temperatures lead to more varied, random responses, while lower temperatures make the model behave more deterministically.</p><p>Conceptually, temperature reshapes the probability distribution from which we sample. Instead of sampling directly from the raw probabilities generated by the model, we adjust them — either concentrating more heavily on high-probability tokens (low temperature) or flattening the distribution to give low-probability tokens a better chance (high temperature).</p><p>The actual formula looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*rED0NLNXDaMyr2EgEwWYpw.png" /></figure><p>where:</p><ul><li>P(x_i) is the raw probability of the token $x_i$ as produced by the model,</li><li>T is the temperature,</li><li>n is the total number of tokens and</li><li>Q(x_i) is the adjusted probability of the token x_i</li></ul><p>In Python, we can implement this as:</p><pre>def apply_temperature(probs, temperature):<br>    sum_denominator = sum(prob ** (1 / temperature) for prob in probs)<br>    return [prob ** (1 / temperature) / sum_denominator for prob in probs]</pre><p>Before diving into the math, let’s look at a simple example:</p><pre>def round_probs(probs):<br>    return [round(prob, 2) for prob in probs]<br><br>probs = [0.6, 0.3, 0.1]<br>print(round_probs(apply_temperature(probs, 0.1))) # [1.0, 0.0, 0.0]<br>print(round_probs(apply_temperature(probs, 0.5))) # [0.78, 0.2, 0.02]<br>print(round_probs(apply_temperature(probs, 1))) # [0.6, 0.3, 0.1]<br>print(round_probs(apply_temperature(probs, 2))) # [0.47, 0.33, 0.19]</pre><p>Here’s what we observe:</p><ul><li>A temperature of 1 leaves the probabilities unchanged.</li><li>Temperatures below 1 make the distribution more peaked — concentrating on the most likely tokens.</li><li>Temperatures above 1 make the distribution flatter — spreading out probability mass across more tokens.</li></ul><p>Importantly, the relative ranking of tokens remains unchanged — only the probabilities are rescaled.</p><p>This makes sense when we look back at the formula. For T = 1, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*jWeUnpXiwFWba3Z0T2r2vA.png" /></figure><p>Therefore, applying a temperature of T = 1 leaves the probabilities unchanged.</p><p>For T &lt; 1, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*Svp4pu2KdEsBGLMhi1dbbg.png" /></figure><p>where S = 1 / T &gt; 1.</p><p>Therefore, each probability is raised to a power greater than 1. This disproportionately suppresses lower-probability values.</p><p>For example, 0.9 ** 10 is approximately 0.35 while 0.1 ** 10 is approximately 1e-10 meaning that the smaller probability is effectively eliminated from the distribution.</p><p>The opposite is true for T &gt; 1. Here we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*Svp4pu2KdEsBGLMhi1dbbg.png" /></figure><p>where S = 1 / T &lt; 1.</p><p>In this scenario, every probability will be raised to a power smaller than 1. This boosts the lower values relative to the higher ones.</p><p>For example, 0.9 ** 10 is approximately 0.99 while 0.1 ** 0.1 is approximately 0.8 meaning that the smaller probability gets much more weight in the distribution than before.</p><p>With the math out of the way, here’s the key takeaway:</p><ul><li>A temperature of 1 leaves the probabilities unchanged.</li><li>A temperature smaller than 1 makes the probabilities more concentrated on the most likely tokens leading to more deterministic output.</li><li>A temperature larger than 1 makes the probabilities more uniform leading to more random output.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mlPozLlKhpayaA4T-Csaug.png" /></figure><p>In practice, we use log probabilities rather than raw probabilities, primarily for numerical stability. So, instead of rescaling the probabilities, we rescale the log probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*Dlq1jHcjYUCHM8SgcW5O7g.png" /></figure><p>This is equivalent to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*syokxofFNBp6G_WBs_ufSA.png" /></figure><p>Letting z_i = log(P(x_i)) we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*NaqTkFQ3OT1sXqCkzjWWNg.png" /></figure><p>This is the formulation of the temperature parameter you will see most often in the literature.</p><p>We can implement this in Python as follows:</p><pre>def apply_temperature(logprobs, temperature):<br>    sum_denominator = sum(math.exp(logprob / temperature) for logprob in logprobs)<br>    return [math.exp(logprob / temperature) / sum_denominator for logprob in logprobs]</pre><p>Let’s use this function in a simple example:</p><pre>logprobs = [math.log(0.6), math.log(0.3), math.log(0.1)]<br>print(round_probs(apply_temperature(logprobs, 0.1))) # [1.0, 0.0, 0.0]<br>print(round_probs(apply_temperature(logprobs, 0.5))) # [0.78, 0.2, 0.02]<br>print(round_probs(apply_temperature(logprobs, 1))) # [0.6, 0.3, 0.1]<br>print(round_probs(apply_temperature(logprobs, 2))) # [0.47, 0.33, 0.19]</pre><p>The results are the same as before.</p><p>So, how should you choose the optimal temperature? Once again, it depends on the task — and there’s little rigorous research on how to choose the “best” temperature.</p><p>Even OpenAI doesn’t offer a definitive recommendation. To quote from the <a href="https://arxiv.org/pdf/2303.08774">GPT-4 technical report</a>:</p><blockquote>Due to the longer iteration time of human expert grading, we did no methodology iteration on temperature or prompt, instead we simply ran these free response questions each only a single time at our best-guess temperature (0.6) and prompt.</blockquote><p>As of the time of this writing, the OpenAI API defaults to a temperature of 1. In actual applications, people often use values of 0.4 or 0.7, but this isn’t really backed by any theory either.</p><p>Generally speaking, some people say that:</p><ul><li>lower temperatures (T &lt;= 0.7) are suitable for tasks requiring precision and reliability, e.g. factual question answering</li><li>moderate temperatures (0.7 &lt; T &lt;= 1) are suitable for general-purpose conversations where you need reliability but also some degree of creativity, e.g. for a chat bot</li><li>higher temperatures (T &gt; 1) are suitable for creative endeavors, e.g. for storytelling or brainstorming</li></ul><p>Again, this has practically no rigorous theoretical basis and seems to just be something application developers have empirically converged on. So take these values with a grain of salt — or rather, a full salt mill. In real-world scenarios, you will have to experiment with different temperatures to find the one that works best for your task.</p><p>An interesting edge case is T = 0. Technically, this is undefined because we divide by zero in the formula. Usually, this edge case is treated as roughly equivalent to greedy sampling and models will try to pick the most likely token. This aligns with the general intuition: lower temperatures yield more deterministic outputs.</p><p>Note that the OpenAI API will not return fully deterministic results even for T = 0. The reasons for this are complicated and beyond the scope of this book.</p><p><em>If you found this helpful, give it a few 👏 (you can hit up to 50!) and tap </em><strong><em>Subscribe</em></strong><em> to get more insights in your feed.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81e9f27fef77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thinking-sand/mastering-llm-temperature-a-step-by-step-guide-81e9f27fef77">Mastering LLM Temperature: A Step-by-Step Guide</a> was originally published in <a href="https://medium.com/thinking-sand">Thinking Sand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Sampling Explained: Selecting the Next Token]]></title>
            <link>https://medium.com/thinking-sand/llm-sampling-explained-selecting-the-next-token-b897b5984833?source=rss-ecf95b4b6977------2</link>
            <guid isPermaLink="false">https://medium.com/p/b897b5984833</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[sampling]]></category>
            <category><![CDATA[logprobs]]></category>
            <category><![CDATA[greedy-algorithms]]></category>
            <category><![CDATA[llm-sampling]]></category>
            <dc:creator><![CDATA[Mikhail Berkov]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 16:38:18 GMT</pubDate>
            <atom:updated>2025-08-05T16:38:18.611Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding how LLMs decide what to say next can help you write better prompts and interpret model behavior when generating text. This article breaks down how models assign probabilities to possible next tokens, what log probabilities are, and how the basic sampling methods (greedy vs. probabilistic sampling) work in practice.</p><h3>A List of Probabilities</h3><p>We have already <a href="https://medium.com/thinking-sand/what-is-llm-tokenization-and-why-is-it-important-4eb5fbefb075">learned</a> that LLMs generate text one token at a time. So, how does the model decide which token to generate next?</p><p>Behind the scenes, the LLM produces a list of all possible next tokens, each paired with its probability. For example, given the input “How are you? I am “, the model might produce a list like this:</p><ul><li>fine paired with probability 0.7</li><li>good paired with probability 0.2</li><li>bad paired with probability 0.1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tpxxbuClMYyhawie6meqg.png" /></figure><p>Because the list includes every token in the model’s vocabulary, it tends to be quite large.</p><p>Technically, the list contains <strong>log probabilities</strong> — that is, the logarithms of the actual probabilities. This approach is more numerically stable than working with raw probabilities. To convert a log probability back to a probability, you simply exponentiate it:</p><pre>import math<br><br>original_prob = 0.7<br>logprob = math.log(original_prob)<br>prob = math.exp(logprob)<br><br>print(f&quot;Original probability: {original_prob}&quot;)<br>print(f&quot;Log probability: {logprob}&quot;)<br>print(f&quot;Reconstructed probability: {prob}&quot;)</pre><p>This will output:</p><pre>Original probability: 0.7<br>Log probability: -0.35667494393873245<br>Reconstructed probability: 0.7</pre><p>The OpenAI API lets you retrieve the top log probabilities for the next token, given a prompt:</p><pre>import math<br>import os, requests<br><br>response = requests.post(<br>    &quot;https://api.openai.com/v1/chat/completions&quot;,<br>    headers={<br>        &quot;Authorization&quot;: f&quot;Bearer {os.getenv(&#39;OPENAI_API_KEY&#39;)}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    },<br>    json={<br>        &quot;model&quot;: &quot;gpt-4o&quot;,<br>        &quot;messages&quot;: [<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;How are you?&quot;}<br>        ],<br>        &quot;logprobs&quot;: True,<br>        &quot;top_logprobs&quot;: 5<br>    }<br>)<br><br>response_json = response.json()<br>logprobs = response_json[&quot;choices&quot;][0][&quot;logprobs&quot;]<br>next_token_logprobs = logprobs[&quot;content&quot;][0][&quot;top_logprobs&quot;]<br><br>for item in next_token_logprobs:<br>    token, logprob = item[&quot;token&quot;], item[&quot;logprob&quot;]<br>    prob = math.exp(logprob)<br>    print(token, prob)</pre><p>This will output something along the lines of:</p><pre>Thank 0.903825743563041<br>I&#39;m 0.09526252257393902<br>I 0.0004998919591426934<br>Thanks 0.0003893162492314283<br>Hello 1.9382905474713714e-05</pre><p>This means the model predicts Thank as the next token with a probability of 0.90, I&#39;m with 0.09, and so on.</p><h3>Sampling from the List</h3><p>Now that we have a list of probabilities, how do we use it to generate the next token?</p><p>The simplest approach is to use <strong>greedy sampling</strong>. This simply means selecting the token with the highest probability:</p><pre>def greedy_sample(logprobs):<br>    return max(logprobs, key=lambda item: item[&quot;prob&quot;])<br><br>next_token_logprobs = [<br>    {&quot;token&quot;: &quot;Apple&quot;, &quot;prob&quot;: 0.6},<br>    {&quot;token&quot;: &quot;Banana&quot;, &quot;prob&quot;: 0.3},<br>    {&quot;token&quot;: &quot;Cherry&quot;, &quot;prob&quot;: 0.1},<br>]<br>print(greedy_sample(next_token_logprobs))</pre><p>This will output:</p><pre>{&#39;token&#39;: &#39;Apple&#39;, &#39;prob&#39;: 0.6}</pre><p>Another approach is to actually sample from the list. This involves randomly selecting a token from the list, with each token weighted by its probability. The higher the probability, the more likely the token will be selected.</p><pre>import random<br>from collections import defaultdict<br><br>def sample_from_list(logprobs):<br>    return random.choices(logprobs, weights=[item[&quot;prob&quot;] for item in logprobs], k=1)[0]<br><br>next_token_logprobs = [<br>    {&quot;token&quot;: &quot;Apple&quot;, &quot;prob&quot;: 0.6},<br>    {&quot;token&quot;: &quot;Banana&quot;, &quot;prob&quot;: 0.3},<br>    {&quot;token&quot;: &quot;Cherry&quot;, &quot;prob&quot;: 0.1},<br>]<br><br>counts = defaultdict(int)<br>for _ in range(1000):<br>    counts[sample_from_list(next_token_logprobs)[&quot;token&quot;]] += 1<br><br>print(counts)</pre><p>This will output something along the lines of:</p><pre>{&#39;Apple&#39;: 598, &#39;Banana&#39;: 303, &#39;Cherry&#39;: 99}</pre><p>Note how the counts of every token are roughly proportional to their probabilities.</p><p>Greedy sampling has a few clear advantages: it’s simple, fast, and fully deterministic. Nevertheless, it comes with a downside: it always selects the most likely token — even when that token’s probability is relatively low. As a result, greedy sampling is often associated with repetitive output.</p><p>This concern was highlighted in the famous paper <a href="https://arxiv.org/pdf/1904.09751">The Curious Case of Neural Text Degeneration</a> which shows that greedy sampling — and its close relative, beam search — often leads to repetitive text. However, that study focused on GPT-2, a model that is outdated by today’s standards.</p><p>More recent research paints a more nuanced picture. For instance, <a href="https://arxiv.org/pdf/2407.10457">The Good, The Bad, and The Greedy: Evaluation of LLMs Should Not Ignore Non-Determinism</a> found that greedy sampling actually outperformed more complex methods in some cases. Similarly, <a href="https://arxiv.org/pdf/2402.06925">A Thorough Examination of Decoding Methods in the Era of LLMs</a> argues that no single sampling method is the best — it all depends on the task at hand. In practice, that does seem to hold true.</p><p>In short, while probabilistic sampling is typically the default, greedy sampling can be a reasonable — and at times even preferable — alternative.</p><p>The discussion around greedy sampling and probabilistic sampling highlights just how shaky the foundations of LLMs are and how quickly the field moves. We still lack a definitive answer to something as basic as the best sampling method — let alone more complex questions.</p><p><em>If you found this helpful, give it a few 👏 (you can hit up to 50!) and tap </em><strong><em>Subscribe</em></strong><em> to get more insights in your feed.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b897b5984833" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thinking-sand/llm-sampling-explained-selecting-the-next-token-b897b5984833">LLM Sampling Explained: Selecting the Next Token</a> was originally published in <a href="https://medium.com/thinking-sand">Thinking Sand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is LLM Tokenization and Why Is It Important?]]></title>
            <link>https://medium.com/thinking-sand/what-is-llm-tokenization-and-why-is-it-important-4eb5fbefb075?source=rss-ecf95b4b6977------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eb5fbefb075</guid>
            <category><![CDATA[llm-tokenization]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[context-window]]></category>
            <category><![CDATA[token-price]]></category>
            <category><![CDATA[llm-tokens]]></category>
            <dc:creator><![CDATA[Mikhail Berkov]]></dc:creator>
            <pubDate>Mon, 04 Aug 2025 14:49:17 GMT</pubDate>
            <atom:updated>2025-08-05T16:30:17.633Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding tokenization is essential for anyone working with large language models (LLMs). It helps you <strong>control model behavior</strong>, <strong>optimize costs</strong>, and <strong>avoid hitting hard limits like the context window</strong>. Whether you’re building an app or just experimenting, knowing how tokens work lets you craft better prompts, estimate usage accurately, and debug unexpected output more easily.</p><h3>LLMs Generate Text By Generating Tokens</h3><p>LLMs take text as input and produce text as output. However, they don’t process text the way we do — not as characters or words. Instead, they work with more general units called <strong>tokens</strong>.</p><p>A <strong>token</strong> is the basic unit of text that an LLM can process. Whenever you feed text into an LLM, it’s first split into tokens. Tokens can be single characters, whole words, or even subword fragments.</p><p>For example, the sentence “Hello, world” might be split into the tokens &#39;Hello&#39;, &#39;,&#39;, &#39; &#39;, &#39;wo&#39;, &#39;rl&#39;, &#39;d&#39;. The token &#39;Hello&#39; is a single word, the tokens &#39;wo&#39; and &#39;rl&#39; are subword fragments, and the tokens &#39;,&#39; and &#39; &#39; are single characters. All of these are valid tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azEBazNPxVFHvJi-0a2H-Q.png" /></figure><p>The set of all tokens available to an LLM is called the <strong>vocabulary</strong>. Usually, the vocabulary of a modern LLM is very large, containing tens of thousands of tokens.</p><p>Now, here is the key point: <strong>LLMs generate text one token at a time.</strong></p><p>When you feed text into an LLM, it’s first split into tokens. The model generates one token at a time, each based on the input plus all previously generated tokens. This continues until it produces a special token called the <strong>end-of-sequence token</strong>, or reaches a predefined limit.</p><p>Consider the input text “How are you?”.</p><p>The model first splits the text into tokens: &#39;How&#39;, &#39; &#39;, &#39;are&#39;, &#39; &#39;, &#39;you&#39;, &#39;?&#39;.</p><p>It then begins generating one token at a time.</p><p>The first token might be &#39;I&#39;, producing a new input text: “How are you? I”</p><p>Next, it generates &#39; am&#39;, resulting in: “How are you? I am”</p><p>Then comes &#39; fine&#39;: “How are you? I am fine”</p><p>Followed by &#39;.&#39;: “How are you? I am fine.”</p><p>Finally, it may generate the special <strong>end-of-sequence token</strong>, signaling that it’s done.</p><p>The final output text is “How are you? I am fine.” Usually, the end-of-sequence token is not included in the output text.</p><h3>The Tokenizer</h3><p>The <strong>tokenizer</strong> is the LLM component that splits text into tokens and makes them digestible by the model. Different LLMs use different tokenizers and not all of them split text the same way. Tokenizers are usually trained on a large corpus of text and learn to split it in ways that are most useful for the model.</p><p>For example, the GPT models from OpenAI use a <strong>byte-pair encoding (BPE)</strong> tokenizer. BPE starts with a vocabulary containing single characters and progressively merges the most frequent pairs of existing tokens to form new tokens. The tokenizer might start with the vocabulary containing all the characters in the alphabet. It might notice that ‘t’ and ‘h’ often appear together and merge them into ‘th’. Later, it may merge ‘th’ and ‘e’ into ‘the’. This continues until a certain number of tokens is reached.</p><p>We can use the <em>tiktoken</em> library to see the tokens that a given LLM uses.</p><blockquote>If you don’t want to go through the hassle of installing the library, you can also go to <a href="https://platform.openai.com/tokenizer">https://platform.openai.com/tokenizer</a> and paste your text there.</blockquote><p>First, we need to install the library:</p><pre>pip install tiktoken</pre><p>Then, we can use the library to get the tokens for a given model:</p><pre>import tiktoken<br><br># Get the tokenizer for the GPT-4o model<br>enc = tiktoken.encoding_for_model(&quot;gpt-4o&quot;)<br><br># Encode a string into tokens<br>tokens = enc.encode(&quot;Hello, world&quot;)<br>print(tokens) # [13225, 11, 2375]</pre><p>Interestingly enough, the tokens printed by the <em>tiktoken</em> library are integers, not strings. This is because LLMs are neural networks that operate on numbers instead of text. Therefore, the tokenizer not only splits the text into tokens, but also assigns a unique integer to each token called a <strong>token ID</strong>.</p><p>For example, the gpt-4o tokenizer assigns the token ID 13225 to the token &#39;Hello&#39;, 11 to the token &#39;,&#39;, and 2375 to the token &#39; world&#39;.</p><p>We can decode each token back into a string using the decode_single_token_bytes method:</p><pre>decoded_text = enc.decode_single_token_bytes(13225)<br>print(decoded_text) # b&#39;Hello&#39;<br><br>decoded_text = enc.decode_single_token_bytes(11)<br>print(decoded_text) # b&#39;,&#39;<br><br>decoded_text = enc.decode_single_token_bytes(2375)<br>print(decoded_text) # b&#39; world&#39;</pre><p>Notice that the last token isn’t &#39;world&#39;, but &#39; world&#39; — with a leading space. In fact, there are two different tokens for &#39;world&#39; and &#39; world&#39;:</p><pre>print(enc.encode(&quot;world&quot;)) # [24169]<br>print(enc.encode(&quot; world&quot;)) # [2375]</pre><p>This results from how BPE works: because it frequently merges tokens that appear together, and words often follow a space, most words end up with two versions — one with a leading space and one without. This helps reduce token usage and improves the model’s understanding of word boundaries.</p><p>Instead of decoding tokens one by one using the decode_single_token_bytes method, we can also decode the entire list of tokens at once using the decode method:</p><pre>decoded_text = enc.decode(tokens)<br>print(decoded_text) # &#39;Hello, world&#39;</pre><blockquote>Warning: While you can apply decode to single tokens, doing so may be lossy if the token does not align with UTF-8 character boundaries.</blockquote><p>Remember how we said that the tokens are often subwords instead of whole words? Here is an example of a tokenization where a single word is split into multiple tokens:</p><pre>tokens = enc.encode(&quot;Deoxyribonucleic acid&quot;)<br>print(tokens) # [1923, 1233, 3866, 53047, 68714, 291, 18655]</pre><p>Let’s print the tokens one by one:</p><pre>for token in tokens:<br>    print(enc.decode_single_token_bytes(token))</pre><p>This will output:</p><pre>b&#39;De&#39;<br>b&#39;ox&#39;<br>b&#39;yr&#39;<br>b&#39;ibon&#39;<br>b&#39;ucle&#39;<br>b&#39;ic&#39;<br>b&#39; acid&#39;</pre><p>We can see that the word “Deoxyribonucleic” is split into 6 tokens.</p><h3>Token Pricing</h3><p>Understanding tokens is key to understanding how LLMs are priced because model providers typically charge per token. For example, the <a href="https://platform.openai.com/docs/pricing">OpenAI Pricing page</a> lists prices per million tokens — not per request.</p><p>Let’s say you want to use the gpt-4o model in your application and you want to estimate the cost of a given prompt. The OpenAI pricing page gives two prices — one price for input tokens and one price for output tokens. In this particular instance, they charge $2.50 per million input tokens and $10 per million output tokens.</p><blockquote>Output tokens are more expensive than input tokens because they have to be generated by the model one by one.</blockquote><p>Therefore, if you had a prompt containing 1000 tokens that is expected to generate 2000 tokens, the cost for the input tokens would be $2.50 * 1000 / 1000000 = $0.0025 and the cost for the output tokens would be $10 * 2000 / 1000000 = $0.02.</p><p>The total cost for the prompt would be $0.0025 + $0.02 = $0.0225.</p><p>This is a very simple example, but it already illustrates that your costs will be mostly determined by the number of output tokens that you generate.</p><p>That makes practical cost estimation a bit tricky because the number of output tokens is typically not known in advance. Nevertheless, you can produce reasonable estimates by sending a few example requests and averaging the results. You can either do this manually by counting the output tokens using the <em>tiktoken</em> library or by inspecting the response using the OpenAI API which gives you a usage object containing the number of input and output tokens:</p><pre>import os, sys, requests<br><br>OPENAI_API_KEY = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>if not OPENAI_API_KEY:<br>    sys.exit(&quot;Error: set your API key in the OPENAI_API_KEY environment variable.&quot;)<br><br>response = requests.post(<br>    &quot;https://api.openai.com/v1/chat/completions&quot;,<br>    headers={<br>        &quot;Authorization&quot;: f&quot;Bearer {OPENAI_API_KEY}&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    },<br>    json={<br>        &quot;model&quot;: &quot;gpt-4o&quot;,<br>        &quot;messages&quot;: [<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hello, world&quot;}<br>        ]<br>    }<br>)<br><br>response_json = response.json()<br>usage = response_json[&quot;usage&quot;]<br>prompt_tokens = usage[&quot;prompt_tokens&quot;]<br>completion_tokens = usage[&quot;completion_tokens&quot;]<br>total_tokens = usage[&quot;total_tokens&quot;]<br><br>print(f&quot;Completion: {response_json[&#39;choices&#39;][0][&#39;message&#39;][&#39;content&#39;]}&quot;)<br><br>print(f&quot;Prompt tokens: {prompt_tokens}&quot;)<br>print(f&quot;Completion tokens: {completion_tokens}&quot;)<br>print(f&quot;Total tokens: {total_tokens}&quot;)</pre><p>This will output something along the lines of:</p><pre>Completion: Hello! How can I assist you today?<br><br>Prompt tokens: 10<br>Completion tokens: 9<br>Total tokens: 19</pre><p>OpenAI includes formatting tokens for message roles in the total token count — which is why you see 10 prompt tokens instead of just 4. For most practical purposes, this difference will be negligible.</p><p>Once you’ve estimated how many tokens your application will use, it’s a good idea to set a maximum token limit. A common approach is to allow about 50% more than your estimate, using the max_tokens or max_completion_tokens parameter. This helps avoid unexpected costs while giving you a bit of buffer.</p><h3>The Context Window</h3><p>Every large language model has a <strong>context window</strong> — the maximum number of tokens that can be processed in a single request. For example, the gpt-4o model has a context window of 128k tokens.</p><p>If you try to process more tokens than the context window allows, most APIs will throw an error while most chat interfaces will silently truncate the request. This is especially important to keep in mind when you have long multi-turn conversations or are processing large files.</p><p>To avoid overflowing the context window, you can summarize or compress earlier content, truncate low-priority sections, use sliding windows or chunk long content into smaller pieces. We will discuss some of these approaches in later chapters.</p><p>For now, it’s important to understand that the context window is a hard limit on what you can process and that you need to keep that in mind when you design your application.</p><p><em>If you found this helpful, give it a few 👏 (you can hit up to 50!) and tap </em><strong><em>Subscribe</em></strong><em> to get more insights in your feed.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eb5fbefb075" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thinking-sand/what-is-llm-tokenization-and-why-is-it-important-4eb5fbefb075">What is LLM Tokenization and Why Is It Important?</a> was originally published in <a href="https://medium.com/thinking-sand">Thinking Sand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding LLM Logprobs]]></title>
            <link>https://medium.com/thinking-sand/understanding-llm-logprobs-029794105903?source=rss-ecf95b4b6977------2</link>
            <guid isPermaLink="false">https://medium.com/p/029794105903</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[logprobs]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Mikhail Berkov]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 11:25:15 GMT</pubDate>
            <atom:updated>2025-04-07T11:31:07.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBCbzXidBtZGGfxiilzk9g.png" /></figure><p>We have already covered that the average LLM API has a lot of different parameters that can affect your text generation output. One such parameter is <a href="https://medium.com/thinking-sand/the-definitive-guide-to-llm-temperatures-abab311260a6">temperature</a>, which we explored in a previous article. Another powerful feature you can experiment with is <strong>logprobs</strong>.</p><p>As usual, it is instructive to look at the OpenAI API <a href="https://platform.openai.com/docs/api-reference/chat/create#chat-create-logprobs">documentation</a>. Here is what it says about the logprobs parameter:</p><blockquote>Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message.</blockquote><p>Additionally, you can choose how many logprobs to return by <a href="https://platform.openai.com/docs/api-reference/chat/create#chat-create-top_logprobs">specifying</a> top_logprobs:</p><blockquote>An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. logprobs must be set to true if this parameter is used.</blockquote><p>But what exactly do these logprobs do?</p><h3>Next Token Prediction</h3><p>We have already discussed how large language models generate the next token in the <a href="https://medium.com/thinking-sand/a-guide-to-large-language-models-for-non-techies-2b2ac152ccc8">guide to LLMs for non-techies</a>, but to recap:</p><blockquote>[The prediction layer] takes the embeddings created by the transformer and <strong>produces a huge list of probabilities for the next token</strong>. For example, if the input text was “What is a large language”, the token “model” would have a high probability, but the tokens “homework” or “fngrl” would probably have a low probability.</blockquote><p>Here is how this looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*d2MxQxwyHuFWWi5IwywtMA.png" /><figcaption>The prediction layer produces a huge list containing the probabilities for all possible next tokens.</figcaption></figure><p>In this particular example, we would assign:</p><ul><li>a probability of 0.4 that the next token should be “model”</li><li>a probability of 0.1 that the next token should be “homework”</li><li>a probability of 0.01 that the next token should be “fngrl”</li></ul><p>From this list of probabilities we can then actually sample the next token. This is something we also covered in the <a href="https://medium.com/thinking-sand/a-guide-to-large-language-models-for-non-techies-2b2ac152ccc8">guide to LLMs for non-techies</a>:</p><blockquote>You can then use this list of probabilities to actually produce the next token. The simplest way to go about it would, of course, be to always <strong>select the most probable token</strong>. However, this often leads to boring and repetitive texts.</blockquote><blockquote>Instead, LLMs usually <strong>sample</strong> from this distribution. This means that they randomly select a token in such a way that tokens with higher probabilities have a higher chance to be generated.</blockquote><p>You can probably already see where this is going. <strong>The logprobs represent the (logarithms of the) probabilities of the various next tokens.</strong></p><h3>Getting the Logprobs</h3><p>You can get the logprobs from the OpenAI API (and most other OpenAI-compatible APIs) by setting the logprobs parameter to true and setting the top_logprobs to indicate how many logprobs you want to return:</p><pre>curl https://api.openai.com/v1/chat/completions \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;Authorization: Bearer $OPENAI_API_KEY&quot; \<br>  -d &#39;{<br>    &quot;model&quot;: &quot;gpt-4o&quot;,<br>    &quot;messages&quot;: [<br>      {<br>        &quot;role&quot;: &quot;system&quot;,<br>        &quot;content&quot;: &quot;You are a helpful assistant.&quot;<br>      },<br>      {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;Generate me a random number between 1 and 9. Only return that random number, nothing else.&quot;<br>      }<br>    ],<br>    &quot;temperature&quot;: 0,<br>    &quot;logprobs&quot;: true,<br>    &quot;top_logprobs&quot;: 10<br>  }&#39;</pre><p>If we look at the top_logprobs field in the response, we will see something like this:</p><pre>[<br>  {<br>    &quot;token&quot;: &quot;4&quot;,<br>    &quot;logprob&quot;: -1.6929036378860474,<br>    &quot;bytes&quot;: [<br>      52<br>    ]<br>  },<br>  {<br>    &quot;token&quot;: &quot;7&quot;,<br>    &quot;logprob&quot;: -1.8179036378860474,<br>    &quot;bytes&quot;: [<br>      55<br>    ]<br>  },<br>  {<br>    &quot;token&quot;: &quot;5&quot;,<br>    &quot;logprob&quot;: -1.8179036378860474,<br>    &quot;bytes&quot;: [<br>      53<br>    ]<br>  },<br>  {<br>    &quot;token&quot;: &quot;3&quot;,<br>    &quot;logprob&quot;: -1.9429036378860474,<br>    &quot;bytes&quot;: [<br>      51<br>    ]<br>  },<br>  {<br>    &quot;token&quot;: &quot;6&quot;,<br>    &quot;logprob&quot;: -1.9429036378860474,<br>    &quot;bytes&quot;: [<br>      54<br>    ]<br>  },<br>  {<br>    &quot;token&quot;: &quot;8&quot;,<br>    &quot;logprob&quot;: -2.067903518676758,<br>    &quot;bytes&quot;: [<br>      56<br>    ]<br>  },<br>  {<br>    &quot;token&quot;: &quot;2&quot;,<br>    &quot;logprob&quot;: -2.692903518676758,<br>    &quot;bytes&quot;: [<br>      50<br>    ]<br>  },<br>  {<br>    &quot;token&quot;: &quot;9&quot;,<br>    &quot;logprob&quot;: -4.817903518676758,<br>    &quot;bytes&quot;: [<br>      57<br>    ]<br>  },<br>  {<br>    &quot;token&quot;: &quot;1&quot;,<br>    &quot;logprob&quot;: -6.067903518676758,<br>    &quot;bytes&quot;: [<br>      49<br>    ]<br>  },<br>  {<br>    &quot;token&quot;: &quot;Sure&quot;,<br>    &quot;logprob&quot;: -8.942903518676758,<br>    &quot;bytes&quot;: [<br>      83,<br>      117,<br>      114,<br>      101<br>    ]<br>  }<br>]</pre><p>To get from the logprobs to the actual probabilities, we simply have to calculate <strong>p = exp(logprob)</strong>.</p><p>Therefore, these are the tokens together with their actual probabilities for our request:</p><ul><li>the token 4 has the generation probability p ~ exp(-1.69) ~ 0.18</li><li>the token 7 has the generation probability p ~ exp(-1.81) ~ 0.16</li><li>the token 5 has the generation probability p ~ exp(-1.81) ~ 0.16</li><li>…</li><li>the token 1 has the generation probability p ~ exp(-6.06) ~ 0.002</li></ul><blockquote>Yes, LLMs are bad random number generators.</blockquote><p>It’s also important to note that for the reasons previously discussed in the <a href="https://medium.com/thinking-sand/the-definitive-guide-to-llm-temperatures-abab311260a6">temperature</a> article the logprobs will not be deterministic. If you rerun the same query multiple times you will get different logprobs.</p><blockquote>Again, you can try setting the seed parameter here to partially mitigate this problem, but even then the OpenAI API does not guarantee anything (at least as of the time I write this).</blockquote><h3>Why Logprobs?</h3><p>Why do LLMs output logprobs instead of just giving us the probabilities directly? The main answer is that it is better to work with logprobs if you are working with a lot of elements.</p><p>Consider a text T which consists of tokens x₁, x₂, …, xₙ (where n is some reasonably large number). If you want to determine the joint probability of the text T, you would need to calculate:</p><p><strong>P(T) = P(x₁) * P(x₂) * … * P(xₙ)</strong></p><p>Remember, the probabilities P(xᵢ) will all be numbers smaller than 1, which means you will be <em>multiplying a lot of numbers smaller than 1</em>. If you know anything about floating point calculations, you know that this will quickly lead to nasty problems which will make this calculation highly numerically unstable.</p><p>Logprobs to the rescue! Remember the following identity:</p><p><strong>log(p * q) = log(p) + log(q)</strong></p><p>This means that instead of calculating P(T), we can calculate logprob(T) as follows:</p><p><strong>logprob(T) = logprob(x₁) + logprob(x₂) +… + logprob(xₙ)</strong></p><p>Adding numbers is numerically much safer than multiplying them, so even for a large number of tokens we will get accurate results.</p><h3>Logprobs as Confidence</h3><p>You can think of the model logprobs as a kind of “confidence” the model has in the next token prediction. If the logprob is very high, the model is very confident in the next token. Similarly, if the logprob is very low, the model is not really confident in the next token.</p><p>This can be used in practice. For example, let’s say you want to employ an LLM for a classification problem. Instead of just outputting the class predicted by the model, you could also output the logprob of the class token to indicate the confidence of the prediction.</p><p>Similarly, if you want to get the confidence of the model over an entire text, you can calculate:</p><p><strong>logprob(T) = logprob(x₁) + logprob(x₂) +… + logprob(xₙ)</strong></p><p>This allows you to quantify how likely the model thinks a particular sequence is.</p><blockquote>You could, in fact, use this as a simple AI detector. Just take an existing text and calculate the logprob across that text.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=029794105903" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thinking-sand/understanding-llm-logprobs-029794105903">Understanding LLM Logprobs</a> was originally published in <a href="https://medium.com/thinking-sand">Thinking Sand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WSGI Explained]]></title>
            <link>https://medium.com/@uhasker/wsgi-explained-cc3ddc1b232e?source=rss-ecf95b4b6977------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc3ddc1b232e</guid>
            <category><![CDATA[python-web-development]]></category>
            <category><![CDATA[gunicorn]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[wsgi]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Mikhail Berkov]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 16:27:32 GMT</pubDate>
            <atom:updated>2025-03-02T16:27:32.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VChZN2-9goHSaoAXVrEO0g.png" /></figure><p>If you’ve worked with Python web frameworks like Flask, gunicorn or Django you might have heard that they build on top of <strong>WSGI</strong> (short for Web Server Gateway Interface). You may have also tried to look at <a href="https://peps.python.org/pep-3333/">PEP 3333</a> just to encounter terms like “server gateway” and “application object” and give up.</p><p>So let’s dive into WSGI and find out what is going on there.</p><h3>A Simple WSGI Application</h3><p>The simplest possible WSGI application looks like this:</p><pre>from wsgiref.simple_server import make_server<br><br>def application(environ, start_response):<br>    response_body = b&quot;Hello, world&quot;<br>    start_response(&#39;200 OK&#39;, [(&#39;Content-Type&#39;, &#39;text/html&#39;), (&#39;Content-Length&#39;, str(len(response_body)))])<br>    return [response_body]<br><br>httpd = make_server(&#39;localhost&#39;, 8000, application)<br>httpd.handle_request()</pre><p>Save this script under app.py and start the server by running the script as python app.py.</p><p>You can now send a request to it like this:</p><pre>curl -X GET http://localhost:8000/</pre><p>This will return Hello, world.</p><p>What exactly does this code do?</p><h3>Some Terminology</h3><p>WSGI is a specification whose job is to create a standard interface between traditional web servers (like nginx) and Python web applications.</p><p>The most important WSGI concept is the <strong>application object</strong>. Interestingly enough, the application object is not really a regular Python object, but a callable. To quote from PEP 3333:</p><blockquote>The term “object” should not be misconstrued as requiring an actual object instance: a function, method, class, or instance with a __call__ method are all acceptable for use as an application object.</blockquote><p>Really, an application object is just a callable that accepts two arguments — environ and start_response.</p><p>The environ variable is a dictionary containing essential information about the request as well as the server configuration. Here is where you can find things like the request method, the query string, and the request headers.</p><p>The start_response method is a callback that can be used to initiate an HTTP response. This is what you call when you have finished processing the request, calculated the response data, and want to return the actual response.</p><p>The <strong>WSGI server</strong> (also often referred to as the WSGI gateway) invokes the application object (which, again, is just a callable) once for each request that it receives from an HTTP client. To quote from PEP 3333 again:</p><blockquote>The server or gateway invokes the application callable once for each request it receives from an HTTP client, that is directed at the application.</blockquote><p>PEP 3333 prescribes very little in terms of actual implementation, and in fact, there are lots of different WSGI implementations out there. Our example uses simple_server.WSGIServer which is available from the standard library.</p><blockquote>Note that simple_server.WSGIServer is not a production-ready WSGI implementation. We will cover production-ready WSGI servers in a later article.</blockquote><h3>The environ Dictionary</h3><p>As we’ve already mentioned, the environ dictionary contains information about the request and the server configuration.</p><p>The most important values are:</p><ul><li>REQUEST_METHOD which contains the HTTP request method (GET in our example)</li><li>SERVER_NAME which contains the server name (localhost in our example)</li><li>SERVER_PORT which contains the server port (8000 in our example)</li><li>SERVER_PROTOCOL which contains the HTTP protocol (most likely HTTP/1.1 in our example)</li><li>PATH_INFO which contains the request path (/ in our example)</li><li>QUERY_STRING which contains the query string, i.e. the portion of the URL that contains the query parameters (an empty string in our example)</li></ul><p>Additionally, the keys that are prefixed with HTTP_ correspond to the headers of the request. For example, HTTP_USER_AGENT would correspond to the User-Agent header.</p><h3>Sending a Response</h3><p>The start_response callable can be used to begin the HTTP response. It takes two mandatory arguments.</p><p>The first one is the status code formatted as a status string like 200 OK or 404 Not Found.</p><p>The second one represents the response headers and must contain a list of (header_name, header_value) tuples. Each header_name must be a valid HTTP header field-name (like Content-Type or Content-Length).</p><p>Here is how this could look like:</p><pre>start_response(&#39;200 OK&#39;, [<br>    (&#39;Content-Type&#39;, &#39;text/html&#39;),<br>    (&#39;Content-Length&#39;, str(len(response_body)))<br>])</pre><p>You will note that there is an argument that is conspicuously absent here and that’s the actual response body. That’s because start_response only <em>initiates</em> the HTTP response, but it does not actually send it.</p><p>Instead, the WSGI application callable returns an iterable (usually a list) containing the response body as byte strings. The WSGI server iterates over this iterable to send the actual content to the client:</p><pre>def application(environ, start_response):<br>    ...<br>    return [response_body]</pre><p>This is useful because it means that applications can produce response data lazily and generate the content on-the-fly, which is necessary if you want to e.g. stream data.</p><h3>Reading the Request Body</h3><p>If you want to read the request body (e.g. in a POST request), you need to access the special wsgi.input field of the environ variable. This is a BufferedReader from which you can read the data using the BufferedReader.read method. Note that this will return bytes, so if you want to get a string, you need to decode those bytes:</p><pre>request_body = environ[&#39;wsgi.input&#39;].read(content_length).decode(&#39;utf-8&#39;)</pre><p>You can get the content length from the environ[&quot;CONTENT_LENGTH&quot;]. Note that this might be empty so you need to wrap it inside a try...catch:</p><pre>try:<br>    content_length = int(environ.get(&#39;CONTENT_LENGTH&#39;, 0))<br>except ValueError:<br>    content_length = 0</pre><p>Here is how the full application callable should look like:</p><pre>def application(environ, start_response):<br>    try:<br>        content_length = int(environ.get(&#39;CONTENT_LENGTH&#39;, 0))<br>    except ValueError:<br>        content_length = 0<br>    request_body = environ[&#39;wsgi.input&#39;].read(content_length).decode(&#39;utf-8&#39;)<br>    response_body = f&quot;Hello, world\n{request_body}&quot;<br>    start_response(&#39;200 OK&#39;, [(&#39;Content-Type&#39;, &#39;text/plain&#39;), (&#39;Content-Length&#39;, str(len(response_body)))])<br>    return [response_body.encode(&#39;utf-8&#39;)]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc3ddc1b232e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Definitive Guide to LLM Temperatures]]></title>
            <link>https://medium.com/thinking-sand/the-definitive-guide-to-llm-temperatures-abab311260a6?source=rss-ecf95b4b6977------2</link>
            <guid isPermaLink="false">https://medium.com/p/abab311260a6</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[temperature]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Mikhail Berkov]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 09:51:20 GMT</pubDate>
            <atom:updated>2025-03-18T17:31:23.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9PlyvDSfX5xoslUz2WOYA.png" /></figure><p>If you use the API or a playground of any modern large language model (LLM), you will be able to fiddle with a lot of settings. The most prominent setting will usually be the <strong>temperature</strong>, which e.g. the <a href="https://platform.openai.com/docs/api-reference/assistants/createAssistant#assistants-createassistant-temperature">OpenAI documentation explains</a> like this:</p><blockquote>What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.</blockquote><p>But what <em>exactly</em> does setting the temperature do? Let’s find out.</p><h3>LLMs Predict Token Probabilities</h3><p>Large language models predict the next token by generating a list of probabilities of all possible next tokens and then sampling from that list. I already wrote about this in my <a href="https://medium.com/thinking-sand/a-guide-to-large-language-models-for-non-techies-2b2ac152ccc8">guide to LLMs for non-techies</a>, so I’m just going to quote myself here:</p><blockquote>[The prediction layer] takes the embeddings created by the transformer and <strong>produces a huge list of probabilities for the next token</strong>. For example, if the input text was “What is a large language”, the token “model” would have a high probability, but the tokens “homework” or “fngrl” would probably have a low probability.</blockquote><p>Here is how this looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*TXAEnR_HEwNkrWTkd6DCVw.png" /><figcaption>The prediction layer produces a huge list containing the probabilities for all possible next tokens.</figcaption></figure><p>In this particular example, we would assign:</p><ul><li>a probability of 0.4 that the next token should be “model”</li><li>a probability of 0.1 that the next token should be “homework”</li><li>a probability of 0.01 that the next token should be “fngrl”</li></ul><p>From this list of probabilities we can then actually sample the next token. This is something we also covered in the <a href="https://medium.com/thinking-sand/a-guide-to-large-language-models-for-non-techies-2b2ac152ccc8">guide to LLMs for non-techies</a>:</p><blockquote>You can use then this list of probabilities to actually produce the next token. The simplest way to go about it would of course be to always <strong>select the most probable token</strong>. However, this often leads to boring and repetitive texts.</blockquote><blockquote>Instead, LLMs usually <strong>sample</strong> from this distribution. This means that they randomly select a token in such a way that tokens with higher probabilities have a higher chance to be generated.</blockquote><p>Let’s look at our example once more. If we would follow the first approach (always selecting the most probable token), we would just sample the token “model” since it’s the most probable token.</p><p>However, if we would follow the second approach (sampling from the distribution), we would only sample the token “model” with a probability of 0.4. This also means that with probability 0.1 we would generate the token “homework” which might (or might not) be what we want.</p><p>To recap the most important points:</p><ul><li>LLMs are next-token predictors, i.e. given a text they produce the next token</li><li>they do that by generating a list of probabilities for all possible next tokens and then sampling from that list according to the probabilities</li><li>tokens with higher probabilities will have a higher chance of being generated as the next token</li></ul><p>From now on we will say that we have n possible tokens x₁ to xₙ and the probability of each token will be called P(xᵢ).</p><h3>The Temperature</h3><p>The temperature controls how we weigh the initial probabilities that we get from the prediction layer.</p><p>Instead of directly sampling from the probability distribution P, we sample from a new probability distribution Q where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/0*4Eu-W0rpLc4p2iRw.png" /></figure><p>This looks a bit strange at first glance, but you can quite easily understand this formula by substituting different values for T.</p><p>Let’s consider this formula for T = 1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/0*XWXBwyMwq0Kg7eiL.png" /></figure><p>In that case Q is equivalent to P. Put differently, T = 1 means “don’t change the probability distribution and directly sample from it”.</p><p>What if we have T = 0.1? Then this becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/0*vmMdRm2d_mE_rEZj.png" /></figure><p>This means that large probabilities will weighted even heavier compared to their smaller counterparts. <strong>Generally, T &lt; 1 means you assign even more weight to already large probabilities.</strong> The sampling becomes more deterministic.</p><p>An interesting edge case to consider is T = 0. Technically, Q is not defined for this value (since you can’t meaningfully divide by 0). <strong>Practically, we say that T = 0 means that you just always sample the token with the highest probability.</strong></p><p>What happens for T &gt; 1? Let’s consider T = 10 as an example. Then Q looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*mDsWgfXFIuYnhZKl.png" /></figure><p>This is basically the opposite of T &lt; 1 which is not particularly surprising. <strong>For T &gt; 1, larger probabilities are weighted less compared to their smaller counterparts.</strong> You get a more uniform probability distribution and your sampling becomes more random.</p><h3>The Optimal Temperature</h3><p>There is very little rigorous research with regards to optimal temperature settings. For example, the famous <a href="https://arxiv.org/pdf/2303.08774">GPT-4 technical report</a> basically just sets a best-guess temperature of 0.6 for all their free response questions:</p><blockquote>Due to the longer iteration time of human expert grading, we did no methodology iteration on temperature or prompt, instead we simply ran these free response questions each only a single time at our <strong>best-guess temperature (0.6) </strong>and prompt.</blockquote><p>On the other hand, the default temperature of the OpenAI API is <a href="https://platform.openai.com/docs/api-reference/chat/create#chat-create-temperature">set to T = 1</a>. However, <a href="https://platform.openai.com/docs/api-reference/making-requests">a lot of request examples in the docs are given with a temperature of T = 0.7</a>. Other sources also recommend <a href="https://datascience.stackexchange.com/questions/124584/why-is-0-7-in-general-the-default-value-of-temperature-for-llms">T = 0.7</a>.</p><p>Empirically, developers have observed that:</p><ul><li>lower temperatures (T ≤ 0.7) are suitable for tasks requiring precision and reliability, e.g. factual question answering</li><li>moderate temperatures (0.7 &lt; T ≤ 1) are suitable for general-purpose conversations where you need reliability but also some degree of creativity, e.g. for a chat bot</li><li>higher temperatures (T &gt; 1) are suitable for creative endeavors, e.g. for storytelling or brainstorming</li></ul><p>Again, this has practically no rigorous theoretical basis and seems to just be something application developers have empirically converged on. So take these values with a grain of salt (or, rather, a full salt mill).</p><h3>OpenAI and T = 0</h3><p>If you work a lot with the OpenAI API in real-world applications, you will soon run into an interesting case — <strong>the OpenAI API is not deterministic even for T=0</strong> (as of the time of this writing).</p><p>You can try this out for yourself. Grab your API key and set T = 0:</p><pre>curl https://api.openai.com/v1/chat/completions \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;Authorization: Bearer $OPENAI_API_KEY&quot; \<br>  -d &#39;{<br>    &quot;model&quot;: &quot;gpt-4o&quot;,<br>    &quot;messages&quot;: [<br>      {<br>        &quot;role&quot;: &quot;system&quot;,<br>        &quot;content&quot;: &quot;You are a helpful assistant.&quot;<br>      },<br>      {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;Hello, how are you doing today?&quot;<br>      }<br>    ],<br>    &quot;temperature&quot;: 0<br>  }&#39;</pre><p>This will return different responses between each run. For instance, here is what I got for the first run:</p><pre>Hello! I&#39;m just a computer program, so I don&#39;t have feelings, but I&#39;m here and ready to help you. How can I assist you today?</pre><p>And here is what I got for the second run:</p><pre>Hello! I&#39;m just a computer program, so I don&#39;t have feelings, but I&#39;m here and ready to help you with whatever you need. How can I assist you today?</pre><p>Note that the texts have different endings. What is going on?</p><p>I think that the answer provided in this <a href="https://stackoverflow.com/questions/76855624/azure-openai-gpt-35-turbo-nondeterministic-with-temperature-0?utm_source=chatgpt.com">Stack Overflow thread</a> is largely correct.</p><p>First, you will always have some non-determinism due to the underlying tech stack which includes a lot of asynchronous floating point GPU computations (a topic which we will dive into at some point).</p><p>Second, GPT-4 is most likely a Mixture of Experts model which introduces additional non-determinism as well. You can read an explanation for this <a href="https://152334h.github.io/blog/non-determinism-in-gpt-4/">here</a>.</p><p>To get completely deterministic behaviour, you can try to provide a seed to the model:</p><pre>curl https://api.openai.com/v1/chat/completions \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -H &quot;Authorization: Bearer $OPENAI_API_KEY&quot; \<br>  -d &#39;{<br>    &quot;model&quot;: &quot;gpt-4o&quot;,<br>    &quot;messages&quot;: [<br>      {<br>        &quot;role&quot;: &quot;system&quot;,<br>        &quot;content&quot;: &quot;You are a helpful assistant.&quot;<br>      },<br>      {<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: &quot;Hello, how are you doing today?&quot;<br>      }<br>    ],<br>    &quot;temperature&quot;: 0,<br>    &quot;seed&quot;: 42<br>  }&#39;</pre><p>If you try to run this query multiple times, you will most likely get the same answers over multiple runs.</p><p>However, you should know that even with a seed, the OpenAI API <a href="https://platform.openai.com/docs/api-reference/chat/create#chat-create-seed">does not technically guarantee determinism</a>:</p><blockquote>If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same seed and parameters should return the same result.</blockquote><blockquote>Determinism is not guaranteed, and you should refer to the system_fingerprint response parameter to monitor changes in the backend.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abab311260a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thinking-sand/the-definitive-guide-to-llm-temperatures-abab311260a6">The Definitive Guide to LLM Temperatures</a> was originally published in <a href="https://medium.com/thinking-sand">Thinking Sand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Four Components of a Large Language Model]]></title>
            <link>https://medium.com/thinking-sand/a-guide-to-large-language-models-for-non-techies-2b2ac152ccc8?source=rss-ecf95b4b6977------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b2ac152ccc8</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Mikhail Berkov]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 19:20:33 GMT</pubDate>
            <atom:updated>2025-07-01T08:21:17.401Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNcnY55bl5yNzk63PcaVIA.png" /></figure><p>Unless you happen to live under a rock (in which case, good for you), you’ve certainly heard of <strong>large language models</strong> (LLMs). Chances are that you’ve even used them at some point (<em>*cough*</em> ChatGPT <em>*cough*</em>). However, the only thing most people know about large language models is that they seem to be large, have something to do with language and are, apparently, models.</p><p>This is not really surprising given that most explanations and papers in the field read like an alien vomited over a sheet of paper and then attempted to arrange the mess into something vaguely resembling human language. In this article, we will try to understand the high-level functionality behind an LLM without the alien vomit.</p><h3>Predicting the Next Token</h3><p>First of all, large language models are <strong>next token predictors</strong>.</p><p>What do we mean by that? <strong>At its core, you give an LLM a text and it predicts the next token that should follow the text.</strong> A <strong>token</strong> is basically just a part of a text (for example a token might be “<em>an</em>” or “<em>123</em>” or “<em>this</em>” or “<em>th</em>”).</p><p>For example, the input text could be the text “<em>What is a large language”. </em>Then the LLM might predict that the next token should be “<em> model</em>”. By combining the input text and the next token we get the result which would be “<em>What is a large language model”.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*CEmyoEw2zYwIEm_KnEFcaQ.png" /><figcaption>The text “What is a large language” is passed through an LLM which predicts the next token as “ model”.</figcaption></figure><blockquote>The whitespace at the beginning in the “ model” token is on purpose. After all, the whitespaces also need to be part of the resulting text.</blockquote><p>However, if you’ve ever you talked to something like ChatGPT, you know that LLMs don’t just give the next token, but instead respond with <strong>complete texts</strong>. How do they do that?</p><p>The answer is embarrassingly simple — <strong>LLMs generate texts one token at a time</strong>. Yeah, that’s really all there is.</p><p>Again, let’s say that the text to be completed is “<em>What is a Large Language</em>”.</p><p>The LLM might predict “<em> Model</em>” as the next token. Now you would take the text together with the next token (“<em>What is a Large Language Model</em>”) and feed it into the model again, asking it to predict the next token which might be the question mark “<em>?</em>”. You can now take the text together with the next token (“<em>What is a Large Language Model?</em>”) again and feed it into the model once more.</p><p>This process continues until either a maximum number of tokens has been reached or the predicted token is a special <strong>EOS</strong> (end of sequence) token which basically stands for “this sequence is over, stop generating”.</p><p>For example, if upon feeding the text “<em>What is Large Language Model?</em>” the model predicts the <strong>EOS</strong> token as the next token, the generation would end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O_uluwePFOorjF7YGTtB2g.png" /><figcaption>LLMs generate texts one token at a time. The predicted token is appended to the text to produce the new input.</figcaption></figure><blockquote>This is by the way why most chatbot applications can “stream” the tokens into the UI and show you one token at a time.</blockquote><p>We just found out that LLMs complete texts by repeatedly predicting the next token. But how do they actually <em>predict the next token</em>? To adequately explain that, we need to introduce a concept called “embeddings” first.</p><h3>It’s Numbers All The Way Down</h3><p>LLMs consist of mathematical functions (more on this later). Mathematical functions tend to work with numbers instead of texts. Therefore, to apply functions to texts, we usually need to convert the texts to numbers first.</p><p>However, we don’t want to convert texts to arbitrary numbers. Instead, these numbers should have some meaning.</p><p>This is the core insight behind <strong>embeddings</strong> — <strong>an embedding is a point in high-dimensional space that represents some piece of a text in a meaningful way</strong>.</p><p>Let’s make this more concrete. For example, you might want to represent the words <em>cat</em>, <em>dog</em>, <em>pet</em>, <em>car</em>, <em>automobile</em>, <em>vehicle</em>, <em>apple</em>, <em>banana</em> and <em>fruit</em> using points in two-dimensional space.</p><p>It seems that — in order for our representation to be meaningful — the words <em>cat</em>, <em>dog</em> and <em>pet</em> should be close to each other. The same should probably be true for <em>car</em>, <em>automobile</em> and <em>vehicle</em>. Finally, <em>apple</em>, <em>fruit</em> and <em>banana</em> should be close to each other as well. However, <em>cat</em> and <em>car</em> should be far apart, because they are <strong>semantically different</strong> (even though there is only a one-letter difference between them).</p><p>The concept of semantic similarity is usually formalized using the <a href="https://en.wikipedia.org/wiki/Distributional_semantics">distributional hypothesis</a>:</p><p><strong>Words (more generally, tokens) are similar if they appear in similar contexts.</strong></p><p>This is why we would say that “cat” and “dog” are semantically similar (even though obviously cats and dogs are very different pets) — because they appear in similar contexts (namely, when we talk about pets).</p><p>Here is how all of this could look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*_JrYUs5qkEdwXHXxmyeJnQ.png" /><figcaption>An example visualization of a few (hypothetical) embeddings. Usually, there will be many more dimensions than 2.</figcaption></figure><p>Mathematically, we can represent points as lists of numbers called <strong>vectors</strong>. In this example, the word <em>pet</em> is represented by the vector <em>(2, 1.5).</em></p><p><strong>Therefore, embeddings of texts are vectors with the property that two embeddings are close to each other if the underlying texts are semantically similar.</strong></p><p>We can apply this concept to more than just words. Embeddings can be created for sentences, paragraphs, articles and any arbitrary pieces of text (like tokens).</p><blockquote>One important thing to note is that, in practice, embeddings have much more dimensions than just two. For example, embeddings that are utilized in modern LLMs have anywhere from hundreds to thousands of dimensions.</blockquote><h3>The Four Components of a Large Language Model</h3><p>Armed with this newfound knowledge, we can sketch out the four fundamental components of most Large Language Models.</p><p><strong>The first component is the tokenizer.</strong> The tokenizer is responsible for <strong>splitting an input text into tokens</strong>.</p><p>For example, the tokenizer used by GPT-4 would take the text “<em>What is a Large Language Model?</em>” and split it into the following tokens:</p><ul><li><em>What</em></li><li><em>is</em></li><li><em>a</em></li><li><em>Large</em></li><li><em>Language</em></li><li><em>Model</em></li><li><em>?</em></li></ul><p>Here is how you could visualize this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ZsJnjvAsaBryLl7Z3kVRKg.jpeg" /><figcaption>The tokenization of the sentence “What is a Large Language Model?”</figcaption></figure><p>Note that the GPT-4 tokenizer would not always split the text into word tokens. If you would take the english word <em>overfitting</em>, the resulting tokens would be <em>over</em>, <em>fit</em> and <em>ting</em>.</p><p>You can try the GPT-4 tokenizer as well as other tokenizers out for yourself at <a href="https://platform.openai.com/tokenizer">this link</a>.</p><blockquote>Technical Completeness Note: In reality, the tokenizer produces token IDs which are special numbers that represent the tokens. However, this is not particularly relevant for the high-level understanding we are trying to achieve here.</blockquote><p><strong>The second component is an embedding layer.</strong> The embedding layer takes the list of tokens produced by the tokenizer and <strong>produces an embedding for each token</strong>. Consider the list of tokens from our example:</p><ul><li><em>What</em></li><li><em>is</em></li><li><em>a</em></li><li><em>Large</em></li><li><em>Language</em></li><li><em>Model</em></li><li><em>?</em></li></ul><p>Here we have seven tokens. This means that the embedding layer would produce seven embeddings (one embedding per token).</p><p>The first embedding would be a vector representing the token “<em>What</em>”, the second embedding a vector representing the token “<em> is</em>” and so on until we arrive at the last embedding representing the token “<em>?</em>”.</p><p>Remember that embeddings are lists of numbers (vectors) that represent points in high-dimensional space in a semantically meaningful way. Therefore the output of the embedding layer would contain seven vectors which have some semantic meaning.</p><blockquote>Technical Completeness Note: In addition to token embeddings, there are also positional embeddings and more. These are often combined. We will gloss over these technical details since they are— again — not particularly relevant for a high-level understanding.</blockquote><p><strong>The third component is the transformer.</strong> The transformer is really the core component of modern LLMs. It basically <strong>takes the embeddings and mixes them together to provide context </strong>(resulting in better embeddings).</p><p>Why is this important? Consider the two sentences “The <em>bat</em> flew out of the cave” and “He hit the ball with his <em>bat</em>”. In both texts, the token “<em>bat</em>” is present, however it has a completely different meaning in each sentence.</p><p>The embedding layer would produce the same embeddings for the “bat” token in both cases. After all, the token would be the same in both sentences. This obviously doesn’t seem ideal.</p><p>Therefore, the transformer <strong>introduces context using something called the attention mechanism</strong>. This allows the other tokens to — well — pay <strong>attention</strong> to other relevant tokens. For example, <em>bat</em> might pay attention to <em>flew</em> and <em>cave</em> in the first sentence and pay attention to <em>hit</em> and <em>ball</em> in the second sentence.</p><p>Let’s consider the sentence “The bat flew out of the cave”. Then attention scores for this sentence might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*_t_CPGuQAwuXSTF4e7QOeA.png" /><figcaption>Hypothetical attention scores for the sentence “The bat flew out of the cave”.</figcaption></figure><p>Here we have a high attention score between <em>bat</em> and <em>flew</em>, as well as a high attention score between <em>bat</em> and <em>cave</em>. This means that the transformer knows that the most relevant tokens for <em>bat</em> are <em>flew</em> and <em>cave </em>and can understand that this is the type of <em>bat</em> that <em>flies</em> out of <em>caves</em>.</p><p>Now let’s consider the sentence “He hit the ball with his bat”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*LztOy_oipnh-7fNswnCCnA.png" /><figcaption>Hypothetical attention scores for the sentence “He hit the ball with his bat”.</figcaption></figure><p>Here we have a high attention score between <em>bat</em> and <em>hit</em>, as well as a high attention score between <em>bat</em> and <em>ball</em>. In this case, the transformer knows that the most relevant tokens for <em>bat</em> are <em>hit</em> and <em>ball</em>, i.e. that this is a completely different type of bat — the type that can be used to <em>hit</em> a <em>ball</em>.</p><p>The transformer would now mix the <em>bat</em> embedding with the <em>flew</em> and <em>cave</em> embeddings in the first sentence. In the second sentence however, the transformer would mix the <em>bat</em> embedding with the <em>hit</em> and <em>ball</em> embeddings.</p><p>The embeddings for <em>bat</em> would therefore be completely different in each sentence, because they now have context — we call these <strong>contextualized embeddings</strong>. This contextualization is important not just because we can distinguish between <a href="https://en.wikipedia.org/wiki/Homograph">homographs</a>, but also because the LLM can generally look at the entire text instead of just looking at disconnected tokens.</p><blockquote>Technical Completeness Note: The attention mechanism is relatively complicated and traditionally involves converting the embeddings to key and query vectors, computing attention scores and then using the attention scores to combine value vectors. Since this a high-level overview, we will not dive into these computations here.</blockquote><p><strong>The fourth and final component is a prediction layer.</strong> This takes the embeddings created by the transformer and <strong>produces a huge list of probabilities for the next token</strong>. For example, if the input text was “<em>What is a Large Language</em>” then the token “ <em>Model</em>” would have a high probability, but the tokens “homework” or “<em>fngrl</em>” would probably have a low probability.</p><p>You can use then this list of probabilities to actually produce the next token. The simplest way to go about it would of course be to always select the most probable token. However, this often leads to boring and repetitive texts.</p><p>Instead, LLMs usually <strong>sample</strong> from this distribution. This means that they randomly select a token in such a way that tokens with higher probabilities have a higher chance to be generated.</p><p>This is what people talk about when they say that LLMs are <strong>probabilistic models</strong>. Given texts, they produce next tokens with certain probabilities. Some tokens are produced with a higher probability and some tokens are produced with a lower probability.</p><p>This is also why e.g. ChatGPT often gives you different responses for the same input. After all, if you sample from lists of probabilities you will often get different responses even if your inputs are the same.</p><p>Finally, this probabilistic mechanism is also why you can never quite trust an LLM. After all, there is no intrinsic mechanism that would prevent it from generating tokens that lead to inaccurate sentences. This is why ChatGPT has the small disclaimer at the bottom of the screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LRKhGWtJ4kwSKZzwsKEQsw.png" /><figcaption>Yes, you should absolutely check important info when talking to LLMs.</figcaption></figure><p><strong>To sum it up — here is how an LLM predicts the next token given a text:</strong></p><p><strong>First, the tokenizer splits the text into tokens. Second, the embedding layer generates an embedding for every token. Third, the transformer improves the embeddings by mixing them together and produces better embeddings. Finally, the prediction layer generates a list of probabilities for all possible next tokens and samples the next token.</strong></p><h3>Training a Large Language Model</h3><p>Ok, so far, so good. But why do companies like OpenAI and Meta have to spend tens of millions of dollars on their Large Language Models?</p><p>Well, remember all those mathematical functions from the previous paragraphs? These functions usually have billions upon billions of parameters.</p><p>And these parameters have to be <strong>learned</strong> — we call that “training the model”.</p><p>To train the model, we need to collect a giant dataset first. And by giant I mean <em>giant</em>. For example, the <a href="https://github.com/togethercomputer/RedPajama-Data">RedPajama-Data-v2 dataset</a> (one of the most well-known open datasets) has 20 billion documents consisting of 30 trillion tokens. This is a <em>lot</em> of tokens.</p><p>The way the actual training works is conceptually simple: First, we initialize the model with random parameters. Next, we split our text corpus into tokens. Then we iterate over all the tokens and at each token, we ask the model to give the probabilities for the next token (this is the output of the prediction layer, remember?). Finally, we adjust the parameters of the model in such a way that the actual next token becomes more probable and all other tokens become less probable.</p><p>This is really it, although quite often after the initial training is done, models are usually fine-tuned (i.e. trained further) on special datasets that make the model less likely to produce undesired outputs, allow the model to chat with a user etc. We will cover this post-training in another article.</p><blockquote>Technical Completeness Note: We necessarily glossed over a lot of technical details in this section. For example, we don’t really train models token by token. Instead, the model is fed batches of training data and processes multiple examples at the same time.</blockquote><p>While conceptually simple, the mathematical details and technical execution can get quite complicated. For example, at some point Meta announced <a href="https://engineering.fb.com/2024/03/12/data-center-engineering/building-metas-genai-infrastructure/">two 24k GPU clusters</a> to manage model training. As you can guess, managing these clusters and running the training requires a high degree of technical sophistication and a lot of resources — not many companies can do something like this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b2ac152ccc8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thinking-sand/a-guide-to-large-language-models-for-non-techies-2b2ac152ccc8">The Four Components of a Large Language Model</a> was originally published in <a href="https://medium.com/thinking-sand">Thinking Sand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>