<?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 Funboy Ea on Medium]]></title>
        <description><![CDATA[Stories by Funboy Ea on Medium]]></description>
        <link>https://medium.com/@funboy.ea?source=rss-52496b282c20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RRjrjDBM_C5AN6Oj</url>
            <title>Stories by Funboy Ea on Medium</title>
            <link>https://medium.com/@funboy.ea?source=rss-52496b282c20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:29:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@funboy.ea/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[When Does Per-Agent Monitoring Fail?]]></title>
            <link>https://medium.com/@funboy.ea/when-does-per-agent-monitoring-fail-e55fc2013204?source=rss-52496b282c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/e55fc2013204</guid>
            <category><![CDATA[aisafetyresearch]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Funboy Ea]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 10:46:10 GMT</pubDate>
            <atom:updated>2026-11-18T10:46:10.846Z</atom:updated>
            <content:encoded><![CDATA[<h3>When Does Per-Agent Monitoring Fail? Distributed Collection Attacks on an Identity-Bound Audit Trail, With a Pre-Registered Follow-Up</h3><p><em>The main experiment was run at the Swarm Alignment Hackathon (Apart Research), 6 to 8 November 2026. The K=5 follow-up was pre-registered on 13 November and run afterwards (13 to 17 November 2026). Code and data: </em><a href="https://github.com/abeenoch/aguard"><em>https://github.com/abeenoch/aguard</em></a><em> (directory </em><em>experiments/).</em></p><h3>Abstract</h3><p>Distributed attacks split a harmful goal across several agents so that no single agent looks suspicious. We ask whether grouping actions by shared resource, using an identity-bound audit trail, helps detect such attacks without knowing which agents collude. We built a testbed on A-guard, an open-source security layer for AI agents: agents authenticate through a real OAuth flow, call MCP tools on a 48-document synthetic corpus (10 confidential), and every access is logged with a verified client identity and resource id. In a first experiment (160 episodes; 2 or 3 colluders reading 3 to 5 confidential documents each) we found no evasion gap: no benign agent read more than 2 confidential documents, so a per-agent count detected every attack and beat every LLM monitor. We then pre-registered five predictions and ran a follow-up with five colluders reading exactly 2 confidential documents each, matching the benign maximum (another 160 episodes). Per-agent counts and per-agent LLM monitoring then failed (0% detection), while a deterministic cross-agent count of confidential documents still detected 100% of attacks at 0% held-out false positives. LLM monitors given raw resource-keyed logs detected at most 10%; with a computed coverage summary their results were inconsistent across monitors and bystander settings (10% to 85%). Three predictions held, one held in part, and one was not supported. An identity-bound audit trail makes cheap, deterministic cross-agent aggregates possible; we found no evidence that LLM monitors use them reliably.</p><h3>1. Introduction</h3><p>In a distributed attack each agent performs its own plausible task, and the harm exists only in the combination of their actions. A monitor that reads one agent at a time cannot see a threat that exists only across agents. Recent red-teaming work on loss-of-control risks built multi-agent control environments and human-crafted distributed attacks that reliably appear benign to frontier-level monitors (Kitaoka et al., 2026). Deployments that put many agents in front of a shared document store usually have something single-agent monitors lack: an access layer that sees every request with a verified principal, a resource id and a timestamp. We ask whether that access layer can close the gap: if audit rows are grouped by the resource touched instead of by agent, can a collection goal that was split across agents be detected <strong>without being told which agents collude</strong>?</p><p><strong>Threat model.</strong> N agents work concurrently on independent benign tasks against a shared document store. K &gt;= 2 of them collude to collect between them the full set of confidential documents, each wrapping this in a cover task. The plan is fixed in advance, there is no communication during the run, and no covert channels are studied. The defender controls the access layer, sees every access with its verified principal, resource and timestamp, and agents cannot forge or suppress audit rows. The defender knows each document’s classification label but not who colludes. The monitor is asynchronous and sees actions only.</p><p><strong>Contributions.</strong></p><ol><li>A reproducible testbed in which scripted colluders and LLM-driven benign agents make real MCP tool calls through a real OAuth flow, each agent a distinct client in an append-only audit trail, with attack success checked deterministically from the audit table.</li><li>A negative first result: when each colluder’s share (3 to 5 confidential documents) exceeds any benign agent’s footprint (at most 2), per-agent monitoring is not evaded, and a plain count beats every LLM monitor.</li><li>A pre-registered follow-up in the regime where per-agent monitoring should fail (five colluders, 2 documents each), with a scorecard of five predictions.</li><li>Evidence that, in that regime, a deterministic cross-agent aggregate over the audit trail succeeds where per-agent views fail, while LLM monitors given the same information are inconsistent.</li></ol><h3>2. Related Work</h3><p><strong>Multi-agent control.</strong> AI control studies protocols that hold up even if models intentionally subvert them (Greenblatt et al., 2024). Kitaoka et al. (2026) extend this to multiple agents with independent benign tasks plus a shared side task, and report that human-crafted distributed attacks appear benign to monitors that read one agent’s trajectory. We follow their framing (independent tasks, a shared hidden goal, action-only monitoring) but use an identity-bound access layer, scripted non-adaptive attacks, and ask about the monitor’s input: grouping by resource without knowing the colluders.</p><p><strong>Multi-agent security.</strong> Other work studies data leakage through compromised agents despite access control (OMNI-LEAK, 2026) and network-level risks in agent systems (Microsoft Research, 2026). Those study attacks; we study a defender-side observation, the audit trail, and its limits.</p><h3>3. Methods</h3><p>All code is in experiments/. A-guard itself (OIDC authorization server, MCP resource server, Postgres-enforced permissions, and the agent_audit table with resource_id) is preexisting and unchanged at git tag pre-sprint (commit 6e0ee4e).</p><p><strong>Environment.</strong> A second A-guard authorization-server and MCP pair ran against a separate database. The corpus has 48 synthetic documents (10 titled CONFIDENTIAL -, 38 not), selected with seed 42 from a dataset generated with Adaption Labs tooling and inserted in shuffled order so that ids do not reveal classification; a doc_meta table records classification. All documents share one owner (agents are tenant-scoped by row-level security). Each agent is a distinct OAuth client (dynamic registration, authorization-code flow with PKCE) calling list_documents, read_document and redact_text; all agents act as the same user and are separated only by client identity.</p><p><strong>Episodes.</strong> An episode is a team plus B bystander agents (B in {0, 3}) running concurrently. In benign episodes every agent is an LLM tool-calling loop (Qwen2.5–7B-Instruct on vLLM, at most 12 steps) with one task from the Adaption-generated task file (128 tasks after filtering, sampled with reuse). In attack episodes the team is scripted (no LLM) and makes the same real tool calls with random delays (0.2 to 2 s) and 1 to 3 cover reads each; bystanders are unchanged. Let T be the 10 confidential documents. <strong>A1</strong> (parallel slicing): K colluders read disjoint slices of T concurrently. <strong>A2</strong> (staged): colluder 1 lists and picks T by title and the rest read it later. An attack succeeds if the colluders’ successful reads cover all of T, checked from agent_audit only.</p><ul><li><strong>Main experiment:</strong> 3-agent teams, A1 and A2, K in {2, 3}, 5 repeats per cell: 40 attacks, plus 60 benign episodes per B (30 calibration, 30 held-out): 160 episodes.</li><li><strong>K=5 follow-up:</strong> 5-agent teams, A1 only, K=5 (each colluder reads exactly 2 confidential documents), 20 attacks per B, plus 60 benign 5-agent episodes per B: 160 episodes. Benign comparison episodes have the same shape.</li></ul><p><strong>Views.</strong> From agent_audit, ordered by time, with pseudonymised principals (shuffled per episode), timestamps as offsets and each resource labelled with its classification: <strong>V1</strong> per-agent (episode score is the max over agents); <strong>V2</strong> the team&#39;s rows merged (uses knowledge of the team); <strong>V3</strong> all rows on documents, all principals; <strong>V4</strong> V3 plus a code-computed summary (per-principal distinct and confidential documents touched, and the union of confidential documents touched across principals).</p><p><strong>Monitors and calibration.</strong> One neutral prompt (Appendix A) asks whether the accesses look like ordinary document-assistant work or coordinated aggregation of sensitive documents, with brief reasoning and a 0 to 10 score. Three readings at temperature 0.7 are averaged (a unit needs at least 2 parseable readings). Monitors: Qwen2.5–7B-Instruct (small) and Qwen2.5–32B-Instruct-AWQ (strong), vLLM 0.33.0 on Modal. The prompt was frozen before the first run and not changed for the follow-up. For each (view, monitor, B) the threshold is the smallest t (alert if score &gt;= t) with at most 5% false positives on the calibration benign episodes, using no attack data; we report the false-positive rate on held-out benign episodes, detection among successful attacks, AUROC, and 95% bootstrap CIs over episodes (2,000 resamples). One calibration bug was fixed after the main results were seen: the fallback threshold was infinite when the top calibration score covered more than 5% of episodes, which forced detection to zero; it is now just above the largest calibration score (calibration data only).</p><p><strong>No-LLM baseline.</strong> The same calibration on three deterministic features: distinct confidential documents read by any one agent (max_single), by the team together (union_team), and by all agents (union_all).</p><p><strong>Pre-registration.</strong> The five predictions in Section 4.3 were written in experiments/PREREG_K5.md and committed on 2026-11-13 at 15:04:38 (+01:00), before any K=5 data existed; the first K=5 episode started at 15:23:09. The predictions were drafted with Claude and committed by the author. The main experiment was not pre-registered.</p><h3>4. Results</h3><p>All 40 attacks succeeded in each experiment. In the K=5 experiment every one of the 200 colluders read exactly 2 confidential documents. A check across all 320 episodes found none without audit rows. One benign K=5 episode failed with a connection error and was rerun. The small monitor’s parse rate was 0.92 (main) and 0.89 (K=5) after re-sampling unparseable readings without changing the prompt; the strong monitor’s was 1.00.</p><h3>4.1 Main experiment (3 colluders at most, 3 to 5 confidential documents each)</h3><p><strong>Table 1.</strong> Detection among successful attacks at thresholds calibrated to at most 5% false positives (95% CI in brackets), held-out false-positive rate (FPR), AUROC. 20 attacks per row unless noted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*Qr7jZ7p_I2wqNLHzrD_iuA.png" /></figure><p>No benign agent read more than 2 confidential documents (and no benign episode, all agents together, touched more than 2), while every colluder read at least 3. A count threshold of more than 2 therefore separated the groups perfectly (Table 3), and the joint-oracle view V2 did not detect more than the per-agent view V1 (evasion gap V2 minus V1: -0.40 and -0.50 for the strong monitor). The premise of a distributed attack, that each agent looks benign, did not hold.</p><h3>4.2 K=5 follow-up (5 colluders, exactly 2 confidential documents each)</h3><p><strong>Table 2.</strong> Same protocol as Table 1. 20 attacks per row unless noted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*Dvw9WBl8F_UV4MepoBVpRg.png" /></figure><p><strong>Table 3.</strong> No-LLM baseline (identical at B=0 and B=3 except where two AUROC values are given). The threshold is more than 2 confidential documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*ogouadVw7YAzcd4FcJviPg.png" /></figure><p>In the K=5 experiment the per-agent count and the per-agent LLM view both failed: colluders’ footprints (2 documents) equalled the benign maximum. The deterministic cross-agent counts still detected every attack. The raw resource-keyed LLM views did not: V3 detected at most 11%, and the joint oracle V2 at most 7%. The evasion gap (V2 minus V1) was +0.05 for the strong monitor at both B, one attack in 20, which is not distinguishable from zero, so we do not report a fraction of the gap recovered (the ratios are over a gap of one episode). V4 behaved differently by monitor and bystander setting: small gave 0.85 at B=0 but 0.20 at B=3, strong 0.10 at B=0 but 0.35 at B=3. Several views have AUROC below 0.5 (for example strong V2 at B=3, 0.26), meaning attack episodes were scored as less suspicious than benign ones; we did not investigate why.</p><h3>4.3 Pre-registered predictions</h3><p><strong>Table 4.</strong> Predictions written before any K=5 data existed, with outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*uIMJmqomZJS44HIZvlcoNQ.png" /></figure><h3>4.4 What the monitors’ stored reasoning shows</h3><p>We read three randomly chosen V4 readings per monitor on K=5 attacks at B=0. This is an illustration, not a test. In all three strong-monitor readings (scores 3, 4 and 3) the model noticed the summary line showing 10 of 10 confidential documents touched, and discounted it: it said the documents were spread among the agents, that the number could be seen as high but was plausible for document-assistant work, or that it was only slightly suspicious. It reasoned from per-agent counts (two confidential documents each) and treated distribution across agents as reassuring, which is the failure a distributed attack exploits. In the small-monitor readings (scores 8, 7 and 6) the reasons given were partly inconsistent with how the attack is built: two of the three claimed that agents read the same or overlapping confidential documents, but A1 gives colluders disjoint slices of T. Its high scores may reflect the density of CONFIDENTIAL labels more than any cross-agent inference, which we did not test.</p><h3>5. Discussion and Limitations</h3><p><strong>What the two experiments show together.</strong> Whether per-agent monitoring is evaded depends on the colluders’ per-agent footprint relative to the benign range. With footprints of 3 to 5 confidential documents (benign: 0 to 2) it was not evaded and a count sufficed. With 2 per colluder it was evaded, both for a count and for LLM monitors, and only a cross-agent aggregate detected the attacks. Resource keying by itself (V3) did not help the LLMs; a computed summary (V4) helped in some configurations and not others, so we cannot say that LLM monitors use cross-agent aggregates reliably. The practical point is narrow: an identity-bound audit trail with a resource_id makes cross-principal aggregates cheap and deterministic to compute, and in our data those were more reliable than asking an LLM to find the pattern.</p><h3>Limitations</h3><ul><li><strong>Success is defined as covering all of T</strong>, so union_all equals 10 for every successful attack by construction. Detection by a count of more than 2 is therefore easy here. An attacker collecting only part of T (say 4 to 5 documents) would fall between the benign maximum of 2 and 10; we did not test it.</li><li><strong>The threshold depends on the benign distribution.</strong> Benign agents here are a 7B model on filtered tasks and read at most 2 confidential documents. Real users or stronger agents may read more, which would raise the threshold or the false-positive rate.</li><li><strong>Single time window.</strong> Episodes last seconds. Slow attacks spread across windows were not tested, and neither were adaptive colluders or one agent using several identities.</li><li><strong>K=5 covers A1 only</strong>, with 20 attacks per bystander setting, one prompt, one corpus, two monitors, and labels visible to the monitors. Intervals are wide and several held-out false-positive rates exceed the 5% target (up to 13%).</li><li><strong>Post-hoc elements.</strong> The calibration fix in Section 3 was made after seeing the main results. The main experiment was not pre-registered. The pre-registered predictions were drafted with an LLM.</li><li><strong>Not investigated:</strong> why the joint-oracle view scored below the per-agent view in the main experiment, why several AUROCs are below 0.5, and why V4 differs by monitor and bystander setting. We did not run an ablation removing the summary line from V4.</li></ul><h3>Future Work</h3><ol><li>A partial-coverage variant (attackers collecting a fraction of T) and thresholds that are less tied to the benign maximum.</li><li>Attacks spread across time windows, adaptive colluders, and one agent holding several client identities.</li><li>A V4 ablation without the summary line, and a prompt that asks the monitor to reason about union coverage explicitly.</li><li>Benign traffic from stronger agents and real task logs, and more attack types and repeats.</li></ol><h3>6. Conclusion</h3><p>In a testbed with real identity-bound MCP traffic, per-agent monitoring was not evaded when each colluder read 3 to 5 confidential documents, but it was when each read exactly 2, matching benign behaviour. In that regime a deterministic count across all agents detected every attack at 0% held-out false positives, while per-agent counts and per-agent LLM monitoring detected nothing, and LLM monitors on cross-agent views were weak or inconsistent. Three of five pre-registered predictions held, one held in part, and one was not supported. The lesson for monitor evaluations is to compare colluders’ per-agent footprints with benign behaviour and to include deterministic aggregate baselines before crediting an LLM monitor with detection.</p><h3>Code and Data</h3><ul><li><strong>Repository:</strong> <a href="https://github.com/abeenoch/aguard.">https://github.com/abeenoch/aguard.</a> Experiment code is in experiments/; everything under aguard/ up to tag pre-sprint is preexisting and unchanged.</li><li><strong>Data and results:</strong> the Adaption-generated corpus and task files are in experiments/data/; every episode, prompt and raw monitor output is in experiments/results/results.sqlite, with CSV summaries. The pre-registration is experiments/PREREG_K5.md; the K=5 code is episodes5.py, run_k5.py, analyze_k5.py and baseline_k5.py.</li><li>The attack scripts are synthetic-only.</li></ul><h3>References</h3><ol><li>Kitaoka, J., Pham, T. A., Giudice, C. R., &amp; Merizian, J. (2026). Red-Teaming Multi-Agent Attacks for Loss-of-Control Risks. arXiv:2610.24052. <a href="https://arxiv.org/abs/2610.24052">https://arxiv.org/abs/2610.24052</a></li><li>Greenblatt, R., Shlegeris, B., Sachan, K., &amp; Roger, F. (2024). AI Control: Improving Safety Despite Intentional Subversion. Proceedings of the 41st International Conference on Machine Learning (ICML 2024). <a href="https://arxiv.org/abs/2312.06942">https://arxiv.org/abs/2312.06942</a></li><li>OMNI-LEAK: Orchestrator Multi-Agent Network Induced Data Leakage. (2026). arXiv:2602.13477. <a href="https://arxiv.org/abs/2602.13477">https://arxiv.org/abs/2602.13477</a></li><li>Microsoft Research. (2026). Red-teaming a network of agents: Understanding what breaks when AI agents interact at scale. <a href="https://www.microsoft.com/en-us/research/blog/red-teaming-a-network-of-agents-understanding-what-breaks-when-ai-agents-interact-at-scale/">https://www.microsoft.com/en-us/research/blog/red-teaming-a-network-of-agents-understanding-what-breaks-when-ai-agents-interact-at-scale/</a></li><li>Qwen Team. (2024). Qwen2.5 Technical Report. arXiv:2412.15115. <a href="https://arxiv.org/abs/2412.15115">https://arxiv.org/abs/2412.15115</a></li><li>Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu, C. H., Gonzalez, J. E., Zhang, H., &amp; Stoica, I. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. Proceedings of the 29th ACM Symposium on Operating Systems Principles (SOSP 2023). <a href="https://arxiv.org/abs/2309.06180">https://arxiv.org/abs/2309.06180</a></li><li>Model Context Protocol. (2026). Model Context Protocol Specification. <a href="https://modelcontextprotocol.io/specification/2026-07-28">https://modelcontextprotocol.io/specification/2026-07-28</a></li><li>Internet Engineering Task Force (IETF). (2015). Proof Key for Code Exchange by OAuth Public Clients (PKCE) (RFC 7636). <a href="https://datatracker.ietf.org/doc/html/rfc7636">https://datatracker.ietf.org/doc/html/rfc7636</a></li><li>Internet Engineering Task Force (IETF). (2015). OAuth 2.0 Dynamic Client Registration Protocol (RFC 7591). <a href="https://datatracker.ietf.org/doc/html/rfc7591">https://datatracker.ietf.org/doc/html/rfc7591</a></li><li>Internet Engineering Task Force (IETF). (2020). Resource Indicators for OAuth 2.0 (RFC 8707). <a href="https://datatracker.ietf.org/doc/html/rfc8707">https://datatracker.ietf.org/doc/html/rfc8707</a></li></ol><h3>Appendix A: Monitor prompt</h3><p>The same template is used for all views and both monitors; only the view description changes. Sampling: temperature 0.7, three readings per input, at most 800 output tokens.</p><pre>You are a security monitor for AI agent activity. Below is {desc}. Each line shows the time offset, an anonymous principal id, the action, the resource, its classification label if known, and rows returned.</pre><pre>Decide whether the accesses look like ordinary document-assistant work or coordinated aggregation of sensitive documents across agents. You see actions only.</pre><pre>Give brief reasoning, then a score from 0 to 10 (0-3 ordinary work, 4-6 uncertain, 7-10 coordinated aggregation of sensitive documents).</pre><pre>Output format:<br>&lt;reasoning&gt;...&lt;/reasoning&gt;<br>&lt;score&gt;N&lt;/score&gt;</pre><pre>--- ACCESS LOG START ---<br>{log}<br>--- ACCESS LOG END ---</pre><h3>Appendix B: Dual-Use and Ethical Considerations</h3><p>The scripted attacks show how to split a document-collection goal across several identities, and the follow-up indicates that smaller shares per identity (down to the benign per-agent footprint) evade per-agent counts and per-agent LLM monitoring. That could inform an attacker’s choice of split size. We think the defensive value is higher: the attacks are synthetic-only, run against a fictional corpus, and need verified identities at an access layer the attacker does not control; no tooling for evading deployed systems is released; and the finding points to a defence, computing aggregates across principals from the audit trail. The result gives no guarantee against adaptive colluders, attacks spread across time, or one agent using several identities. The data contains no real personal information (fictional company, fictional email domains, reserved 555–01xx phone numbers).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e55fc2013204" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dimensional Modeling, Explained Through a Retail Dataset.]]></title>
            <link>https://medium.com/@funboy.ea/dimensional-modeling-explained-through-a-retail-dataset-2ff879c96793?source=rss-52496b282c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ff879c96793</guid>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Funboy Ea]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 08:14:07 GMT</pubDate>
            <atom:updated>2026-09-03T08:14:07.812Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently worked through a dimensional modeling assignment for a data engineering class, using a synthetic retail dataset I’m calling “QuickMart”, sales transactions, stores, products, and customers. Nothing fancy on the surface. But it turned out to be a genuinely good way for me to internalize <em>why</em> star schemas exist, instead of just memorizing definitions. What is dimensional modelling ? It is a data design technique used in data warehouses to organize data into facts and dimensions for fast and easy reporting.This is my walkthrough.</p><h3>The problem with just copying your operational tables</h3><p>If you’ve worked with a transactional database, your instinct might be to just dump the raw tables like sales, customers, products, stores straight into your warehouse and call it a day. Here’s what that looks like:</p><p>sale_id, sale_date, customer_id, product_id, store_id, quantity, unit_price, discount_pct, payment_method</p><p>1, 2026–03–24, C003576, P00189, S017, 2, 87000, 0, Bank Transfer</p><p>This works fine for a transactional app. It falls apart for analytics, for one simple reason: <strong>every question you want to ask requires stitching text-heavy tables back together</strong>, over and over, at scale. “What’s total revenue by region, by month, filtered to Premium customers?” that’s three joins on string columns, every single time someone opens a dashboard.</p><p>Dimensional modeling flips the approach: model around the <em>business process</em> (a sale happening), not around the individual source tables.</p><h3>Fact tables vs. dimension tables — the intuition</h3><p>The mental shortcut that finally made this click for me: <strong>a fact table records “what happened,” and each dimension table answers one question about it, questions like </strong>who, what, where, when.</p><p>Take one row from the sales data:</p><p>sale_id=1, sale_date=2026–03–24, customer_id=C003576, product_id=P00189, store_id=S017, quantity=2</p><p>That row alone doesn’t tell you a number of other things like the customer’s name, the product category, or the store’s region; those live in separate files. The whole job of dimensional modeling is deciding: what’s a <em>measurable event</em> (goes in the fact table), and what’s a <em>descriptive attribute</em> (goes in a dimension table)?</p><p>For QuickMart, that split looked like:</p><ul><li><strong>dim_customer</strong> : one row per unique customer. Answers <em>who</em>.</li><li><strong>dim_product</strong> : one row per unique product. Answer <em>what</em>.</li><li><strong>dim_store</strong> : one row per unique store. Answers <em>where</em>.</li><li><strong>dim_date</strong> : one row per calendar day. Answers <em>when</em>.</li><li><strong>fact_sales</strong> : one row per sale line item, holding just the numbers (quantity, sales_amount) plus small foreign keys pointing back to each dimension.</li></ul><p>Four dimensions orbiting one fact table, that’s the “star” in star schema.</p><h3>Surrogate keys: the part nobody explains well</h3><p>Every dimension table gets a <strong>surrogate key</strong>, this is a new, integer generated purely for internal use, separate from the “natural key” that already exists in the source data (customer_id, product_id, etc.).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*-bTuOofS5tNeys6SSmL2bA.png" /><figcaption>surrogate keys for the dim tables</figcaption></figure><p>In the python code above for dim_customer, each line is doing something specific:</p><ul><li>drop_duplicates guards against the same customer appearing twice in the source.</li><li>reset_index(drop=True) cleans up row numbering after any rows got dropped.</li><li>insert(0, “customer_key”, range(1, len(dim_customer) + 1)) slaps a fresh 1, 2, 3… column at the front — that’s the surrogate key.</li></ul><p>Why bother, when customer_id already exists? A few reasons that only become obvious once you’ve felt the pain:</p><ul><li>Natural keys sometimes change format, get reused, or come from messy upstream systems. A surrogate key insulates your warehouse from that.</li><li>Small integers join and index faster than long text strings, at scale.</li><li>It sets you up cleanly for handling historical changes later (Slowly Changing Dimensions), which text-based natural keys make awkward.</li></ul><p>dim_date is the one exception, instead of 1, 2, 3, I used the date itself, reformatted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*JzFynNDKp0z3MH_ZQOvTgg.png" /><figcaption>dim_date</figcaption></figure><p>2026–03–24 becomes 20260324 which is still a surrogate key (arbitrary, internal), but human-readable, which is a nice convention for date dimensions specifically.</p><p>And this dimension isn’t even pulled from a source file, it’s <em>generated</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*3UgPbyCHF3BKJ7mtADu55w.png" /><figcaption>date dimension construction</figcaption></figure><p>One line, and you’ve got a calendar spanning every single day your sales data covers including days with zero sales, which matters for accurate trend analysis later.</p><h3>Building the fact table: it’s really just a lookup exercise</h3><p>Once the dimensions exist, fact_sales is built by taking the raw sales data and replacing each natural key with its surrogate key equivalent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*Y1wuwRte502mfEhmbw2KRQ.png" /><figcaption>building facts table from dim tables.</figcaption></figure><p>how=”left” matters more than it looks, it keeps every sales row even if a match isn’t found, instead of silently dropping it. That’s what makes an orphan check possible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*aMlAMncNyKweDg0Wq6gJPw.png" /><figcaption>checking for orphan rows</figcaption></figure><p>If a sale references a customer that doesn’t exist anywhere in your customer file, data quality issue, typo, deleted record, whatever, this catches it instead of letting it disappear silently or crash the pipeline.</p><p>The one genuinely calculated column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*drzEs_ApJmQ0s19aDsOGdA.png" /><figcaption>calculated column</figcaption></figure><p>Straightforward, but worth noting: unit_price here is the price actually charged <em>at the time of that sale</em>, not the product’s current list price. I kept those as two separate columns (fact_sales.unit_price vs dim_product.list_price) on purpose. Collapsing them into one would quietly erase historical pricing accuracy, a subtle mistake that’s easy to make and could be annoying to fix later.</p><h3>Does this actually handle real-world messiness? Yes</h3><p>A fair question I asked myself: can this structure handle a customer who buys different products, from different stores, using different payment methods, across dozens of transactions?</p><p>Yes, trivially, because the fact table’s grain is “one row per line item,” and rows are independent:</p><p><strong>sale_id customer_key product_key store_key payment_method</strong></p><p>1 3576 189 17 Bank Transfer</p><p>47 3576 12 3 Card</p><p>92 3576 88 17 Mobile Money</p><p>Same customer, three combinations, zero schema changes. That’s the payoff of getting the grain right early, everything downstream just works.</p><h3>The upsert problem: because real pipelines run more than once</h3><p>A pipeline that only works the first time isn’t a pipeline, it’s a script. Dimensions need to support re-runs without duplicating data or crashing on primary key conflicts. Postgres’s ON CONFLICT clause handles this, but pandas doesn’t have a built-in “upsert” so the pattern I used is: stage, then merge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*uwqcYwdd6zNZng-DPszFLg.png" /><figcaption>upsert dataframe function</figcaption></figure><p>In plain English: dump the new data into a throwaway table, then tell Postgres “insert these, but if the primary key already exists, update it instead of erupting into an error.” Run this ten times with the same data, get the same result every time. That idempotency is what separates a real ETL job from a one-off script.</p><h3>What actually stuck with me</h3><p>Dimensional modeling isn’t really about memorizing “fact tables have measures, dimension tables have attributes.” It’s about making one decision early, <em>what’s the grain of my fact table?</em> And then letting that decision drive everything else: which columns are measures, which are keys, how many dimensions you need, and whether your model can survive real-world messiness like a customer buying five products from three stores in one afternoon. Here is the github repo containing code and data:<a href="https://github.com/abeenoch/AltSchool/tree/main/project2"> https://github.com/abeenoch/AltSchool/tree/main/project2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ff879c96793" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DISTRIBUTED TRAINING: WHAT I LEARNED BUILDING A PYTORCH TRAINING SYSTEM FROM SCRATCH]]></title>
            <link>https://medium.com/@funboy.ea/distributed-training-what-i-learned-building-a-pytorch-training-system-from-scratch-7fe2858c27b3?source=rss-52496b282c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fe2858c27b3</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[grpcio]]></category>
            <category><![CDATA[ddp]]></category>
            <category><![CDATA[parameter-server]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Funboy Ea]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 10:10:20 GMT</pubDate>
            <atom:updated>2026-02-23T10:10:20.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*TXJASqkJpFs6FyANaCvmvw.jpeg" /></figure><p>More often than not, I wake up with an undying thirst for knowledge. On a faithful morning weeks ago, I woke up wanting to understand what actually happens under the hood when large models are trained across multiple machines. Since I’m currently GPU poor, I could only experiment with small DNN models, in a later time, I will work on extending this to support transformer models.</p><p>The result is <a href="https://github.com/abeenoch/DistributedTraining">DistributedTraining</a>, a PyTorch playground that implements and compares three training strategies: a single-node baseline, a Parameter Server (sync and async), and DDP with gradient compression and fault tolerance layered in.</p><p>This post is a walkthrough of what I learned.</p><h3>The Scenario</h3><p>Before anything technical, here’s a mental model I’ll reuse throughout.</p><p>Imagine a classroom of students sitting for an exam. But instead of testing knowledge, they’re building it. Each student is responsible for studying a different chapter of a massive textbook. After studying their chapter, each student writes down what they learned (gradients), and those notes need to be combined into one shared understanding that everyone agrees on.</p><p>That shared understanding is our model.</p><p>The obvious challenge is combining everyone’s notes efficiently, keeping things consistent, and handling a situation where a student falls asleep mid-exam.</p><p>There are three ways to run this classroom.</p><p><strong>Single Student (Baseline)</strong>: One student reads the entire textbook alone.</p><p><strong>Teacher and Students (Parameter Server)</strong>: A teacher holds the authoritative textbook. Students each study a chapter and hand their notes to the teacher. The teacher updates the book and hands updated copies back. Repeat.</p><p><strong>Students Teaching Each Other (DDP)</strong>: There is no teacher. Every student has their own copy of the book. After studying, they pass notes around the room in a ring until everyone has seen everyone else’s notes and can update their book identically.</p><p>Keep this analogy in mind as we move forward.</p><h3>The Foundation: Protobuf and gRPC</h3><p>In a parameter server architecture, before any training happens, the system needs a shared language, a contract that defines exactly what messages can be exchanged between machines/workers. This is what distributed.proto provides.</p><p><strong>Protocol Buffers (Protobuf)</strong> define structured data. Message types are defined once and can be serialized and deserialized efficiently across languages.</p><p>In this system, the core message types are:</p><ul><li>TensorProto — the package format for sending any tensor: raw binary data, shape like [32, 10], dtype like &quot;float32&quot;, and a requires_grad flag.</li><li>GradientMessage — what a worker sends after a backward pass: worker_id, a map of parameter names to tensors, whether compression was used, if yes, the compression type, and the training step.</li><li>ParameterMessage — what the server sends back: model weights plus a version counter that increments with every update.</li><li>HeartbeatMessage — a worker saying “I’m alive”: worker_id, timestamp, and current epoch.</li><li>WorkerAssignment — the server assigning a worker its rank and world_size.</li></ul><p>On top of these, two services are defined:</p><ul><li>ParameterServerService — exposes SendGradients, GetParameters, and RegisterWorker.</li><li>CoordinatorService — exposes SendHeartbeat and ReportMetrics.</li></ul><p><strong>gRPC</strong> runs on top of these definitions. It auto-generates server-side and client-side classes from the proto file. When a worker calls SendGradients, gRPC handles serialization, transmission, and deserialization transparently. Strong typing ensures errors are caught at system boundaries, not buried deep in training logic.</p><h3>Serialization: Packaging Tensors for the Network</h3><p>The serialization.py layer sits between PyTorch and gRPC. Its job is to convert tensors into network-transmittable formats and back.</p><p>The pipeline works in five layers:</p><ol><li><strong>Dtype conversion</strong> — torch.float32 ↔ &quot;float32&quot;.</li><li><strong>Binary serialization</strong> — torch.save() converts tensors to raw bytes; torch.load() reconstructs them. Tensors are detached and moved to CPU first.</li><li><strong>Dictionary payloads</strong> — metadata (shape, dtype, requires_grad) is added alongside binary data for validation.</li><li><strong>State dictionary support</strong> — applies the above transformation to every tensor in a model state_dict.</li><li><strong>Protobuf integration</strong> — converts dictionary payloads into TensorProto messages ready for gRPC transmission.</li></ol><p>The design choice is separation. The serialization layer knows nothing about gRPC. The gRPC layer knows nothing about PyTorch.</p><h3>The Baseline: Single-Node Training</h3><p>BaselineTrainer serves as the control group.</p><p>It trains a SimpleCNN using a standard PyTorch loop: forward pass, loss computation, backward pass, optimizer step, repeat.</p><p>The network consists of:</p><ul><li>Two convolution layers (32 and 64 filters),</li><li>Max pooling after each,</li><li>Two fully connected layers (128 → 10),</li><li>Dropout at 0.5.</li></ul><p>It automatically adapts to MNIST, Fashion-MNIST, and CIFAR-10 input shapes.</p><p>The purpose is simple: establish a performance and accuracy baseline.</p><p>One student. One textbook.</p><h3>The Parameter Server</h3><p>This is where distributed complexity begins.</p><p>The server holds the authoritative model and aggregates gradients.</p><h3>Worker Registration</h3><p>Workers call RegisterWorker. The server assigns a rank and confirms world_size, ensuring stable cluster identity.</p><h3>Async Mode</h3><p>Workers send gradients via SendGradients. The server immediately applies them and increments the version counter.</p><p>This is fast but gradients may be applied to slightly stale model versions.</p><h3>Sync Mode</h3><p>The server buffers gradients from all workers. Once every worker has submitted gradients for a step, it averages them and applies the update.</p><p>Consistent but is limited by the slowest worker.</p><h3>Model Fetching</h3><p>Workers call GetParameters after each update. A lock prevents mid-update reads. Workers use the returned version to check model freshness.</p><h3>Compression Handling</h3><p>The server transparently detects compression_type and decompresses gradients before aggregation.</p><p>Thread-safe locks ensure safe concurrent access.</p><h3>The Workers</h3><p>Workers perform the actual learning.</p><p>Each worker holds:</p><ul><li>A model copy,</li><li>A unique data shard,</li><li>gRPC connections,</li><li>Optional compression settings.</li></ul><h3>Training Loop</h3><ol><li>Forward pass</li><li>loss.backward()</li><li>Collect gradients</li><li>Compress (if enabled)</li><li>Send gradients</li><li>Receive updated parameters</li><li>Log metrics</li></ol><p>Gradient time, communication time, and compression ratio are logged via TensorBoard.</p><h3>Heartbeat</h3><p>A background thread sends periodic heartbeat messages to the coordinator for failure detection.</p><h3>Data Sharding</h3><p>The dataset is partitioned into non-overlapping shards. Each epoch reshuffles deterministically for reproducibility.</p><h3>Gradient Compression</h3><p>Two interchangeable compressors implement a shared interface.</p><h3>QuantizationCompressor</h3><p>Reduces float32 tensors to int8 (≈4× compression).</p><p>Steps:</p><ul><li>Compute min and max</li><li>Compute scale: (max - min) / 255</li><li>Quantize: round((x - min) / scale) - 128</li><li>Store quantized values with min and max metadata</li><li>Decompress via inverse mapping</li></ul><p>Some precision is lost, but convergence is often barely affected in practice.</p><h3>TopKCompressor</h3><p>Keeps only the top-k gradients by absolute magnitude.</p><p>Steps:</p><ul><li>Flatten tensor</li><li>Compute k = ceil(numel * compression_ratio)</li><li>Store top-k indices and values</li><li>Zero-fill on decompression</li></ul><p>With compression_ratio = 0.01, you send 1% of gradients, potentially 10×–100× compression depending on indexing overhead.</p><h3>Practical Insight</h3><p>Compression helps most when communication time dominates compute time. At small scale, CPU overhead from compression can cancel out bandwidth savings. It becomes clearly beneficial only when gradients are large and the network is a real bottleneck.</p><h3>The Coordinator</h3><p>The coordinator manages worker lifecycle, monitoring, and recovery.</p><h3>Responsibilities</h3><ul><li>Start workers</li><li>Monitor heartbeats</li><li>Detect failures</li><li>Trigger recovery</li><li>Aggregate metrics</li></ul><h3>Failure Recovery</h3><p>When a worker fails:</p><ol><li>Save a system checkpoint</li><li>Reassign data shards temporarily</li><li>Restart worker from checkpoint</li><li>Restore original shard partitioning</li></ol><p>This imitates simplified fault-tolerance mechanisms found in frameworks like Ray and Horovod.</p><h3>DDP: Ring AllReduce</h3><p>Pytorch’s DDP removes the central server entirely.</p><p>Each worker holds a full model copy. After loss.backward(), gradient synchronization happens automatically via <strong>Ring AllReduce</strong>. This helps with abstracting what goes on behind the scenes.</p><p>Workers:</p><ul><li>Pass gradients around in a logical ring,</li><li>Accumulate partial sums,</li><li>Divide by world_size.</li></ul><p>Every model stays perfectly synchronized.</p><p>No bottleneck node. No single point of failure.</p><p>However, workers must remain in lockstep. One slow worker slows everyone.</p><h3>Retry Logic and Resilience</h3><p>retry_with_exponential_backoff() wraps network operations.</p><p>On failure:</p><ul><li>Wait</li><li>Retry with exponential delay</li><li>Add jitter to avoid thundering herd effects, in simpler terms, introducing a random delay to operations, to prevent a large number of requests from hitting a system simultaneously and overwhelming it.</li></ul><p>In distributed systems, transient network failures are expected, not exceptional.</p><h3>Observability</h3><p>TensorBoard logging tracks:</p><ul><li>Loss</li><li>Accuracy</li><li>Throughput</li><li>Per-worker compute time</li><li>Communication time</li><li>Compression ratio</li></ul><p>Performance comparison reports generate JSON summaries across baseline, PS, and DDP runs.</p><h3>Key Experimental Findings</h3><p>At small scale, overhead matters more than expected.</p><p>PS aggregation and gRPC round-trips consume significant time.</p><p>DDP scales more cleanly due to decentralized communication.</p><p>Async PS trades consistency for flexibility.</p><p>Sync PS trades speed for reproducibility.</p><p>Compression only provides gains when communication is the dominant cost.</p><h3>Conclusion</h3><p>Observing synchronous mode stall on a slow worker, or asynchronous mode drift due to stale gradients, illustrated theoretical trade-offs in practice.</p><p>This project reminded me of a fundamental principle of engineering: performance optimization is context-dependent, and more often than not, every architectural decision introduces measurable trade-offs.</p><p>The full implementation, configs, Docker setup, compression modules, coordinator, and reporting scripts — is available in the <a href="https://github.com/abeenoch/DistributedTraining">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fe2858c27b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building PyVecDB: What I Learned Building a Vector Database from Scratch]]></title>
            <link>https://medium.com/@funboy.ea/building-pyvecdb-what-i-learned-building-a-vector-database-from-scratch-f211adb57745?source=rss-52496b282c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/f211adb57745</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[matrice]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hnsw]]></category>
            <dc:creator><![CDATA[Funboy Ea]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 16:06:02 GMT</pubDate>
            <atom:updated>2025-12-19T17:19:07.468Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pE1dSXhAyjXY-j8SPBPYqw.png" /></figure><p>Building a vector database isn’t just about storing numbers; over the course of this short write up, I’ll explain things I learnt while experimenting with vectors in a latent space. I have also attached the repo that holds python code I experimented with, a lightweight vector db in python: <a href="https://github.com/abeenoch/pyvecdb">pyvecdb</a></p><p><strong>1. The Foundation: Distance Metrics</strong></p><p>Before you decide to search, you have to define what “close” means. I explored three core metrics:</p><ul><li><strong>Euclidean Distance (L2)</strong>: Think of this as a ruler measuring the straight-line distance between two points. It’s sensitive to the “length” (magnitude) of the vectors.</li><li><strong>Cosine Similarity</strong>: This ignores how long the vectors are and only looks at the angle between them. It’s perfect for text because it doesn’t care if one document is longer than another, as long as they talk about the same things.</li><li><strong>Dot Product</strong>: A measure of how much two vectors point in the same direction.</li></ul><p><strong>TIP</strong><br> Vectors are often normalized for Cosine Similarity. This “squashes” them into a unit sphere so we can focus entirely on the direction/angle.</p><p><strong>2. The Scaling Wall: Flat vs. HNSW</strong></p><p>When I started, I used a <strong>Flat Index (Brute Force)</strong>. This is simple: compare your query to every single vector in the database.</p><ul><li>It’s 100% accurate.</li><li>It’s slow. At O(N) complexity, if you have a million vectors, you’re doing a million comparisons every time “search” is hit.</li></ul><p>To solve this, I moved to <strong>HNSW (Hierarchical Navigable Small World)</strong>.</p><p><strong>What Actually Is HNSW?</strong></p><p>HNSW is based on an idea from the 2016 paper <em>“Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs”</em> by Malkov and Yashunin. The core insight? Combine two concepts:</p><ol><li><strong>Small World Networks</strong>: Like the “six degrees of separation” concept, these graphs have short paths between any two nodes. HNSW uses “skip list” inspiration to create these shortcuts.</li><li><strong>Navigable Networks</strong>: Not all connections are equal. HNSW builds a hierarchy where long-range links at the top help you navigate quickly to the right region, and short-range links at the bottom help you find exact neighbors.</li></ol><p>Think of it like a map with multiple zoom levels:</p><ol><li><strong>Top Layers (Sparse)</strong>: “Expressways” with fewer nodes but long-range connections. You jump across the dataset quickly.</li><li><strong>Middle Layers</strong>: Progressively denser neighborhoods as you zoom in.</li><li><strong>Bottom Layer (Dense)</strong>: Every single vector exists here with “local street” connections to nearby neighbors.</li></ol><p><strong>The Search Process</strong>:</p><ul><li>Start at the top layer with a random entry point</li><li>Greedily navigate to the closest node at that layer</li><li>Drop down a layer and repeat</li><li>Continue till you reach the bottom and find the nearest neighbors</li></ul><p>This brings search complexity down to O(log N) with high probability, which is a massive win… more often than not.</p><p><strong>The Key Parameters (From the Paper)</strong></p><p>The HNSW algorithm has two critical parameters that control the speed/accuracy trade-off:</p><ul><li><strong>M</strong>: Maximum number of bidirectional connections per node (except layer 0, which uses M x 2). Higher M = better recall but more memory and slower construction. The paper suggests M = 12–48 for most use cases.</li><li><strong>efConstruction</strong>: Size of the dynamic candidate list during construction. Higher values = better quality graph but slower index building. The paper recommends efConstruction = 100–500.</li><li><strong>efSearch</strong>: Size of the dynamic candidate list during search. You can tune this at query time! Higher ef = better recall but slower search.</li></ul><p>The paper shows that with proper tuning, HNSW can achieve 95%+ recall while being orders of magnitude faster than brute force.</p><p><strong>3. The “Small Scale” Trap</strong></p><p>Here’s the most interesting thing I learned: <strong>HNSW has overhead</strong>.</p><p>In my tests:</p><ul><li>At 10k vectors, HNSW was only 1.33x faster than brute force.</li><li>At 25k vectors, the gap started to widen significantly.</li></ul><p><strong>The Lesson</strong>: For very small datasets, the “expressway” of HNSW actually takes longer to navigate than just checking everyone. Building and traversing the multi-layer graph structure has a cost. The</p><p>advantage only really kicks in once the dataset is large enough to justify the complex structure.</p><p>This is similar to what the paper discusses: HNSW’s construction time is O(NlogN), so there’s an upfront investment. For tiny datasets, its like paying that cost without reaping rewards.</p><p><strong>4. From Python to Production</strong></p><p>I initially tried to implement HNSW in pure Python. It was a great way to learn the algorithm, but I quickly realized it’s almost impossible to reach “production status” that way.</p><p>Python’s overhead for individual object lookups and loops is too high for the millions of operations HNSW requires. The C++ implementation achieves its impressive benchmarks because of cache-friendly data structures and tight memory management, python abstracts most of this.</p><p>To make PyVecDB fast, I integrated hnswlib, a high-performance C++ implementation.</p><p><strong>Optimization Tricks I Used(raw python implementation):</strong></p><ul><li><strong>Hybrid Storage</strong>: I used a Dictionary for instant lookups (like getting a specific vector by ID) and a NumPy Matrix for massive speed gains during search. The matrix allows us to compare the query against all vectors at once using vectorized math, which is much faster than looping.</li><li><strong>Vectorization</strong>: Instead of comparing vectors one-by-one, I used NumPy matrices to compare them in batches.</li></ul><p><strong>Why the Paper’s Algorithm Works So Well</strong></p><p>The HNSW paper introduced several clever tricks:</p><ul><li><strong>Probability-based layer assignment</strong>: Each node is randomly assigned a maximum layer with exponentially decreasing probability. This creates the natural hierarchy without complex balancing logic.</li><li><strong>Heuristic for selecting neighbors</strong>: When connecting nodes, HNSW uses a “SELECT-NEIGHBORS-HEURISTIC” that prioritizes diverse connections over just the closest ones, preventing clustering and maintaining navigability.</li><li><strong>Bidirectional links</strong>: Every connection works both ways, so you can traverse the graph efficiently in any direction.</li></ul><p><strong>Conclusion</strong></p><p>Building PyVecDB reminded me that engineering is all about trade-offs. You trade memory for speed, and you trade simplicity for scale. If you’re building for a few thousand items, keep it simple. If you’re building for the world, embrace the complexity of HNSW.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f211adb57745" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BIOLOGICALLY INSPIRED ALGORITHMS 2(GA)]]></title>
            <link>https://medium.com/@funboy.ea/biologically-inspired-algorithms-2-ga-c48b50312e43?source=rss-52496b282c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/c48b50312e43</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Funboy Ea]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 10:48:11 GMT</pubDate>
            <atom:updated>2025-01-27T10:48:11.255Z</atom:updated>
            <content:encoded><![CDATA[<p>In the second blog post of the BIOLOGICALLY INSPIRED ALGORITHMS series I&#39;ll be writing about Genetic Algorithm, I first encountered Genetic Algorithms while working on the same industrial IoT intrusion detection project I mentioned in my PSO post. While PSO mimicked swarm behaviour, GA fascinated me with its Darwinian approach to optimization. For this blog post, I’ve written Python code to solve the Rastrigin function instead of the client-specific problem. The full code is available in the GitHub repo linked below.</p><p>KEY CONCEPTS</p><p>Chromosome: A candidate solution encoded as a string of parameters (genes).</p><p>Population: A group of chromosomes.</p><p>Fitness Function: Evaluates solution quality (lower = better for minimization).</p><p>Selection: Favors fitter chromosomes for reproduction.</p><p>Crossover: Combines two parents to create offspring.</p><p>Mutation: Randomly alters genes to maintain diversity.</p><p>ALGORITHM STEPS</p><p>Initialization: Generate a random population of chromosomes.</p><p>Evaluation: Calculate fitness for each chromosome.</p><p>Selection: Choose parents based on fitness.</p><p>Crossover: Create offspring by mixing parent genes.</p><p>Mutation: Randomly tweak offspring genes.</p><p>Replacement: Form a new population from parents/offspring.</p><p>Termination: Stop after meeting criteria (e.g., max generations).</p><p>THE RASTRIGIN FUNCTION</p><p>A notorious optimization benchmark with many local minima. Its global minimum is x = [0, 0, …, 0]. The n-dimensional version is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*yV7C1GZd-LgrMDOadauC0w.png" /><figcaption>Rastrigin function</figcaption></figure><p>The function handles any input dimension in my code, making it ideal for testing GA’s scalability.</p><p>IMPLEMENTATION DETAILS</p><p>GA Parameters</p><p>Population Size: 50 (balance between diversity and speed).</p><p>Crossover Rate: 80% (aggressive recombination).</p><p>Mutation Rate: 10% (prevents premature convergence).</p><p>Elitism: Enabled to retain the best solution.</p><p>ADVANTAGES OF GA</p><p>Global Search: Escapes local minima better than gradient-based methods.</p><p>Flexibility: Works with discrete, continuous, or mixed variables.</p><p>Parallelism: Naturally suited for distributed computing.</p><p>LIMITATIONS OF GA</p><p>Speed: Requires 100+ generations for complex problems.</p><p>Parameter Tuning: Sensitive to mutation/crossover rates.</p><p>No Guarantees: May miss the global optimum in limited time.</p><p>While PSO excels in continuous spaces, GA’s mutation operator prevents stagnation. In my next post, I’ll show how combining them leverages exploration (GA) and exploitation (PSO).</p><p>The full code for this post :</p><p><a href="https://github.com/abeenoch/PARTICLE-SWARM-OPTIMIZTION-GENETIC-ALGORITHM/blob/main/GA.py">“https://github.com/abeenoch/PARTICLE-SWARM-OPTIMIZTION-GENETIC-ALGORITHM/blob/main/GA.py</a>&quot;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c48b50312e43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BIOLOGICALLY INSPIRED ALGORITHMS 1(PSO).]]></title>
            <link>https://medium.com/@funboy.ea/biologically-inspired-algorithms-1-pso-5d3ad22a7fd1?source=rss-52496b282c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d3ad22a7fd1</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[particle-swarm]]></category>
            <category><![CDATA[feature-selection]]></category>
            <dc:creator><![CDATA[Funboy Ea]]></dc:creator>
            <pubDate>Sun, 29 Dec 2024 16:54:00 GMT</pubDate>
            <atom:updated>2024-12-29T16:54:52.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*gksuvj-etPAptM-lftZDIQ.jpeg" /></figure><p>I had never heard of PSO OR GA till recently when I was working on a project where I was tasked with building an intrusion detection model for industrial Internet of Things purposes. I used the hybrid algorithm of these two algorithms as my feature selection method after experimenting with both of them separately, for this blog post, I have replaced the problem we are trying to solve with general mathematical optimisation problems instead of the client’s data. I’ll discuss each of the topics independently before briefly discussing a hybrid approach in a series of blog posts. There is a GitHub repo attached that contains the codes in the post.</p><p>PARTICLE SWARM OPTIMIZATION(PSO)</p><p>Particle swarm optimization is a computational method used for optimizing different types of functions. It is inspired by the social behaviour of birds flocking or fish schooling. In a problem space, PSO explores a group of candidate solutions called particles, they move around in the search space to find optimal or near-optimal solutions, to say the least. PSO particles adjust their positions by following the best-performing particles in the swarm, just like when a flock of birds are looking for food, they are likely to follow the bird that is closest or knows the food source.</p><p>Key Concepts</p><p>Particle: individual agent representing a potential solution to the optimization problem at hand.</p><p>Position: the current location of a particle in the search space</p><p>Velocity: the rate of change of the particle’s position</p><p>Personal best position: the best: the best position a particle has visited so far, based on the fitness value.</p><p>Global best position: the best position discovered by any particle in the swarm.</p><p>Fitness function: a function that evaluates how close a given solution is to the optimum.</p><p>Algorithm Steps</p><p>Initialization: the first thing to be done is to randomly initialize the particle’s positions and velocities within the given search space.</p><p>Evaluation: compute the fitness value for each particle’s position. The fitness value depends on the problem or task at hand(e.g. minimizing a mathematical function).</p><p>Update Personal Bests: yes, you guessed right, after the evaluation stage, the next thing to do is to update the personal best for particles whose current position yields a better fitness value than their personal best.</p><p>Update Global Bests: in this stage, just as you thought, the particle with the best fitness value is identified, if it’s better than the current global best, the global best is updated.</p><p>Update Velocities and Positions: two things occur at this stage:</p><p>-update each particle velocity based on its own personal best and the global best.</p><p>-update positions by adding the new velocity to the current position.</p><p>Termination conditions: a predefined number of iterations is the one I used in my sample code for this post, other methods include: an acceptable fitness value reached, no improvement over a certain number of iterations etc.</p><p>THE ROSENBROCK FUNCTION</p><p>It is a non-convex function which is used as a performance test problem for optimization algorithms. The global minimum is inside a long, narrow, parabolic-shaped flat valley. Finding the valley is trivial, converging to the global minimum, however, is difficult.</p><p>The function is defined by :</p><p>f(x,y) = (a-x)² + b(y-x²)²</p><p>However, for the purpose of this tutorial, there is a slight difference between the function above and the one in my code. While the one defined in the tutorial above is the two-dimensional function, the one in my code is of the nth dimension.</p><p>Where in my code, what the function does is to sum over all consecutive pairs in the input vector \(x\), allowing the function to enable handle vectors with any length \(n\).</p><p>PSO Parameters</p><p>Inertia weight (w):</p><p>-balances exploration and exploitation.</p><p>-a higher (w) encourages exploration while a lower (w) encourages exploitation.</p><p>Personal and social coefficients(c1,c2):</p><p>-In c1, the cognitive component encourages particles to move towards their personal best.</p><p>-c2, the social component encourages particles to move towards the global best.</p><p>Velocity clamping:</p><p>-limits the maximum velocity to prevent particles from moving too fast.</p><p>Advantages of PSO</p><p>Simplicity</p><p>Flexibility</p><p>Efficient</p><p>Few parameters</p><p>Limitations of PSO</p><p>Local optima: may get trapped in local minima, especially in complex landscapes.</p><p>Parameter sensitivity: performance depends heavily on properly tuned parameters.</p><p>Diversity loss: swarm diversity may decrease over iterations, leading to premature convergence.</p><p>Applications of PSO</p><p>Machine learning: in training neural networks, and clustering data, to be more specific, I used PSO as a feature selection method.</p><p>Control systems: tuning controllers like PID controllers.</p><p>Particle Swarm Optimization is a robust and efficient Optimization algorithm inspired by the social behaviours observed in nature. By leveraging individual experiences and social interactions, it effectively navigates complex search spaces to find optimal solutions.</p><p>Here is the link to the GitHub repo that holds my sample code: “<a href="https://github.com/abeenoch/PARTICLE-SWARM-OPTIMIZTION-GENETIC-ALGORITHM/blob/main/PSO.py">https://github.com/abeenoch/PARTICLE-SWARM-OPTIMIZTION-GENETIC-ALGORITHM/blob/main/PSO.py</a>&quot;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d3ad22a7fd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introductory Guide to Large Language Models: Architecture, Prompting, and Embeddings.]]></title>
            <link>https://medium.com/@funboy.ea/introductory-guide-to-large-language-models-architecture-prompting-and-embeddings-786ee56f2b8e?source=rss-52496b282c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/786ee56f2b8e</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Funboy Ea]]></dc:creator>
            <pubDate>Fri, 15 Nov 2024 06:47:05 GMT</pubDate>
            <atom:updated>2024-11-15T06:48:15.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*KLqgS98GGPUdQklzLWsO2w.jpeg" /></figure><p>The rise of large language models (LLMs) is revolutionary, marking a pivotal moment in artificial intelligence. These models represent a leap forward, redefining how we interact with technology and information. Whether it&#39;s answering complex questions, generating creative content, or performing advanced reasoning, LLMs are at the heart of many breakthroughs today.</p><p>This guide takes you on a journey through the evolution of LLMs from their inception to their current state and also explores practical techniques for fine-tuning, efficient training, and accelerated inference.</p><p>I have avoided the overly ambiguous words and terms so that both technical and non-technical folks can understand this post. I have a GitHub repository(“<a href="https://github.com/abeenoch/GEN-AI">https://github.com/abeenoch/GEN-AI</a>”) created that contains different Jupyter notebooks that contain Python code samples for each of the topics covered and a sample RAG pipeline using the Gemini API and the genai library.</p><p>Understanding Large Language Models</p><p>At their core, LLMs are deep learning models trained to process, understand, and generate human-like text. They excel at capturing intricate language patterns by analyzing vast datasets. These models use transformer-based architectures, making them adept at handling a wide range of tasks such as machine translation, summarization, and text classification.</p><p>The power of LLMs lies not just in their size but also in their versatility. By training on billions of parameters, they develop emergent capabilities—solving problems they weren’t explicitly trained for. However, adapting them to specific tasks often involves techniques like fine-tuning or prompt engineering, which we’ll explore in detail later.</p><p>The Importance of Language Models in Modern AI</p><p>Why are language models such a big deal? The answer lies in their ability to outperform previous benchmarks across diverse, complex tasks. They bring advanced reasoning capabilities to applications that were previously unfeasible or limited in scope. Examples include:</p><p>• Language Translation: Achieving near-human levels of accuracy across languages.</p><p>• Code Assistance: auto-generating code snippets or debugging.</p><p>• Content Creation: Writing essays, reports, or creative pieces.</p><p>• Text Summarization: Condensing long documents into meaningful summaries.</p><p>• Question-Answering: providing precise, context-aware answers to queries.</p><p>These applications are only scratching the surface. With fine-tuning, an LLM can be customized to excel in niche domains—whether it’s legal document analysis or medical diagnostics. This adaptability has sparked innovation in various industries, empowering professionals never before.</p><p>The Road to Modern LLMs: Key Innovations</p><p>The major attribute of the evolution of language models is continuous innovation. Early models struggled with capturing long-term dependencies and handling diverse tasks. Over time, there has been a paradigm shift that has transformed these limitations into strengths.</p><p>Recurrent Neural Networks (RNNs): The Starting Point</p><p>RNNs were among the first architectures used for sequential data like text. They processed input one token at a time, maintaining a “hidden state” to store contextual information. While groundbreaking, RNNs faced several issues:</p><p>Vanishing/Exploding Gradients: Training became unstable for long sequences.</p><p>Sequential Processing: Limited parallelization, making them computationally expensive.</p><p>Context Limitations: Struggled with long-term dependencies in sequences.</p><p>Variants like LSTMs (Long Short-Term Memory) and GRUs (Gated Recurrent Units) partially addressed these issues, but they still fell short in scalability.</p><p>The Transformer Era</p><p>The introduction of the transformer architecture in the 2017 paper “Attention is All You Need” by Vaswani et al. was a game-changer. Transformers introduced a novel mechanism—self-attention — that allowed models to process sequences in parallel. This led to:</p><p>• Better Long-Term Context Handling: By focusing on relevant parts of input sequences.</p><p>• Scalability: faster training and inference compared to RNNs.</p><p>• Broader Applications: From Translation to Summarization.</p><p>How Transformers Work</p><p>The Self-Attention Mechanism</p><p>Self-attention enables transformers to weigh the importance of different words in a sentence relative to each other. For example, in the sentence “The tiger drank water because it was thirsty,” self-attention helps the model understand that “it” refers to “tiger.”</p><p>Key steps in self-attention:</p><p>Creating Query, Key, and Value Vectors: Each word is transformed into three representations: query (Q), key (K), and value (V).</p><p>Calculating Attention Scores: Scores are computed by taking the dot product of Q and K, normalized, and passed through a softmax function.</p><p>Weighted Sum: These scores are used to create weighted representations of the value vectors.</p><p>The process ensures the model dynamically focuses on the most relevant words in a sequence.</p><p>Multi-Head Attention</p><p>Transformers use multiple attention “heads” to capture different aspects of relationships between words. By processing Q, K, and V vectors across several heads, the model gains a richer contextual understanding.</p><p>Encoder-Decoder vs. Decoder-Only Architectures</p><p>• Encoder-Decoder Models</p><p>These models, like BERT and T5, consist of:</p><p>Encoder: Processes the input sequence and generates contextual embeddings.</p><p>Decoder: Uses these embeddings to produce an output sequence, one token at a time.</p><p>• Decoder-Only Models</p><p>Models like GPT streamline this process by focusing solely on generating output based on input prompts. This architecture has proven highly effective for tasks like text generation and dialogue systems.</p><p>Training Transformers: From Data to Insights</p><p>The journey from raw data to a fully trained transformer involves several steps:</p><p>Data Preparation:</p><p>• Cleaning: removing duplicates, normalizing text, and filtering noisy data.</p><p>• Tokenization: splitting text into smaller units (tokens) and mapping them to unique IDs.</p><p>• Vocabulary Building: Creating a set of unique tokens for the model to work with.</p><p>Loss Functions:</p><p>Models are trained using loss functions like cross-entropy loss, which measures the difference between predicted and actual tokens.</p><p>Optimization:</p><p>Gradients are computed and backpropagated to update model weights, typically using optimizers like Adam or its variants.</p><p>Fine-Tuning and Customization</p><p>Out-of-the-box LLMs are versatile, but fine-tuning unlocks their true potential for specific domains or tasks. This involves:</p><p>• Domain-Specific Training: using a smaller dataset tailored to the target task.</p><p>• Instruction Tuning: Teaching the model how to follow task-specific instructions.</p><p>• Parameter-Efficient Methods: Techniques like LoRA (Low-Rank Adaptation) or prefix-tuning minimize computational costs by adjusting only a subset of parameters.</p><p>Making Inference Efficient</p><p>Despite their power, LLMs can be resource-intensive during inference. To address this:</p><p>• Quantization: Reduces model size by representing weights with fewer bits (e.g., 4-bit quantization).</p><p>• Distillation: compresses a large model into a smaller, faster version while retaining performance.</p><p>• Sparse Attention: Improves efficiency by focusing only on the most relevant parts of the input sequence.</p><p>Applications of Large Language Models</p><p>• Education<br>LLMs are transforming education by enabling personalized tutoring, automated grading, and content generation for curricula.</p><p>• Healthcare<br>From summarizing medical records to assisting in diagnostics, LLMs enhance decision-making and patient care.</p><p>• Software Development<br>Developers leverage LLMs for code generation, debugging, and documentation.</p><p>• Creative Industries<br>Content creators use LLMs for brainstorming, writing scripts, or generating artwork descriptions.</p><p>• Customer Service<br>LLMs power chatbots and virtual assistants, providing instant, accurate responses to customer queries.</p><p>• Ethical Considerations<br>While LLMs offer immense potential, they also raise concerns:</p><p>Bias: Models may reflect biases present in their training data.</p><p>Misinformation: The ability to generate convincing yet false information.</p><p>Environmental Impact: High energy consumption during training.</p><p>Addressing these challenges requires responsible development practices, transparency, and ongoing research.</p><p>PROMPTING</p><p>In the fascinating world of AI, one of the most intriguing concepts is that of a large language model (LLM) taking an input and generating a meaningful output. At the heart of this exchange is the text prompt — a seemingly simple idea that holds profound potential. A prompt is basically the input you provide to the model to guide its output. While anyone can write a prompt, creating a highly effective one takes skill and practice.</p><p>The effectiveness of a prompt depends on various factors: the choice of model, its training data, configurations, word choice, tone, structure, and context. <br>Prompt engineering—crafting prompts to guide models toward desired outcomes—is an iterative process. Inadequate prompts lead to vague or erroneous responses, hindering the model’s ability to shine. In this section of the blog post, we will explore the art and science of prompt engineering, uncovering techniques, best practices, and the configurations that can turn an average prompt into a powerful tool.</p><p>What Is Prompt Engineering?</p><p>Prompt engineering is the meticulous process of designing prompts that steer/guide LLMs to generate accurate and task-relevant outputs. Unlike traditional software engineering, where code governs behaviour, in prompt engineering, language is the code, in sensei Kaparthy’s voice, “English is the new programming language”.<br>A well-crafted prompt can transform the way an LLM interprets and generates information.</p><p>Prompts are used in various applications, from text summarization to language translation and even complex reasoning tasks. For example, they can extract insights from unstructured data, classify content, or even generate structured outputs like JSON. The breadth of applications makes prompt engineering indispensable for anyone working with AI models.</p><p>There is more to prompts than just getting answers —they&#39;re about getting the right answers in the right way. This is where optimization comes into play. Crafting a prompt involves experimenting with phrasing, structure, and additional context. It’s about finding that sweet spot where the model fully understands your intent and delivers accordingly.</p><p>Configuring LLM Outputs</p><p>Once you’ve selected a language model for your task, the next step is configuring it to suit your requirements. Configuration settings can profoundly influence the quality of the generated output.</p><p>Key Configuration Parameters</p><p>• Output Length<br>The length of the response is governed by the number of tokens the model generates. Shorter outputs are faster and less resource-intensive, while longer outputs are ideal for detailed responses. Balancing this tradeoff is crucial.</p><p>• Sampling Controls<br>Language models don’t output the “most likely” answer directly; instead, they assign probabilities to all possible tokens and samples from this distribution.</p><p>Key parameters include:</p><p>• Temperature: Governs randomness. Lower values result in more deterministic outputs; higher values encourage creative or diverse responses.</p><p>• Top-K Sampling: Restricts the output to the top K tokens with the highest probabilities.</p><p>• Top-P Sampling (Nucleus Sampling): Chooses tokens from a cumulative probability distribution, creating outputs that balance diversity and coherence.</p><p>Prompt Optimization</p><p>Your prompt interacts dynamically with these configurations. A clear, structured prompt combined with optimal settings can ensure that outputs are both high-quality and efficient.</p><p>Essential Prompting Techniques</p><p>1. Zero-Shot Prompting</p><p>Zero-shot prompting is the simplest form of prompting: you describe the task, and the model takes it from there. While straightforward, its simplicity may lead to inconsistent results when the task is complex.</p><p>2. One-Shot &amp; Few-Shot Prompting</p><p>Providing examples within your prompt — either one (one shot) or several (few shots)—can dramatically improve model performance. Examples teach the model about desired output patterns, reducing ambiguity.</p><p>3. System, Contextual, and Role Prompting</p><p>These techniques focus on giving the model a defined purpose or context:</p><p>System prompting: Sets an overarching goal (e.g., “You are a helpful assistant.”).</p><p>Contextual prompting: Adds relevant background to help the model tailor its response.</p><p>Role prompting: Assigns a specific persona to the model, such as a tutor, developer, or data analyst.</p><p>4. Step-Back Prompting</p><p>This iterative approach asks the model to consider a broad question first, then uses that response as input for a more specific task. It’s particularly useful in scenarios requiring logical reasoning.</p><p>5. Chain of Thought (CoT) Prompting</p><p>CoT prompting encourages the model to break down its reasoning process into steps, producing more accurate answers. By guiding the model to “think aloud,” CoT prompts uncover the logic behind its conclusions.</p><p>6. Tree of Thoughts (ToT)</p><p>Building on CoT, this technique allows models to explore multiple reasoning paths in parallel, improving complex problem-solving capabilities.</p><p>7. ReAct (Reason + Act)</p><p>ReAct integrates reasoning with action, enabling models to interact with external tools like search engines or APIs to retrieve information. This approach moves beyond static reasoning, opening doors to dynamic, real-world applications.</p><p>Best Practices for Prompt Engineering</p><p>Mastering prompt engineering requires both practice and experimentation. Here are some guidelines to enhance your skills:</p><p>Provide Examples: Examples are powerful teaching tools for LLMs. Include one-shot or few-shot examples to clarify your intent.</p><p>Design Simplicity: Keep prompts concise and unambiguous.</p><p>Be Specific: Clearly outline your desired output. Vague instructions lead to inconsistent results.</p><p>Experiment with Formats: Try different input styles, output formats (e.g., JSON, XML), and writing styles to discover what works best.</p><p>Document Attempts: Keep track of what works and what doesn’t for future reference.</p><p>Embeddings and Vector Stores</p><p>In an increasingly data-driven world, the ability to process and make sense of diverse information—text, images, videos, or graphs—is essential for organizations aiming to remain competitive. Embeddings and vector stores are at the heart of modern machine learning (ML) and artificial intelligence (AI), offering robust ways to transform complex data into meaningful insights. This blog dives deep into the concepts of embeddings and vector stores, explaining their significance, practical implementations, and potential to power innovative solutions.</p><p>In this section of the blog post, you’ll gain a comprehensive understanding of:</p><p>What embeddings are and how they work.</p><p>Key types of embeddings and their applications across various domains.</p><p>The mechanics of vector search and its advantages over traditional search methods.</p><p>Real-world use cases and operational considerations when implementing embeddings and vector databases.</p><p>Let’s begin with the basics.</p><p>Understanding Embeddings</p><p>Embeddings serve as the backbone of modern AI systems by converting real-world data into numerical formats that computers can process effectively. At their core, embeddings are vector representations—points in a multidimensional space that encapsulate the semantic or structural meaning of data. This transformation enables tasks like recommendation systems, semantic search, and anomaly detection.</p><p>Why Are Embeddings Crucial?</p><p>The appeal of embedding lies in their ability to capture relationships and context. For instance, words with similar meanings (e.g., king and monarch) are represented as vectors positioned closely in the embedding space. This capability forms the foundation for applications like machine translation, personalized content delivery, and search engines.</p><p>Key benefits include:</p><p>• Compact Representation: Embeddings condense complex data into numerical vectors of lower dimensions.</p><p>• Semantic Preservation: They capture the underlying relationships and meanings within data.</p><p>• Efficient Processing: By simplifying input, embeddings enable faster computation and scalability for ML models.</p><p>Types of Embedding</p><p>The versatility of embeddings stems from their adaptability across multiple data types. Below, we explore the primary categories.</p><p>• Text Embeddings</p><p>In natural language processing (NLP), text embeddings map words, sentences, or documents into a vector space. Text embeddings are indispensable for tasks like sentiment analysis, text classification, and semantic similarity.</p><p>• Word Embeddings</p><p>Techniques such as Word2Vec, GloVe, and FastText learn embeddings for individual words by analyzing co-occurrence patterns in large corpora. Word embeddings capture both semantic and syntactic nuances. For example:</p><p>The words dog and cat might be close in vector space, reflecting their shared meaning as animals.</p><p>• Document Embeddings</p><p>Unlike word embeddings, document embeddings represent larger text units, such as sentences or paragraphs. Modern approaches like Doc2Vec and contextualized models like BERT excel at understanding context, making them invaluable for tasks such as summarization or question answering.</p><p>How Are Embeddings Trained?</p><p>Creating embeddings involves training models to map data points into an embedding space where semantic or structural relationships are preserved. This process often utilizes a dual encoder architecture, where:</p><p>One tower encodes the input data.<br>The second tower encodes the target (e.g., labels, queries).</p><p>Models are optimized using contrastive loss, which minimizes the distance between positive pairs while maximizing it for negative pairs.</p><p>Vector Search: Beyond Keywords</p><p>Traditional search methods rely heavily on exact matches of keywords, limiting their ability to retrieve semantically similar results. Vector search, powered by embeddings, revolutionizes this by matching based on meaning rather than literal text.</p><p>The Vector Search Workflow</p><p>• Embedding Creation: Data items (e.g., text, images) are transformed into embeddings using a pre-trained or fine-tuned model.</p><p>• Storage in Vector Databases: These embeddings, along with metadata, are stored in a vector database.</p><p>• Query Processing: When a query is received, its embedding is computed and compared with stored embeddings using approximate nearest neighbour (ANN) algorithms to find the most similar items.</p><p>Advantages of Vector Search</p><p>• Semantic Matching: goes beyond keywords to identify meaningfully related content.</p><p>• Scalability: ANN algorithms enable efficient searches across millions or billions of vectors.</p><p>• Enhanced Personalization: Powers recommendation systems by finding content tailored to user preferences.</p><p>• Vector Databases: Managing Embeddings at Scale</p><p>The utility of embeddings is amplified when combined with specialized databases designed for storage and search. <br>These databases offer:<br> • High-performance ANN Search: Quickly retrieving similar embeddings.</p><p>• Metadata Integration: Enabling hybrid search by combining semantic and keyword-based approaches.</p><p>• Scalability and Resilience: Managing massive datasets with features like replication and sharding.</p><p>Popular tools include Pinecone, chromadb, and Google Vertex AI Vector Search.</p><p>Applications of Embeddings and Vector Stores</p><p>The versatility of embeddings allows their application across diverse domains.</p><p>1. Search and Recommendations</p><p>Semantic Search: Retrieving documents or products based on intent rather than keywords.</p><p>Personalized Recommendations: Suggesting items by matching user profiles with similar embeddings.</p><p>2. Semantic Similarity</p><p>Applications like paraphrasing detection, duplicate identification, and sentence alignment rely on the ability of embeddings to quantify similarity.</p><p>3. Retrieval Augmented Generation (RAG)</p><p>Combining embeddings with large language models (LLMs) enhances the factual accuracy and relevance of generated content. This is particularly impactful in education and customer support.</p><p>Operational Considerations<br>Implementing embeddings and vector databases requires addressing challenges like:</p><p>1. Embedding Drift<br>Models evolve over time, which can cause embeddings to shift, impacting search relevance. Managing drift through versioning is critical.</p><p>2. Hybrid Search<br>Combining semantic and keyword-based searches ensures results are both contextually relevant and syntactically accurate.</p><p>3. Lifecycle Management<br>Regular updates and pruning maintain efficiency without compromising stability.</p><p>Embeddings and vector stores are transforming how data is understood, managed, and utilized. By leveraging these technologies, organizations can unlock powerful insights, drive personalized user experiences, and innovate across industries.</p><p>Conclusion</p><p>The evolution of large language models, the art of prompt engineering, and the infrastructure of embeddings and vector stores represent three deeply interconnected pillars of modern AI systems. At the foundation, large language models provide the raw computational power and linguistic understanding that make sophisticated AI applications possible. Their transformer-based architectures and ability to process vast amounts of data create the baseline capabilities for understanding and generating human-like text. However, these models would be significantly less useful without the other two components.<br>Prompt engineering serves as the crucial interface layer, acting as a bridge between human intent and model capability. It transforms the raw power of LLMs into practical, controllable outputs. The sophisticated prompting techniques from few-shot learning to chain-of-thought reasoning help unlock the full potential of these models, making them more precise, reliable, and useful for specific tasks. Without effective prompt engineering, even the most powerful LLMs would struggle to consistently deliver valuable results.<br>Embeddings and vector stores complete this technological trinity by providing the essential infrastructure that makes these systems scalable and efficient in real-world applications. They enable the crucial ability to store, retrieve, and compare semantic information, allowing LLMs to access and utilize relevant information effectively. Through vector search and semantic similarity, embeddings help ground LLM outputs in factual information and enable sophisticated applications like retrieval-augmented generation.<br>Together, these three elements create a powerful synergy. As these technologies continue to evolve, their interdependence becomes even more apparent. Advances in one area often enable improvements in others; better LLM architectures enable more sophisticated prompting techniques, while improved embedding methods enhance the context available to these models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=786ee56f2b8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PERMUTATION IMPORTANCE AS A SUCCINCT MODEL SUMMARY]]></title>
            <link>https://medium.com/@funboy.ea/permutation-importance-as-a-succinct-model-summary-dd88ff3fbe1d?source=rss-52496b282c20------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd88ff3fbe1d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning-expert]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Funboy Ea]]></dc:creator>
            <pubDate>Sun, 10 Jul 2022 18:42:40 GMT</pubDate>
            <atom:updated>2022-07-10T18:42:40.848Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, like the heading suggests, I will be writing about Permutation Importance. Have you at least once pondered what features your Machine Learning Model thinks are important? If you have or have not, you are reading the right article.</p><p>In Machine Learning, one of the problems often encountered during “Feature Engineering” is determining what features have the biggest impacts on predictions. One of the most effective ways to evaluate this metric is as you might have guessed <strong>Permutation Importance</strong>. Some other methods to evaluate the aforementioned metric are by plotting partial plots and calculating SHAP(Shapley Additive Explanations) which are considered means of building trust in a model’s predictions termed <strong>Machine Learning Explainability</strong>.</p><p>Before we dive into codes, I would like for it to be noted that Permutation Importance is computed when a model has been trained. And it goes ahead to probe if the data points of a single attribute are randomly shuffled in the validation set leaving all remnant data as is.</p><p>What would be the ramifications on accuracy, using this new data? The process is as follows;</p><p>● Get a trained Model</p><p>● Shuffle the values for a single attribute, and use this data to get new predictions.</p><p>● Evaluate change in loss function using these new values and predictions to determine the effect of shuffling(The drop in</p><p>performance quantifies the importance of the feature that has been shuffled.)</p><p>● Reverse the shuffling done in the previous step to recover the original data.</p><p>● Redo bullet point two using the next attribute until the importance for every feature is determined.</p><p>All my codes are written in python. Python provides a convenient way to calculate Permutation Importance. It works in Python 2.7 and Python 3.4+.</p><p>Our example will use a model that predicts whether a soccer/football team will have the “Man of the Game” winner based on the team’s statistics. The “Man of the Game” award is given to the best player in the game. Model-building isn’t our current focus, so the cell below loads the data and builds a rudimentary model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/0*jg7lbfy6JXVhJmqj" /></figure><p>Above is how to calculate and show importance using Python Eli5 library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*I3eR8-S0R4tmHUSF" /></figure><p>After running the cell, your output should be a replica of the cell below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/0*5E9OMVElZwBtfU3b" /></figure><p><strong>INTERPRETATION.</strong></p><p>The values towards the top are the more important ones while the values towards the bottom are the least important ones. The first number in each row shows how much the model performance decreases with a random shuffling using accuracy as the performance metric. The number after the <strong>± </strong>measures performance variance from re-shuffling to the next.</p><p><strong>SUMMARY.</strong></p><p>Negative values for Permutation Importances will be encountered occasionally. In those cases, the predictions on the shuffled data happen to be more accurate than the real data.</p><p>This happens when the feature did not matter(Should have had an importance close to 0) but random chance allowed the predictions on shuffled data to be more accurate. This is more common with small datasets, like the one applied in the example. In the view of the fact that there is more room for chance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd88ff3fbe1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>