<?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 Manoj Kumar Vohra on Medium]]></title>
        <description><![CDATA[Stories by Manoj Kumar Vohra on Medium]]></description>
        <link>https://medium.com/@manojkumarvohra9?source=rss-19d25161bec8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CfpCzabOMm1vX_vi1hXtgg.jpeg</url>
            <title>Stories by Manoj Kumar Vohra on Medium</title>
            <link>https://medium.com/@manojkumarvohra9?source=rss-19d25161bec8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:48:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manojkumarvohra9/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[Relevant Is Not the Same as Right: Can Retrieval Tell Which Source to Trust?]]></title>
            <link>https://medium.com/@manojkumarvohra9/relevant-is-not-the-same-as-right-can-retrieval-tell-which-source-to-trust-5e405e6f8472?source=rss-19d25161bec8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e405e6f8472</guid>
            <category><![CDATA[ai-knowledge-graphs]]></category>
            <category><![CDATA[jevs]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[hybrid-search]]></category>
            <category><![CDATA[decision-model]]></category>
            <dc:creator><![CDATA[Manoj Kumar Vohra]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 08:15:22 GMT</pubDate>
            <atom:updated>2026-10-09T08:15:22.993Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Whether you retrieve from documents or from a knowledge graph, sources disagree. We gave look-alike evidence to ten scoring systems and asked one question: which of them can tell the current, official answer from the ones that only sound right?</em></p><p>Picture a support chatbot that answers from your company documents. A customer asks:</p><blockquote>“What is the current refund policy for an annual Pro subscription, and are there any exceptions?”</blockquote><p>The search step returns a pile of documents. Some are the official, current policy. Others are an old version that says 30 days, an unapproved internal draft that also says 30 days, a forum thread, a blog guessing what “most SaaS companies” do, and an official document about something else entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7KGwS2D5seWlsaTw6IFDbA.png" /><figcaption><em>Figure 1. Five documents, one right answer.</em></figcaption></figure><p>Every one of them is about refunds. Only one of them is right: the real answer is <strong>14 days</strong>. If the chatbot trusts the wrong one, it promises a customer something your company will not honour.</p><p>This article is about that problem in two settings: a simple RAG support chatbot like the one above, and knowledge graph retrieval, where several sources assert different values for the same fact. It covers a kind of model built for the problem (JEV-style “decision models”) and what happened when we tested those models against the tools most teams use today. Our tests use the RAG setup and we explain how the knowledge graph case maps onto it.</p><h3>Two places this problem shows up</h3><p><strong>Use case 1: a RAG support chatbot.</strong> The chatbot answers from company documents. Search returns chunks of text, and the model has to decide which chunk to believe. The refund example above is this case. The thing being judged is a <strong>chunk of text</strong>, and the risk is that the chatbot repeats an outdated or unofficial one.</p><p><strong>Use case 2: knowledge graph retrieval.</strong> A knowledge graph stores facts as links between things, such as “Pro annual plan, refund window, 14 days”. When a graph is built from documents, tickets and wikis, it often holds several competing values for the same fact, each linked to the source it came from. Asking for the refund window returns all of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kcqrox6Xcbi55KBbNqG10w.png" /><figcaption><em>Figure 2. Four sources assert a value for one fact.</em></figcaption></figure><p>Graph traversal answers “what is connected to this?” It does not answer “which of these values should I trust?” That is the same gap as in search: being connected, like being related, is not the same as being right. The three decisions map onto a graph directly:</p><ul><li><strong>Authority</strong> says how much to trust the source behind a link.</li><li><strong>Freshness</strong> says whether the value is current or has been superseded.</li><li><strong>Contradiction</strong> says whether a value conflicts with the best-supported value for the same fact.</li></ul><p>Your code can then keep the winning link, flag the others, or store the scores as weights on the links. The source details we send with each document in the tests below (source type, date and status) are what a graph would store as provenance on each link.</p><p><strong>What we tested.</strong> We tested the first case. But our chunk-level test has the shape of the second: each question asks for one value, and there are 15 pieces of evidence for it, six of which assert a wrong one.</p><h3>Why search alone is not enough</h3><p>A typical search pipeline for RAG (retrieval-augmented generation, where a model answers from retrieved documents) looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRIq9frpFMZxoqikpcmNOQ.png" /><figcaption><em>Figure 3. A typical hybrid search pipeline.</em></figcaption></figure><ul><li><strong>BM25</strong> matches the words in the question against the words in each document.</li><li><strong>Semantic search</strong> compares meaning using embeddings, so it finds documents that use different words.</li><li><strong>Reciprocal rank fusion (RRF)</strong> merges the two ranked lists by position, so a document that ranks high in both rises to the top.</li><li><strong>A reranker</strong> (optional) reads the question and a piece of text together and returns one number for “how related”, to reorder the top results more carefully.</li></ul><p>Every stage answers the same question: how related is this document to what was asked?</p><p>Relatedness is blind to everything else that matters when you are about to put text in front of a customer:</p><ul><li><strong>Authority:</strong> is this from the official source or from a forum comment?</li><li><strong>Freshness:</strong> is this the current version, or was it superseded last year?</li><li><strong>Contradiction:</strong> does it say something that conflicts with the verified facts?</li></ul><p>An outdated policy page is <em>highly related</em> to a question about the current policy. A reranker will rank it right behind the correct page, and a language model reading both may pick the wrong one.</p><p>So the real question for a RAG system is not “which documents match?” but “which documents can I trust, and which should I flag?”</p><p>We call the answer <strong>decision-augmented search</strong>. Keep hybrid retrieval, fusion and reranking for finding and ordering candidates. Then add one stage: for each surviving candidate, get typed decisions about authority, freshness and contradiction before anything reaches the customer. Jev is one such augmentation. It sits on top of the earlier stages and does not replace any of them. The same stage works after graph retrieval, where the candidates are facts instead of chunks (Figure 4).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zb8qzDTdEmP78SZdtPtOUw.png" /><figcaption><em>Figure 4. The same decision stage after two kinds of retrieval.</em></figcaption></figure><h3>What is Jev, and what is a decision model?</h3><p>Jev is a hosted model from TypeSafe. TypeSafe calls this kind of model <strong>System One</strong>, after the two modes of thinking that Daniel Kahneman described. <strong>System 1</strong> is fast and intuitive: you glance at a message and know it is urgent. <strong>System 2</strong> is slow and deliberate: you work through a problem step by step.</p><p>TypeSafe’s argument is that most decisions inside software are System 1 judgments (“which team should handle this?”, “is this urgent?”), yet teams have been using System 2 tools, large chat models, to make them. A chat model writes text, and your code then has to parse that text. A System One model skips that step. You ask a <strong>typed question</strong> and get a <strong>typed answer</strong> back, in one quick pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwlyutFwfOs8AicrG4MhLw.png" /><figcaption><em>Figure 5. System 1 and System 2 ways to make a decision in software.</em></figcaption></figure><p>In this article, Jev, OpenJev and the Ollama models are System One style decision models, and the GPT-5.6 judges are the System 2 comparison: general chat models told to answer in JSON. That framing is TypeSafe’s own. Our tests measure how well these systems separate documents, not the vendor’s wider claims about speed and cost.</p><p>There are three kinds of question:</p><ul><li><strong>Score:</strong> “How authoritative is this source, on a scale of 0 to 4?” The answer comes back as a probability spread over the levels, for example “91% very high”.</li><li><strong>Yes/no:</strong> “Does this document contradict the verified policy?” The answer is a probability between 0 and 1.</li><li><strong>Choice:</strong> “Which team should handle this: billing, shipping or technical?” The answer is a probability for each option.</li></ul><p>You define the questions and the scale when you make the request. The model returns numbers in one quick pass, with no generated sentence and no JSON to repair.</p><p>For ranking documents that matters. A probability like 0.92 for “contradicts” is something you can put a threshold on. Free text is not. The search stays fast, and the decisions arrive as numbers your code can act on.</p><p>We asked six questions about each document:</p><ol><li><strong>Relevance:</strong> is it about what I asked?</li><li><strong>Answerability:</strong> can I actually answer from it?</li><li><strong>Authority:</strong> how trustworthy is the source?</li><li><strong>Freshness:</strong> is it current?</li><li><strong>Specificity:</strong> does it speak to this exact question?</li><li><strong>Contradiction:</strong> is its claim wrong or outdated compared with the best current source?</li></ol><p>We combined the answers into one score, with contradiction acting as a penalty:</p><pre><br>final = (0.30 relevance + 0.30 answerability + 0.15 authority<br>         + 0.10 freshness + 0.15 specificity) x (1 - 0.5 x contradiction<br></pre><p>In words: add up the five quality scores with the weights shown, then cut the result by up to half if the document contradicts the best source.</p><h3>The systems we tested</h3><p>We compared ten systems, in three groups.</p><p><strong>Jev-style decision models</strong></p><ul><li><strong>Hosted Jev</strong>, model jev-1.13-free, served through BeatAPI on its free tier.</li><li><strong>OpenJev</strong>, an independent open-weight decision model, in a 4-bit build for Apple silicon. It is licensed CC BY-NC 4.0 (non-commercial) and is not affiliated with TypeSafe.</li><li><strong>SemIf</strong>, an independent open project that reads option probabilities from a frozen Qwen3.5–4B model. It copies the <em>interface pattern</em> of a decision model, not Jev’s own model or training. Our adapter maps yes/no and score questions onto its multiple-choice format, which may be unfair to it.</li><li><strong>Three Ollama models</strong> that run locally: tev1:0.8b, tev1 (4B) and nimble (9B).</li></ul><p><strong>General-purpose LLM judges</strong></p><ul><li><strong>GPT-5.6 luna</strong> and <strong>GPT-5.6 terra</strong>, told to return the same six answers as JSON.</li></ul><p><strong>Rerankers</strong></p><ul><li><strong>bge-reranker-base</strong>, which reads at most 512 tokens (a token is roughly three quarters of a word).</li><li><strong>bge-reranker-v2-m3</strong>, which reads up to 8,192 tokens.</li></ul><p><strong>Where it ran.</strong> The local systems ran on one MacBook Pro (Apple M5 Max, 18 cores, 48 GB). Hosted Jev used the free tier of BeatAPI, and the GPT-5.6 models ran on Azure OpenAI. Local models ran strictly one at a time.</p><h3>How we tested</h3><p>We wanted a test where the difficulty was in the <em>kind</em> of wrongness, not in the length of the text. It has three parts:</p><ul><li><strong>Part 1, short set:</strong> 8 passages of about 100 words each. A warm-up.</li><li><strong>Part 2, long set:</strong> 8 documents of 5,000 to 8,000 tokens each, scored whole. This is the main test.</li><li><strong>Part 3, chunk-level set:</strong> 15 retrieved chunks per question, in two sizes. It checks the same ideas at search scale.</li></ul><p>All three parts use the same two stages. First each item is scored on its own. Then it is checked for contradiction against the other items. The parts differ in how the other items are shown to the contradiction check. Part 1 shows the full text of the other passages, since they are short. Part 2 shows a one-sentence summary of each other document, written by us, because the full documents would not fit. Part 3 compares five ways of showing them.</p><h3>The long set</h3><p>In each long document the paragraph that matters is buried at a different depth, surrounded by realistic but unrelated filler (legal clauses, retention rules, help articles, forum chatter). The filler never mentions refunds, so the only refund facts are the ones we planted.</p><p>The eight documents were built so that being on topic, official, current and wrong vary <strong>independently</strong>. We wrote down the right labels for each before running any model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UzAWZlr53w-4qnVBi8mfFw.png" /><figcaption><em>Figure 6. The eight long documents and what is true about each.</em></figcaption></figure><p>That design makes a sharp test possible. D2 and D3 are <strong>official but irrelevant</strong>, so a good system gives them high authority and low relevance. D4 and D5 are <strong>relevant but unofficial</strong>, so a good system gives them high relevance and low authority. A system that cannot tell relevance from authority will rate both groups the same.</p><p>Each long document goes through three steps and costs two requests (steps 1 and 2):</p><p><strong>Step 1. Score the document on its own</strong> on five questions: relevance, answerability, authority, freshness and specificity.</p><p><strong>Step 2. Score contradiction.</strong> The model sees the document together with a one-sentence summary of each of the other seven documents, and is asked whether the document’s claim is wrong or outdated.</p><p><strong>Step 3. Combine the six answers</strong> into one score and rank the eight documents.</p><p>Using short summaries in step 2 kept every request comfortably inside every model’s context window (the amount of text it can read at once). Peak prompts were about 9,000 tokens, against limits of 32,000 (hosted Jev), 16,384 (OpenJev and our long-context Ollama copies) and 12,288 (SemIf).</p><h3>The chunk-level set</h3><p>Real search returns many small pieces of text (chunks), not a few whole documents. This test copies that. For each question we start with 15 chunks, ask each system to score them, and see whether the best chunk ends up first. It is also the shape of a knowledge graph conflict: one question about one value, with many pieces of evidence behind it.</p><p>There are three questions: the refund window, the length of a free trial, and an uptime guarantee. Each question gets the same mix of 15 chunks:</p><ul><li><strong>6 chunks state the right answer:</strong> four official chunks, one partial official chunk and one correct forum post.</li><li><strong>6 chunks state a wrong answer:</strong> an old version, an unapproved draft, an outdated support macro, a wrong forum post, a blog guess and a review site.</li><li><strong>3 chunks are about something else:</strong> another plan, an unrelated topic, or nothing relevant.</li></ul><p>Titles are neutral (none says “superseded” or “draft”), and the correct labels were never shown to a model. Each question also exists in two sizes. <strong>Small</strong> chunks are about 40 to 210 tokens each. <strong>Large</strong> chunks hold the same claims inside filler text, about 1,300 to 1,800 tokens each and 22,000 tokens in total.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQS-Urq_IWUei2Slqr5bfg.png" /><figcaption><em>Figure 7. How the chunk-level test scores and reorders 15 chunks.</em></figcaption></figure><p>The test runs in five steps:</p><p><strong>Step 1. Start with the 15 chunks</strong> for one question.</p><p><strong>Step 2. Score each chunk on its own</strong> on five things: relevance, answerability, authority, freshness and specificity. Each score is a number from 0 to 1.</p><p><strong>Step 3. Score contradiction.</strong> The question is: does this chunk say something wrong or outdated compared with the best current source? To answer, the model has to see the other 14 chunks. The hard part is deciding how to show them, so we tried five ways:</p><ul><li><strong>Summary:</strong> one sentence for each other chunk, written by us. This is the method the long set used.</li><li><strong>Raw:</strong> the full text of all 14 other chunks. For large chunks that is about 23,000 tokens. Only GPT-5.6 could take it, so we ran it there on the refund question only.</li><li><strong>Truncated:</strong> only the first 120 words of each other chunk.</li><li><strong>Batched:</strong> the full text in groups of 6 chunks (4 for SemIf), keeping the highest contradiction score. We used 6 because Ollama refuses requests larger than 64 KiB, and a group of 7 large chunks was too big.</li><li><strong>Reference:</strong> use the step 2 scores to find the 3 other chunks the model trusts most (highest authority times freshness), then compare only against those 3, with the model’s own scores attached.</li></ul><p><strong>Step 4. Combine the scores</strong> into one number: the weighted quality score from before, multiplied by (1 − 0.5 × contradiction). A chunk that contradicts the best source loses up to half its score.</p><p><strong>Step 5. Reorder the 15 chunks</strong> by that number, and compare the result with a reranker that orders by relevance alone.</p><p>Every system was run except hosted Jev, whose free tier allows one request per minute. Local models ran one request at a time, and GPT-5.6 requests ran in parallel.</p><h3>What each system received</h3><p>Every document was sent to the decision models with four fields next to its text: a source title, a source type (official, internal, forum, blog), a date and a status (current, superseded, draft, unverified). We call these the <strong>source details</strong>. In the long set, some titles also carried the status, for example “Terms of Service v3.9 (official, superseded)”. The chunk-level titles were neutral. The rerankers received only the question and the text. The small-chunk tests were also run without the source details, to show how much the models rely on them (finding 8).</p><h3>How we measured</h3><p>Two measures did most of the work.</p><p><strong>NDCG</strong> gives one score from 0 to 1 for the whole ordering. Putting good documents near the top counts more than putting them further down.</p><p><strong>AUC</strong>, per question, asks: “pick one document that should score high and one that should score low at random. How often does the system give the right one the higher score?” 1.00 means always, 0.50 is a coin flip, and near 0 means backwards.</p><p>You will see below why we ended up trusting AUC more than NDCG when there are only a few documents.</p><h3>What we found</h3><h3>1. Hosted Jev separated everything, and did it repeatably</h3><p>On the long set, hosted Jev scored <strong>AUC 1.00 on relevance, authority, freshness and contradiction</strong>. It was the only system that did. Every document that contradicts the right answer scored 0.90 or higher on contradiction, and every document that does not scored 0.41 or lower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rovm8aEy6jLr6hI1LKYOeQ.png" /><figcaption><em>Figure 8. AUC per question on the long set. Only hosted Jev scores 1.00 on all four.</em></figcaption></figure><p>It was also the most stable system. We ran the entire sweep twice, on 4 and 6 October. No hosted Jev score moved by more than 0.05.</p><h3>2. The ranking score turned out to be a trap</h3><p>In the first run, hosted Jev and both GPT-5.6 judges tied for the best NDCG at 0.965. In the second run they all dropped to about 0.89. Did they get worse?</p><p>No. D1 and D7 are both correct, and we had labelled D1 as slightly better. Hosted Jev scored them <strong>0.903 and 0.905</strong>, effectively a tie, and in the first run it happened to put D1 first. With only eight documents, swapping two near-equal correct answers moves NDCG by about 0.08. That swing is bigger than most of the gaps between the systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lh-JpcgA5yBQtLD-EkjYVw.png" /><figcaption><em>Figure 9. NDCG on the long set. Nine of the twelve rows fall between 0.887 and 0.899.</em></figcaption></figure><p>The lesson: <strong>with a small set, do not rank systems on small NDCG differences.</strong> Look at what they get right and wrong, and at whether the answer repeats.</p><h3>3. The LLM judges separated well, but did not repeat</h3><p>GPT-5.6 luna and terra both scored contradiction AUC 1.00 and authority AUC 1.00. They finished the whole long set in 50 to 56 seconds with no rate-limit trouble. They are a reasonable option if you are already on that platform.</p><p>The catch is repeatability. With byte-identical prompts, a second full run changed 9 of 48 long-set scores by more than 0.05 for each judge. The largest single change was 0.88 on a 0 to 1 scale. Terra scored the unapproved draft 0.05 on “contradicts the truth” in one run and 0.93 in the other. Luna’s largest change was 0.66, on the blog (0.30, then 0.96). In the first run one judge missed the blog as a contradiction and the other missed the draft. In the second run neither missed. Those were not stable weaknesses. They were noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKSGRAFE9LTRLM1109gTJw.png" /><figcaption><em>Figure 10. Largest change in any score between two full runs of the same prompts.</em></figcaption></figure><p>In practice: <strong>run an LLM judge several times and average, and do not draw conclusions from a single run.</strong> We saw this with a reasoning setting of “low”. We did not test other settings, so we cannot say how general it is.</p><p>The judges were also coarser, with scores in steps of 0.25 and relevance AUC of 0.93 rather than 1.00. They gave the irrelevant-but-official documents a “moderate” relevance of up to 0.75.</p><h3>4. A small model you host yourself is a strong option</h3><p>tev1 (4B), running on the laptop, reached AUC 1.00 on relevance, authority and contradiction and 0.93 on freshness. It took 44.8 seconds for the whole long set, and gave the <strong>identical</strong> answer on every run. nimble (9B) was similarly accurate (freshness AUC 0.87) but put one wrong document, the superseded policy, in its top three.</p><h3>5. Two systems that did not work for this task</h3><p><strong>The 0.8-billion-parameter model was too small.</strong> It rated nearly every document between 0.76 and 0.94 on relevance, including documents that were not about the question. Its relevance AUC was 0.67, and its contradiction AUC was 0.25, which is mostly backwards.</p><p><strong>SemIf</strong>, which turns a frozen general-purpose 4B model into a decision interface, did reasonably on relevance (AUC 0.93) and authority (1.00). It failed on contradiction, with AUC 0.12. That means it was nearly always <strong>backwards</strong>: it scored correct documents as more contradicting than wrong ones. It also ranked the superseded policy first. That fits its design. It is a baseline for the interface pattern, not a model tuned for these decisions, and our yes/no mapping may be unfair to it. Treat this as a result for our setup, not a verdict on the project.</p><h3>6. The reranker did what it is built to do, and no more</h3><p>On relevance, the reranker was excellent once it could read the whole document. bge-reranker-base truncates at 512 tokens. On our long documents that meant it never reached the refund clause in the middle, and every relevance score rounded to 0.00 (relevance AUC 0.60). Chunking the text into windows fixed that and brought relevance AUC to 1.00.</p><p>bge-reranker-v2-m3 reads up to 8,192 tokens and handled whole documents directly. It scored the highest NDCG of any system, 0.976, in 13.2 seconds for the whole set.</p><p>But look at what it did with the <em>wrong</em> documents. Even at 0.976, it ranked the unapproved draft and the superseded policy in positions 3 and 4, <strong>ahead of</strong> the official-but-unrelated documents. They are on topic, so it scores them as related. It cannot know they are wrong.</p><p>Its NDCG lead is also the same single swap of two correct documents described above, so we would not call it a win over the decision models. On the short set the picture was clearer: the two rerankers scored 0.83 and 0.85 NDCG and each put one wrong document in the top three, while the eight decision and judge systems scored 0.92 to 0.99 and put none there.</p><p>One fair point about context size: the reranker’s 8,192-token window fixes its <em>own</em> predecessor’s truncation. It is not larger than the decision models’ windows. Hosted Jev’s is 32,000 tokens and OpenJev’s is 16,384, and both were already reading every document in full.</p><h3>7. The wording of the question matters as much as the model</h3><p>We compared two phrasings of the contradiction question. The natural one was “does this document contradict any other evidence?” The correct document, D1, got marked as contradicting by several systems, because three other documents disagreed with it. The long set used a stricter phrasing: a document only counts as contradicting if its own claim is <strong>wrong or outdated compared with the most authoritative current evidence</strong>. With that wording the correct document scored 0.11 on hosted Jev and 0.00 to 0.15 on the judges.</p><p>If you build anything like this, spend time on how you phrase the contradiction question.</p><h3>8. Without source details, authority and freshness get harder</h3><p>The small-chunk tests were run in two variants: with the source title, type, date and status, and with only the text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYs2ch125bGX-lkwTfygIA.png" /><figcaption><em>Figure 11. Authority and freshness AUC with and without source details.</em></figcaption></figure><ul><li><strong>Authority fell for five of seven systems.</strong> GPT-5.6 terra dropped from 1.00 to 0.38, GPT-5.6 luna and the 4B Ollama model from 0.99 to 0.80, the 0.8B model from 0.97 to 0.77 and SemIf from 0.97 to 0.85.</li><li><strong>Two models kept it.</strong> nimble (0.98) and OpenJev (1.00) read authority from the text itself.</li><li><strong>Freshness fell for every system,</strong> to between 0.51 and 0.72. Some of that is unavoidable: a superseded policy cannot be recognised without a date or a version number, so this measures missing information as much as model skill.</li></ul><p>The ranking score held up better than authority and freshness (OpenJev and the 4B model did not fall at all), except for SemIf, which dropped from 0.93 to 0.76, about where the rerankers sit. If your index has no real source and date information, plan for the without-source-details numbers.</p><h3>At search scale: 15 chunks per question</h3><p>Eight documents is a small test, so we also reordered 15 retrieved chunks per question (see “The chunk-level set” above), on every system except hosted Jev. Three results stood out.</p><p><strong>Result 1: decisions beat a reranker.</strong> The decision systems ordered the chunks better. Their NDCG was 0.93 to 0.98 on small chunks and 0.93 to 0.99 on large ones, against 0.75 to 0.78 and 0.64 to 0.74 for the two rerankers. The rerankers also put one or two known-wrong chunks in their top three, and the decision systems put none there. (The rerankers never saw each chunk’s source type, date and status, so part of the gap is missing information, not skill.)</p><p><strong>Result 2: small chunks do not need summaries.</strong> Showing the raw text of the other 14 chunks worked as well as our hand-written summaries for five of the seven systems. Four of them scored a perfect contradiction AUC of 1.00.</p><p><strong>Result 3: for large chunks, how you show the other chunks matters.</strong> The 14 other large chunks add up to about 23,000 tokens, which is too much for most local models. Figure 12 compares four of the five ways from step 3 (the single raw request was too large to run on most models).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qmEVpuasMKwP4J110bfdA.png" /><figcaption><em>Figure 12. Contradiction AUC by how the other chunks are presented. Batches of 7 did better than 6 where we tried them.</em></figcaption></figure><ul><li><strong>Truncating was the worst.</strong> The first 120 words of a chunk often cut off the claim that mattered. The 4B model fell from 0.98 to 0.60, and GPT-5.6 terra from 0.98 to 0.75.</li><li><strong>Batching was slower and less accurate.</strong> Groups of 6 scored 0.92 for the 4B model and 0.90 for the 9B model, against 0.99 for the reference method, and took three to four times as long. On the two questions where we also tried groups of 7, scores were 0.05 to 0.07 higher, so the result depends on group size.</li><li><strong>The reference method worked best without summaries.</strong> It came within 0.03 of the hand-written summaries for the 4B model, the 9B model and both GPT-5.6 models. It did not help SemIf, which was weak at contradiction in every mode.</li></ul><h3>Rate limits, and how to get an answer in bounded time</h3><p>Timing is where the numbers can mislead.</p><p>Hosted Jev’s free tier on BeatAPI allowed about <strong>one request per minute</strong>. The long set took <strong>992.5 seconds</strong> end to end, of which <strong>960 were deliberate waiting</strong>. The actual processing was <strong>23.6 seconds</strong>, about 1.5 seconds per request. Rate limits are a property of the plan, not the model. TypeSafe’s documentation lists the paid Jev 1.13 model at 80 requests per second and 100,000 tokens per second, and says limits may change without notice. We did not test a paid plan, so we cannot confirm those numbers. We rechecked the documentation on 7 October: it still lists 80 requests per second, 100,000 tokens per second and 64,000 tokens per request, and still says limits may change without notice. BeatAPI, the gateway we used, listed only the free Jev model, and its documentation says the request-rate allowance rises with lifetime top-ups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dYE1zRmz958L4DtWc-KciQ.png" /><figcaption><em>Figure 13. Seconds per request (log scale), and where hosted Jev’s 992.5 seconds went. The remaining 8.9 seconds is other overhead.</em></figcaption></figure><p>The slow local system was OpenJev, at about <strong>37 seconds per request</strong> (592 seconds for the set) on the laptop. Part of the reason is how we served it. Each of the five score questions about a document re-reads the whole document from scratch, so a document costs about six full reads. The original helper is built for a server with prefix caching, where the questions share one read. We later added a prefix cache to our local server so the questions share one read (see the section on summarising large chunks). On eight large chunks it cut the full-text decision stage from about 283 s in an earlier run to 162 s, and scores moved by at most 0.03 on a 0 to 4 scale.</p><p>Sequential requests do not scale, so we would run the decisions in <strong>two stages, each sent as parallel requests</strong>. Stage 1 scores every candidate at once. Stage 2 checks every candidate for contradiction at once. In the reference method stage 2 needs the stage 1 scores, which is why the stages run one after the other. A shortlist’s decision time is then about two rounds. With N candidates, C requests served at once and L seconds per request:</p><pre>decision time ≈ 2 x ceil(N / C) x L</pre><p>For a shortlist of 15 documents, that works out to about 30 minutes on the free hosted tier (one request a minute), about 44 seconds one request at a time, about 6 seconds with ten requests at once, about 3 seconds with all 15 at once (a third-party report of 17 concurrent decisions finishing in about 7.6 seconds suggests the real figure could be closer to 8), and about 18 minutes one at a time on the laptop with OpenJev (measured later, with the prefix cache and 8 large chunks: about 3 minutes on full text and under a minute on summaries). GPT-5.6 Luna, at 3.5 seconds per request, would take about 7 seconds with all 15 at once. That is arithmetic from our measurements, not a new benchmark. We never ran hosted Jev with parallel requests, so the 3 seconds is a best case that assumes a paid plan serves them without queueing. Long documents also matter: 15 of ours are about 115,000 input tokens per stage, which is over TypeSafe’s published limit of 100,000 tokens per second, so tokens rather than requests would set the pace. Small chunks do not hit that limit.</p><p><strong>Capacity: queries per second, not only seconds per query.</strong> A 15-candidate shortlist sends about 30 requests (two per candidate), and our 8-chunk runs sent 16. At TypeSafe’s published 80 requests per second, 16 requests per query caps one account at roughly 5 queries per second. The 100,000 tokens-per-second limit can bind first when chunks are large: eight 1.8k-token chunks in full text are around 130,000 input tokens per query (our estimate), so one query sent as a burst would exceed it. Summarising first brings that down to roughly 12,000. These figures are arithmetic from the published limits, which we have not tested. Because one query fires its requests together, use a single shared limiter across all users and put a queue in front of it, so a burst of queries slows down instead of returning 429 errors.</p><p>To keep a pipeline inside a time budget:</p><ul><li><strong>Cap the shortlist.</strong> Make N a function of your time budget.</li><li><strong>Run each stage as parallel requests</strong> on a backend that allows it. Sequential requests do not scale.</li><li><strong>Send the judge only the best-matching passages</strong> instead of whole documents. Check on your data that accuracy holds.</li><li><strong>Choose a smaller model tier</strong> if latency matters more than the last bit of accuracy.</li><li><strong>Set a hard deadline and a fallback.</strong> If the judge is too slow, return the reranker’s order and mark authority, freshness and contradiction as unchecked.</li></ul><h3>Large chunks: summarise first, then decide</h3><p>Once chunks are large, the decision stage is the slow part. Every request has to read them, and the contradiction check reads the other chunks as well. We added one step in our test app, Jev Lab. After the reranker keeps the top 8 chunks, a fast model (GPT-5.6 Luna) writes a summary of each chunk, all at once, and the decision model reads the summaries instead of the full text. A summary is at most 120 words, is written for the user’s question, and is told to keep numbers, dates, conditions and hedges such as “draft” or “replaced”. Chunks shorter than about 180 tokens skip the step. Source details (title, type, date, status) are still sent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUjNfX3m5dt-0nSz44RwLg.png" /><figcaption><em>Figure 14. The pipeline in Jev Lab. Summaries are written in parallel, then one decision request per chunk is sent in parallel.</em></figcaption></figure><p>We ran it on the three large 15-chunk datasets, with OpenJev on a laptop and a prefix cache, and compared the top 8 chunks as full text and as summaries. Run time is rerank plus summaries plus decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*_ccDShaHoDvDlzqBVyFrug.png" /></figure><p>Summaries were about 3.5 times faster end to end. Writing them took 2 to 3 s in total, and about 14.5k tokens of chunks became under 1k. Quality matched on two datasets. On the third, the correct chunk scored 0.987 and another correct chunk scored 0.988, so they swapped places, which is why the mean fell from 0.943 to 0.902. Contradiction detection stayed perfect: the AUC was 1.000 on all three datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUnZw11fdxUnidHlvU5EAg.png" /><figcaption><em>Figure 15. Seconds per query for full text and for summaries (mean of three datasets, one run each).</em></figcaption></figure><p><strong>Can a GPT judge do the decisions instead?</strong> We also ran GPT-5.6 Luna and Terra as the decision system on the same summaries, twice each, and measured contradiction detection (AUC) on the chunks we know conflict with the answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*mWOQ7BBXzTctDh1SmDTgqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvgtrB1VCDIE-eQQJVba_g.png" /><figcaption><em>Figure 16. The same summaries, three decision systems. Two of the axes do not start at zero.</em></figcaption></figure><ul><li><strong>Contradictions:</strong> the GPT judges are close, but they gave non-conflicting chunks about 10 times higher contradiction scores (0.10 against 0.01), so they raise more false alarms.</li><li><strong>Ranking:</strong> GPT scores come in coarse steps (0, 0.25, 0.5, 0.75, 1), so several good chunks tie near 1.0 and the right one is often not first. On one dataset Luna ranked it third in every run.</li><li><strong>Consistency:</strong> Luna’s ranking score on full text moved from 0.773 to 0.847 between two runs.</li><li><strong>Summaries did not hurt the GPT judges on contradiction.</strong></li><li><strong>Speed:</strong> about 6 s against 34 s.</li></ul><p><strong>Can a smaller local model do the decisions?</strong> We ran two Ollama models on the same summaries: nimble 9B and tev1 4B (one run per cell, three datasets).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3jUSZjpOgpp7GNBaEoz5Kw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aArhQk5oRuAhBL7VMLxrIw.png" /><figcaption><em>Figure 17. The same summaries, three local decision models. The ranking axis does not start at zero.</em></figcaption></figure><ul><li><strong>Ranking tied.</strong> All three scored 0.902 and all three separated the conflicting chunks perfectly (AUC 1.00). The same near-tie on one dataset swapped the top two in every run.</li><li><strong>Decisiveness differs.</strong> The 9B separated conflicting chunks as sharply as OpenJev, in about a quarter of the decision time. The 4B was faster still but less decisive.</li><li><strong>Parallel requests did not help.</strong> Sending four requests at once to Ollama took the same time as four in a row (1.06 times on short prompts, 0.92 times on long ones), so the gain comes from model size.</li><li><strong>More context did not help the 4B.</strong> On full text its contradiction scores were muddier (0.57 against 0.20) than on summaries (0.72 against 0.08).</li><li><strong>A longer summary or a stronger summarizer did not help either.</strong> Asking for up to 250 or 400 words left the summaries the same size, because the summarizer only writes what bears on the question, and GPT-5.6 Terra as the summarizer was no better than Luna at about ten times the price.</li></ul><p><strong>What this means for scale.</strong> The decision stage on a large local model is the cost that remains, and a smaller one cuts it sharply: a 9B model took about 12 s against 41 s for OpenJev on summaries. A hosted tier could remove it if the rate limits allow, and summaries help because they send far fewer tokens, but we have not tested a paid plan. The limits above are TypeSafe’s published numbers. Our evidence is small: three datasets with one query each, one OpenJev run per cell against two per GPT model, and one summarizer. The summarizer is a cloud model, so the document text leaves your machine.</p><h3>What we would actually build</h3><p>The results point to a pipeline with decisions added on top of search, not a single winner:</p><ol><li><strong>Retrieve</strong> with hybrid search: BM25 plus semantic search, merged with RRF.</li><li><strong>Shortlist</strong> the top 10 to 20 documents, optionally reranking them first. A reranker is fast and cheap, and relevance is the one thing it does well.</li><li><strong>Augment with decisions.</strong> Judge the shortlist with a Jev-style model on authority, freshness and contradiction, in two parallel stages of small requests. Send real source details (title, type, date, status) if your index has them. For contradiction, compare each chunk with the few chunks the model itself rates most authoritative and current, not with truncated copies of everything. For large chunks, first have a fast model write a short summary of each shortlisted chunk, all at once, and decide on the summaries (see the section above).</li><li><strong>Combine</strong> the scores, keeping the contradiction penalty, and show the user the official source.</li></ol><p>Decision augmentation is an additional stage, not a replacement. Retrieval still finds the candidates, and the decisions run only on the shortlist. We tested the reranking and decision stages. We did not test BM25, semantic search or RRF, so we make no claim about how they compare.</p><p><strong>For a knowledge graph,</strong> the same stage applies with different candidates:</p><ol><li><strong>Retrieve</strong> the candidate facts for the entity and property, each with the source it came from.</li><li><strong>Judge each fact.</strong> Score the authority and freshness of its source, and check whether the fact contradicts the best-supported one for the same property.</li><li><strong>Resolve.</strong> Return the winning fact, flag the conflicting ones, or store the scores as weights on the links.</li></ol><h3>What it costs: hosted or self-hosted</h3><p>The decision stage can run in two ways, and they are paid for differently.</p><p><strong>Hosted API: you pay per token.</strong> List prices in October 2026:</p><ul><li><strong>Jev 1.13:</strong> $0.042 per million input tokens, and output is free (TypeSafe documentation).</li><li><strong>GPT-5.6 Luna:</strong> $0.20 per million input tokens and $1.20 per million output tokens.</li><li><strong>GPT-5.6 Terra:</strong> $2 per million input tokens and $12 per million output tokens.</li></ul><p>The GPT-5.6 prices are Azure OpenAI Standard Global rates. Azure matched OpenAI’s price cut from 1 August 2026, and Data Zone and other deployment types are priced differently, so check your invoice.</p><p>One of our long documents took about 15,000 input tokens across its two requests. That works out to about <strong>$0.65 per 1,000 documents on hosted Jev, $3.11 on Luna and $30.72 on Terra.</strong> Shorter chunks cost proportionally less, because tokens drive the bill. We tested hosted Jev’s free model and priced its tokens at the paid Jev 1.13 rate, which assumes similar token counts.</p><p><strong>Self-hosted: you pay for the machine.</strong> An open model such as tev1 (4B) has no per-token charge. You pay for the hardware instead. A GPU instance such as an AWS g6.xlarge costs about $0.80 per hour on demand, or about $590 a month if it runs all the time. At that price it costs the same as hosted Jev&#39;s per-token price at about 1,200 long documents an hour. Below that sustained volume, hosted is cheaper. Above it, self-hosting wins only if the machine can actually serve that rate, which we did not measure on a cloud GPU. Our latency numbers come from a laptop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*loCyQbjDBcc0XQAcmZ5EUA.png" /><figcaption><em>Figure 18. Cost, and estimated decision time for a 15-candidate shortlist in two parallel stages.</em></figcaption></figure><p><strong>Cost per query, and when this pays off.</strong> For eight large chunks (about 1.8k tokens each), these are our estimates from list prices, not billed amounts:</p><ul><li><strong>Full text on hosted Jev:</strong> about 130,000 input tokens, so about $0.0055 per query.</li><li><strong>Summaries on Luna, decisions on hosted Jev:</strong> Luna reads about 14,500 tokens and writes about 900 (about $0.004), and the decisions read about 12,000 tokens (about $0.0005), so about $0.0045 per query.</li></ul><p>So summarising buys speed and rate-limit headroom, not a lower bill. Cost also grows faster than the number of chunks in full text, because each contradiction request carries every other chunk: 8 chunks send about 115,000 tokens for contradiction and 16 chunks would send about 460,000. Summaries or the reference method (compare against only the top three) flatten that curve.</p><p>It pays off when chunks are long, the step runs on every query, and your rules change often, because a policy update needs new instructions rather than retraining. For short chunks and occasional use, a cheap LLM judge may be close enough on cost, although in our tests the GPT judges ranked less consistently.</p><p>Our reading: for most RAG workloads the hosted per-token cost is a few dollars per thousand documents, so the case for self-hosting is usually privacy, data residency or sustained high volume, not price alone.</p><h3>Limits of what we did</h3><p>This was a small, careful test, not a definitive one. Before relying on it:</p><ul><li><strong>We tested part of the pipeline.</strong> The test starts from a fixed set of candidate documents, so it covers reranking and decisions only. BM25, semantic retrieval and RRF were not tested.</li><li><strong>The long set is one question and eight documents.</strong> NDCG differences below about 0.1 are noise. Repeat the test with 30 to 50 real questions and real documents.</li><li><strong>The chunk-level tests are small too:</strong> three questions, one query each, synthetic filler and our own labels, with some cells (the largest raw requests and OpenJev on large chunks) run once. Hosted Jev was not run at this scale, and the reference method was evaluated only with source details present.</li><li><strong>The long set used hand-written summaries</strong> of the other documents for the contradiction check. We later tested generated summaries (see the section on summarising large chunks): they cost some ranking quality on one dataset, and a summary can still miss a claim.</li><li><strong>The gold labels are ours.</strong> The D1 versus D7 order is genuinely arguable, and so is the “low relevance” label on the Enterprise contract, which does discuss refunds.</li><li><strong>The documents are synthetic.</strong> The filler text is template-generated and repetitive. Real documents may be harder or easier.</li><li><strong>The summary and judge tests are small.</strong> Three datasets with one query each, one OpenJev run per cell against two per GPT model, and GPT-5.6 Luna wrote every summary. We did not try asking the GPT judges for finer scores or averaging repeated calls, which might narrow the ranking gap. The local-model comparison (9B and 4B) is one run per cell on the same three datasets. The OpenJev numbers use a prefix cache we added to the local server, and its scores differed from the uncached server by up to 0.03 on a 0 to 4 scale.</li><li><strong>Cost is estimated, not billed.</strong> It uses list prices and the token counts we measured. We tested hosted Jev’s free model through BeatAPI and priced it at the paid Jev 1.13 rate, we did not run a paid plan or a cloud GPU, and prices change. Other hosts and plans may behave differently.</li><li><strong>Licences differ.</strong> OpenJev’s weights are non-commercial (CC BY-NC 4.0). SemIf is MIT licensed. Both are independent of TypeSafe.</li></ul><pre>Test environment: <br>MacBook Pro (Apple M5 Max, 18 cores, 48 GB) for local systems; <br>hosted Jev through BeatAPI (free tier); <br>Azure OpenAI for GPT-5.6. </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e405e6f8472" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sequence classification techniques for imbalanced datasets (Part-3)]]></title>
            <link>https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-3-35f37c2dd944?source=rss-19d25161bec8------2</link>
            <guid isPermaLink="false">https://medium.com/p/35f37c2dd944</guid>
            <category><![CDATA[imbalanced-data]]></category>
            <category><![CDATA[imbalanced-dataset]]></category>
            <category><![CDATA[sequence-classifier]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Manoj Kumar Vohra]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 07:04:20 GMT</pubDate>
            <atom:updated>2024-01-22T07:04:20.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHRTz4kudtQuM6nwFNEC6A.jpeg" /></figure><p>In <a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-1-e457837525fc">part-1</a> of this series, we discussed the approach of using a custom loss function using which we boosted the loss calculation of minority classes w.r.t majority classes.</p><p>In <a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-2-02ebd0d05e5c">part-2</a>, we discussed the approach of random oversampling and inherent limitations of that approach.</p><p>In this part, we will be discussing another oversampling technique which generates synthetic samples of minority classes using a language model and try to equalise the class distribution.</p><h3>Resources</h3><p><strong>Dataset used</strong></p><p>For this use case, I modified the dataset <a href="https://huggingface.co/datasets/dair-ai/emotion">dair-ai/emotion</a> and created a new dataset by generating synthetic samples of the minority classes using a language model.</p><p>The synthetic samples are grammatical variations of the actual datasets with alternative synonyms, conjunctions, adverbs etc.</p><p>Please find below some examples for class-2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3zOHwM0HLWJuURtOpKUZg.png" /><figcaption>actual samples</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YKkxLmwSTG-BLpSewPqiAw.png" /><figcaption>synthetic samples</figcaption></figure><p>You can locate dataset here: <a href="https://huggingface.co/datasets/manojkumarvohra/amplified_emotions">manojkumarvohra/amplified_emotions</a></p><h4>Class Distribution</h4><p>In the class distribution, you would see all the classes have equal representation in the training dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T7OkGSzopFiCOvIv_KIFsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gz2TircYQcj9V1QGXrIuiw.png" /></figure><p><strong>Language model used</strong></p><p>We will be leveraging “distilbert-base-uncased” model for this classification task. You can refer the model card <a href="https://huggingface.co/distilbert-base-uncased">here</a> to understand more about the model.</p><p><strong>Notebooks used</strong></p><p><a href="https://colab.research.google.com/drive/1xf0de8B-4G6P5j2vIeDitw2yOCfGMCwf?usp=sharing">Classification with synthetic balanced dataset</a></p><h3>RECAP</h3><h4>Baseline Classification</h4><p>In <a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-1-e457837525fc">part-1</a> of this series, we performed classification on original dataset: <a href="https://huggingface.co/datasets/dair-ai/emotion">dair-ai/emotion</a> and achieved the baseline results shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*6PsdtX7yRAmOgC1BZaDZfQ.png" /><figcaption>baseline results</figcaption></figure><h4>Weighted Loss based Classification</h4><p>In <a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-1-e457837525fc">part-1</a> of this series, we performed classification on original dataset: <a href="https://huggingface.co/datasets/dair-ai/emotion">dair-ai/emotion</a> with a custom loss function. The results for that are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*R1oExTkRSE1pLUnE-gEmvA.png" /><figcaption>results with weighted loss function</figcaption></figure><h4>Classification with duplicates</h4><p>In <a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-2-02ebd0d05e5c">part-2</a> of this series, we performed classification on dataset with duplicates <a href="https://huggingface.co/datasets/manojkumarvohra/replicated_emotions">manojkumarvohra/replicated_emotions</a> and achieved below results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QpwFgqlR2P0O8RQtZgJzw.png" /><figcaption>results with duplicate samples</figcaption></figure><h3>Classification with amplification</h3><p>Now we will perform classification with the new dataset with synthetic/amplified samples: <a href="https://huggingface.co/datasets/manojkumarvohra/amplified_emotions">manojkumarvohra/amplified_emotions</a></p><p>The notebook for this one is located <a href="https://colab.research.google.com/drive/1xf0de8B-4G6P5j2vIeDitw2yOCfGMCwf?usp=sharing">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ADwfp3KIRxqhSGoHZ5Q4Q.png" /><figcaption>loading dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*612KYMI30pkQgIxrUXN0mQ.png" /><figcaption>training cycle</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rf864B5Nt5oHjdSoMMoejg.png" /><figcaption>classification report</figcaption></figure><p>If we check, with amplification we are able to achieve best f1-score for class 2 and class 5 as compared with all other techniques tried so far.</p><h3>Limitations</h3><p>While we are able to achieve the highest accurate results so far with synthetic sample generation technique, this technique also comes with its own set of challenges and limitations.</p><h4>Sensitivity to Noisy Data</h4><p>This technique may generate synthetic instances in regions of the feature space that contain noisy or irrelevant examples. This can lead to the introduction of noise in the dataset, potentially impacting the performance of the model.</p><h4>Doesn’t Address Inherent Class Overlapping</h4><p>We assumes that minority class instances can be effectively interpolated in feature space. If the minority class is inherently overlapped with the majority class, the technique may not capture the true underlying distribution, and the generated synthetic instances might not be representative.</p><h4>Amplification Intensity</h4><p>We generated synthetic variations in range of 10 to 20 for each actual sample. However if the minority representation in actual dataset is severely low then this amplification would not help. It would be hard to generate 100 representations of a single sample which are grammatically unique.</p><h4>Potential for Overfitting</h4><p>While the technique aims to reduce overfitting compared to simple random oversampling, it may still lead to overfitting in certain situations. The synthetic instances generated may not fully capture the complexity of the true underlying patterns.</p><h3>Conclusion</h3><p>In conclusion, Synthetic Minority Oversampling is a powerful oversampling method designed to address class imbalance in machine learning datasets. It stands out for its ability to generate synthetic instances for the minority class, thereby balancing class distribution and reducing the risk of overfitting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35f37c2dd944" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sequence classification techniques for imbalanced datasets (Part-2)]]></title>
            <link>https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-2-02ebd0d05e5c?source=rss-19d25161bec8------2</link>
            <guid isPermaLink="false">https://medium.com/p/02ebd0d05e5c</guid>
            <category><![CDATA[sequence-classifier]]></category>
            <category><![CDATA[imbalanced-dataset]]></category>
            <category><![CDATA[imbalanced-class]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Manoj Kumar Vohra]]></dc:creator>
            <pubDate>Mon, 22 Jan 2024 06:25:46 GMT</pubDate>
            <atom:updated>2024-01-22T07:06:51.941Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRqPpqWjTelKxWhAwLFKyA.jpeg" /></figure><p>In <a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-1-e457837525fc">part-1</a> of this series, we discussed the approach of using a custom loss function using which we boosted the loss calculation of minority classes w.r.t majority classes.</p><p>In this part, we will discuss a oversampling technique to modify the dataset so that all the classes have equal representation.</p><p>The simplest oversampling technique is random oversampling.</p><p>Random oversampling is a straightforward technique used to address class imbalance in a dataset by randomly duplicating instances from the minority class until a more balanced distribution is achieved.</p><p>The idea is to increase the number of instances in the minority class to make it comparable to the majority class.</p><p>The next part [<a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-3-35f37c2dd944">part-3</a>], discussed another approach which is Synthetic Minority Oversampling to solve the imbalance.</p><h3>Resources</h3><p><strong>Dataset used</strong></p><p>For this use case, I modified the dataset <a href="https://huggingface.co/datasets/dair-ai/emotion">dair-ai/emotion</a> and created a new dataset by duplicating random samples of the minority classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*zAmJKUKrpnLN4QSy8IUTfg.png" /></figure><p>The new dataset is present here: <a href="https://huggingface.co/datasets/manojkumarvohra/replicated_emotions">manojkumarvohra/replicated_emotions</a></p><p>With this one, if you check the class distribution you would see all the classes have equal representation in the training dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKH7rPjJWxRpL7xRMGrHjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gz2TircYQcj9V1QGXrIuiw.png" /></figure><p><strong>Language model used</strong></p><p>We will be leveraging “distilbert-base-uncased” model for this classification task. You can refer the model card <a href="https://huggingface.co/distilbert-base-uncased">here</a> to understand more about the model.</p><p><strong>Notebooks used</strong></p><p><a href="https://colab.research.google.com/drive/1V0i4tx0CxZk9EcsJ-jlyAgXtyuo3w81q?usp=sharing">Classification with stock trainer with replication</a></p><h3>Baseline Classification</h3><p>In <a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-1-e457837525fc">part-1</a> of this series, we performed classification on original dataset: <a href="https://huggingface.co/datasets/dair-ai/emotion">dair-ai/emotion</a> and achieved the baseline results shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*6PsdtX7yRAmOgC1BZaDZfQ.png" /><figcaption>baseline results</figcaption></figure><h3>Classification with duplication</h3><p>The notebook for this strategy is present <a href="https://colab.research.google.com/drive/1V0i4tx0CxZk9EcsJ-jlyAgXtyuo3w81q?usp=sharing">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFOwb4qEVqdp9LTP0SIRjg.png" /><figcaption>loading dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ske_Ebzkkc_MFdClIwndzw.png" /><figcaption>performing training</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_QpwFgqlR2P0O8RQtZgJzw.png" /></figure><p>If we check, with duplication we are able to achieve better f1-score for class 2 and class 5 as compared with baseline.</p><h3>Limitations</h3><p>While random oversampling is a simple technique to address class imbalance, it comes with certain limitations that should be considered:</p><h4>Risk of Overfitting</h4><p>Randomly duplicating instances from the minority class increases the likelihood of overfitting. The model might memorize the duplicated instances rather than learning the underlying patterns in the data. This can lead to poor generalization to new, unseen data.</p><h4>No Generation of New Information</h4><p>Random oversampling duplicates existing instances, providing no new information to the model. This can be problematic when the minority class is already limited in terms of diverse examples.</p><h4>Potential for Model Biases</h4><p>Duplicating instances might introduce biases into the model, especially if the minority class instances are not representative of the true underlying distribution. This can result in a model that is sensitive to the specific instances duplicated.</p><h4>Doesn’t Address Inherent Class Imbalance</h4><p>Random oversampling does not address the underlying reasons for class imbalance. It may not be effective in situations where the minority class has a diverse distribution or where there is a significant overlap with the majority class.</p><h3>Conclusion</h3><p>We saw random oversampling may lead to slightly better classification accuracy but it comes with its own set of limitations.</p><p>In the next part [<a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-3-35f37c2dd944">part-3</a>] of this series, we will discuss another oversampling technique called SMOTE which can address some of these limitations.</p><p>Until then, stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02ebd0d05e5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sequence classification techniques for imbalanced datasets (Part-1)]]></title>
            <link>https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-1-e457837525fc?source=rss-19d25161bec8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e457837525fc</guid>
            <category><![CDATA[sequence-classifier]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[imbalanced-dataset]]></category>
            <category><![CDATA[imbalanced-classification]]></category>
            <dc:creator><![CDATA[Manoj Kumar Vohra]]></dc:creator>
            <pubDate>Sat, 30 Dec 2023 11:57:30 GMT</pubDate>
            <atom:updated>2024-01-22T07:05:10.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*srT6vLxTA-mqsyEWTM7AWA.jpeg" /></figure><p>Sequence classification tasks often encounter imbalanced datasets, where certain classes are significantly underrepresented, posing challenges for accurate model training. Addressing this issue requires specialised techniques to ensure fair and effective learning across all classes.</p><p>We will explore multiple techniques in this series to address these issues.</p><p>In this article, part-1, we explore the utilisation of weighted cross-entropy loss as a pivotal strategy to tackle the imbalance problem in sequence classification.</p><p>In the subsequent parts [<a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-2-02ebd0d05e5c">part-2</a>, <a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-3-35f37c2dd944">part-3</a>], we will tap on other techniques like under-sampling, over-sampling, synthetic over sampling (SMOTE), hybrid techniques to fix these issues.</p><h3>Resources</h3><p><strong>Dataset used</strong></p><p>In this use case, we will be doing classification of emotions on six different aspects: ‘sadness’, ‘joy’, ‘love’, ‘anger’, ‘fear’, ‘surprise’.</p><p>The dataset is publicly available on huggingface <a href="https://huggingface.co/datasets/dair-ai/emotion">here</a>.</p><p><strong>Language model used</strong></p><p>We will be leveraging “distilbert-base-uncased” model for this classification task. You can refer the model card <a href="https://huggingface.co/distilbert-base-uncased">here</a> to understand more about the model.</p><p><strong>Notebooks used</strong></p><p><a href="https://colab.research.google.com/drive/1_2D4OWbqwH_uvyUvCKufnvgKTiFRpToc?usp=sharing">Classification with stock trainer</a></p><p><a href="https://colab.research.google.com/drive/1XM39X4dLNoB50wADpBV6cMG40aFpByyJ?usp=sharing">Classification with custom weighted loss function</a></p><h3>Understanding the dataset</h3><p>Emotion is a dataset of English Twitter messages with six basic emotions: anger, fear, joy, love, sadness, and surprise.</p><p>The dataset 20K rows of mixed emotions text messages. The dataset is split in tranches with around 16K training samples, 2K validation samples and 2K test samples.</p><p>If we look at the bin distribution of 16K training samples, you will see that majority data is represented by sadness and joy while love and surprise make the minority classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*G5v0FFB2CyZ6bltqs7I9Gg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*8fc0WaWZjatD0y-5DgcVtA.png" /></figure><h3>Perform Baseline Classification</h3><p>We will first perform classification to derive the baseline metrics with stock model and trainer.</p><p>The complete notebook is present <a href="https://colab.research.google.com/drive/1_2D4OWbqwH_uvyUvCKufnvgKTiFRpToc?usp=sharing">here</a>.</p><pre>from transformers import AutoModelForSequenceClassification<br>model = AutoModelForSequenceClassification.from_pretrained(&quot;distilbert-base-uncased&quot;, <br>                                                           num_labels=6,  <br>                                                           id2label=id2label, <br>                                                           label2id=label2id)</pre><p>Training this model on our dataset for 5 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XiktkJxlJvg4-xI9Ra1wxA.png" /></figure><p>For classification tasks, we must understand the associated metrics properly. The basic definitions are discussed below but for a detailed walkthrough do consider reading this <a href="https://towardsdatascience.com/a-look-at-precision-recall-and-f1-score-36b5fd0dd3ec">article</a>.</p><p><strong>Precision</strong></p><p><em>Precision</em> is a measure of how many of the positive predictions made are correct (true positives).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*EcyqmaA8-z50kSrqPvJBHw.png" /></figure><p><strong>Recall</strong></p><p><em>Recall</em> is a measure of how many of the positive cases the classifier correctly predicted, over all the positive cases in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*bAKWEv1kcYg4fwPmEmvZ8Q.png" /></figure><p><strong>f1-score</strong></p><p>F1-Score is a measure combining both precision and recall. It is generally described as the <a href="https://en.wikipedia.org/wiki/Harmonic_mean">harmonic mean</a> of the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*3JaPCZZUuwH_ZWvJ1k9XcQ.png" /></figure><h4>Understanding baseline results</h4><p>The baseline classification metrics against test dataset is present below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*6PsdtX7yRAmOgC1BZaDZfQ.png" /><figcaption>classification results with stock trainer</figcaption></figure><p>If you see both class 2 i.e. love and class 5 i.e. surprise have got a very low f1 score as compared with other classes.</p><p>Lets see how we can boost the weights of minority classes so as they are given more importance during loss calculation in trainer.</p><h3><strong>Weighted Cross Entropy Loss</strong></h3><p>The notebook for this strategy is present <a href="https://colab.research.google.com/drive/1XM39X4dLNoB50wADpBV6cMG40aFpByyJ?usp=sharing">here</a></p><p>As we saw, traditional approaches, reliant on standard cross-entropy loss, exhibit biases toward majority classes, leading to suboptimal performance in recognising and classifying minority sequences.</p><p>To mitigate these limitations, we delve into the concept of weighted cross-entropy loss — a technique designed to rebalance the learning process by assigning differential weights to classes based on their prevalence within the dataset. This method grants higher importance to underrepresented classes during model training, fostering a more equitable learning process.</p><p>Here we define weights for each of the classes based on their “inverse” proportion in the sample set. Based on this the weights for the miniroty classes are enhanced in comparison with majority classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPFBjfAhiRqFWk3n8edCWw.png" /></figure><p>We then define a custom huggingface Trainer which computes loss based on the wighted cross entropy function.</p><p><em>Please note, your model can compute the loss if a </em><em>labels argument is provided and that loss is returned as the first element of the tuple (if your model returns tuples)</em></p><pre>from transformers import Trainer<br>from torch import nn, torch<br><br>class WeightedLossTrainer(Trainer):<br>    <br>    def compute_loss(self, model, inputs, return_outputs=False):<br>        <br>        outputs = model(**inputs)<br>        logits = outputs.get(&quot;logits&quot;)<br>        labels = inputs.get(&quot;labels&quot;)<br>        <br>        loss_func = nn.CrossEntropyLoss(weight=class_weights)<br>        loss = loss_func(logits, labels)<br>        <br>        return (loss, outputs) if return_outputs else loss</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PmrYkBcy2EhtCj4iXzreSw.png" /></figure><p><strong>Classification results with custom trainer</strong></p><p>If you check, with our custom approach, the f1-score for minority classes is enhanced as compared with previous stock approach without effecting the scores for majority classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*R1oExTkRSE1pLUnE-gEmvA.png" /><figcaption>classification results with custom trainer</figcaption></figure><h3>Limitations</h3><p>Weighted cross-entropy loss is a powerful technique for addressing imbalanced datasets in classification tasks, but it does come with certain limitations and considerations:</p><p><strong>Sensitivity to Weight Selection</strong></p><p>The effectiveness of weighted cross-entropy loss heavily relies on the appropriate selection of class weights. If these weights are not chosen accurately, it might lead to suboptimal performance or even exacerbate the problem. Determining these weights can be challenging and might require domain knowledge or experimentation.</p><p><strong>Risk of Overfitting</strong></p><p>When dealing with highly imbalanced datasets, assigning significantly higher weights to minority classes might cause the model to overfit on these specific instances, potentially leading to poorer generalization on unseen data.</p><p><strong>Impact on Majority Classes</strong></p><p>While the focus is often on improving the performance of minority classes, applying high weights to these classes can inadvertently affect the learning process for majority classes. This might cause the model to underperform or misclassify instances from these dominant classes.</p><p><strong>Robustness to Noise and Outliers</strong></p><p>Weighted cross-entropy loss might be sensitive to noise or outliers within the minority classes, potentially causing the model to overly prioritise noisy examples due to their higher weights.</p><p><strong>Difficulty in Weight Determination</strong></p><p>It can be challenging to determine the ideal weights, especially in situations where the class imbalance is not straightforward or where classes have varying degrees of importance.</p><p><strong>Performance Impact on Well-Balanced Datasets</strong></p><p>In datasets that are relatively balanced or have mild class imbalances, using weighted cross-entropy loss might not significantly improve performance and could potentially lead to unnecessary complications in model training.</p><h3>Conclusion</h3><p>We saw that weighted cross entropy loss helps in classification of minority classes but it comes with its own set of challenges.</p><p>In the subsequent parts [<a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-2-02ebd0d05e5c">part-2</a>, <a href="https://medium.com/@manojkumarvohra9/sequence-classification-techniques-for-imbalanced-datasets-part-3-35f37c2dd944">part-3</a>] of this series, we will discuss other approaches such as resampling techniques (oversampling, under sampling) or other advanced algorithms designed explicitly for handling imbalanced datasets, in conjunction with or instead of weighted loss strategies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e457837525fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG on knowledge graphs using Zephyr-7B]]></title>
            <link>https://medium.com/@manojkumarvohra9/rag-on-knowledge-graphs-using-zephyr-7b-2f34f99a9747?source=rss-19d25161bec8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f34f99a9747</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[zephyr]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Manoj Kumar Vohra]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 10:20:07 GMT</pubDate>
            <atom:updated>2023-12-08T15:38:09.836Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>In this article, we will learn to build a RAG framework leveraging information from knowledge graphs.</p><p>We will be using below components in this framework:</p><p><strong>Neo4j</strong> as the knowledge graph</p><p><strong>Zephyr-7B</strong> as the underlying language model from HuggingFace H4</p><p><strong>Langchain </strong>for end to end stitching</p><h3><strong>Understanding the components</strong></h3><h4><strong>The knowledge graph</strong></h4><p>We will be using a dummy dataset of movies and actors connected with each other with different types of relationships. Please refer the schema below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYtwtnlEW0zx6Wv6VutJmQ.png" /><figcaption>Graph Schema</figcaption></figure><p>Here Person belongs to an entity which can play multiple role like an actor, producer, director, critic etc. A person node contains information like name of person and year of birth.</p><p>The Movie entity is the main entity and carries information like title, release year and tagline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfVXXZLlZExO-aj2Ly5Pjw.png" /><figcaption>Graph Sample Set</figcaption></figure><h4><strong>Zephyr language model</strong></h4><p>Zephyr is a series of language models, from HuggingFace, that are trained to act as helpful assistants. Zephyr-7B-β is the second model in the series, and is a fine-tuned version of <a href="https://huggingface.co/mistralai/Mistral-7B-v0.1">mistralai/Mistral-7B-v0.1</a> that was trained on on a mix of publicly available, synthetic datasets using <a href="https://arxiv.org/abs/2305.18290">Direct Preference Optimization (DPO)</a>.</p><p>For more details refer the <a href="https://huggingface.co/HuggingFaceH4/zephyr-7b-beta">model card here</a>.</p><h4><strong>Neo4j vector index</strong></h4><p><em>We will not go in details of what a vector index or database is here. You can follow dedicated spaces on this topic in public knowledge hubs.</em></p><p>Neo4j released its vector index as a public beta in Neo4j 5.11 and general availability in Neo4j 5.13.</p><p>Neo4j vector indexes are powered by the <a href="https://lucene.apache.org/">Apache Lucene</a> indexing and search library. Lucene implements a Hierarchical Navigable Small World (HNSW) Graph to perform a <em>k</em> approximate nearest neighbors (<em>k</em>-ANN) query over the vector fields.</p><p>Before generating the index, you have to generate vector embeddings and store that as a property (or vector fields) in the graph nodes. These vector embeddings are stored as LIST&lt;FLOAT&gt; properties on a node, where each dimensional component of the vector is an element in the LIST.</p><p>To generate embeddings we can use inbuilt Neo4j ML procedures which have support with multiple providers to create embeddings. At the time of writing this article, the supported providers are Vertex.AI, OpenAI and AWS Bedrock. Please find commands syntax for each one of them below:</p><pre>#Vertex.AI<br>CALL apoc.ml.vertexai.embedding([&#39;Some Text&#39;], $accessToken, $project, {}) yield index, text, embedding;<br><br>#OpenAI<br>CALL apoc.ml.openai.embedding([&#39;Some Text&#39;], $apiKey, {}) yield index, text, embedding;<br><br>#AWS Bedrock<br>CALL apoc.ml.bedrock.embedding(texts, $config) yield index, text, embedding;<br></pre><p>I didn’t have subscriptions for any of these providers, so I decided to host my own local embeddings server with open source embeddings using sentence transformers 😉.</p><p>I used a <a href="https://www.sbert.net/">sentence-transformers</a> model: all-MiniLM-L6-v2. It maps sentences &amp; paragraphs to a 384 dimensional dense vector space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlDXQYdjdeNQje07LLNn4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEhu52uF2zMds7iPNTarBA.png" /></figure><p>Then I defined a custom Neo4j APOC to generate embeddings for a node property using my embeddings server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AYMEn85RD10oMZhXwbdEDw.png" /></figure><p>Here is the full class code</p><pre>package com.mkv.custom;<br><br>import java.io.IOException;<br>import java.net.URI;<br>import java.net.URISyntaxException;<br>import java.net.http.HttpClient;<br>import java.net.http.HttpRequest;<br>import java.net.http.HttpResponse;<br>import java.util.List;<br>import java.util.stream.Stream;<br><br>import org.neo4j.procedure.Description;<br>import org.neo4j.procedure.Name;<br>import org.neo4j.procedure.Procedure;<br><br>import com.fasterxml.jackson.databind.ObjectMapper;<br><br>public class Embeddings {<br><br>    public static class CustomEmbeddingsResult {<br><br>        public final List&lt;Double&gt; embeddings;<br><br>        public CustomEmbeddingsResult() {<br>            this.embeddings = null;<br>        }<br><br>        public CustomEmbeddingsResult(List&lt;Double&gt; embeddings) {<br>            this.embeddings = embeddings;<br>        }<br>    }<br><br>    private static final ObjectMapper objectMapper = new ObjectMapper();<br><br>    @Procedure(name = &quot;com.mkv.custom.embeddings&quot;)<br>    @Description(&quot;com.mkv.custom.embeddings(&#39;s1&#39;) - return vector embeddings for the input text.&quot;)<br>    public Stream&lt;CustomEmbeddingsResult&gt; embeddings(<br>            @Name(&quot;text&quot;) String text) throws URISyntaxException, IOException, InterruptedException {<br>        if (text == null) {<br>            return null;<br>        }<br><br>        String POST_URL = &quot;http://127.0.0.1:8081/generate_embeddings&quot;;<br>        URI postURI = new URI(POST_URL);<br>        HttpRequest httpRequestPost = HttpRequest.newBuilder()<br>                .uri(postURI)<br>                .POST(HttpRequest.BodyPublishers.ofString(text))<br>                .header(&quot;Content-Type&quot;, &quot;text/plain&quot;)<br>                .build();<br>        HttpClient httpClient = HttpClient.newHttpClient();<br><br>        HttpResponse&lt;String&gt; postResponse = httpClient.send(httpRequestPost, HttpResponse.BodyHandlers.ofString());<br>        CustomEmbeddingsResult result = objectMapper.readValue(postResponse.body(), CustomEmbeddingsResult.class);<br>        return Stream.of(new CustomEmbeddingsResult(result.embeddings));<br>    }<br>}</pre><p>And the test case:</p><pre>package com.mkv.custom;<br><br>import org.junit.jupiter.api.AfterAll;<br>import org.junit.jupiter.api.BeforeAll;<br>import org.junit.jupiter.api.Test;<br>import org.junit.jupiter.api.TestInstance;<br>import org.neo4j.driver.Driver;<br>import org.neo4j.driver.GraphDatabase;<br>import org.neo4j.driver.Record;<br>import org.neo4j.driver.Session;<br>import org.neo4j.driver.Value;<br>import org.neo4j.harness.Neo4j;<br>import org.neo4j.harness.Neo4jBuilders;<br><br>import java.util.List;<br><br>import static org.assertj.core.api.Assertions.assertThat;<br><br>@TestInstance(TestInstance.Lifecycle.PER_CLASS)<br>public class EmbeddingsTest {<br><br>    private Neo4j embeddedDatabaseServer;<br><br>    @BeforeAll<br>    void initializeNeo4j() {<br>        this.embeddedDatabaseServer = Neo4jBuilders.newInProcessBuilder()<br>                .withDisabledServer()<br>                .withProcedure(Embeddings.class)<br>                .build();<br>    }<br><br>    @AfterAll<br>    void closeNeo4j() {<br>        this.embeddedDatabaseServer.close();<br>    }<br><br>    @Test<br>    void generateEmbeddings() {<br>        // This is in a try-block, to make sure we close the driver after the test<br>        try(Driver driver = GraphDatabase.driver(embeddedDatabaseServer.boltURI());<br>            Session session = driver.session()) {<br><br>            // When<br>            Record result = session.run(&quot;CALL com.mkv.custom.embeddings(&#39;Hello&#39;) YIELD embeddings RETURN embeddings&quot;).single();<br><br>            // Then<br>            Value actual_embeddings = result.get(&quot;embeddings&quot;);<br><br>            List&lt;Double&gt; expected_embeddings = List.of(-0.0627717524766922, 0.054958831518888474, 0.05216477811336517);<br><br>            assertThat(actual_embeddings.get(0).asDouble()).isEqualTo(expected_embeddings.get(0));<br>            assertThat(actual_embeddings.get(1).asDouble()).isEqualTo(expected_embeddings.get(1));<br>            assertThat(actual_embeddings.get(2).asDouble()).isEqualTo(expected_embeddings.get(2));<br>        }<br>    }<br>}<br></pre><p>Finally the dependencies details for Neo4j.</p><pre>&lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0<br>                      http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&gt;<br>  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;<br><br>  &lt;groupId&gt;com.mkv.custom&lt;/groupId&gt;<br>  &lt;artifactId&gt;embedding-apocs&lt;/artifactId&gt;<br>  &lt;version&gt;1.0.0&lt;/version&gt;<br><br>  &lt;packaging&gt;jar&lt;/packaging&gt;<br>  &lt;name&gt;Custom Neo4j Procs&lt;/name&gt;<br>  &lt;description&gt;Custom Neo4j Procs For Generating Embeddings&lt;/description&gt;<br><br>  &lt;properties&gt;<br>    &lt;java.version&gt;17&lt;/java.version&gt;<br>    &lt;maven.compiler.release&gt;${java.version}&lt;/maven.compiler.release&gt;<br><br>    &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;<br>    &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;<br>    &lt;neo4j.version&gt;5.12.0&lt;/neo4j.version&gt;<br>    &lt;jackson.version&gt;2.13.4&lt;/jackson.version&gt;<br>    &lt;neo4j-java-driver.version&gt;5.12.0&lt;/neo4j-java-driver.version&gt;<br>    &lt;junit-jupiter.version&gt;5.10.0&lt;/junit-jupiter.version&gt;<br>    &lt;maven-shade-plugin.version&gt;3.5.1&lt;/maven-shade-plugin.version&gt;<br>    &lt;maven-compiler-plugin.version&gt;3.11.0&lt;/maven-compiler-plugin.version&gt;<br>    &lt;assertj.version&gt;3.24.2&lt;/assertj.version&gt;<br>    &lt;maven-surefire-plugin.version&gt;3.1.2&lt;/maven-surefire-plugin.version&gt;<br>    &lt;maven.version&gt;3.8.1&lt;/maven.version&gt;<br>    &lt;maven-enforcer-plugin.version&gt;3.4.1&lt;/maven-enforcer-plugin.version&gt;<br>  &lt;/properties&gt;<br><br>  &lt;dependencies&gt;<br>    &lt;dependency&gt;<br>      &lt;!-- This gives us the Procedure API our runtime code uses.<br>           We have a `provided` scope on it, because when this is<br>           deployed in a Neo4j Instance, the API will be provided<br>           by Neo4j. If you add non-Neo4j dependencies to this<br>           project, their scope should normally be `compile` --&gt;<br>      &lt;groupId&gt;org.neo4j&lt;/groupId&gt;<br>      &lt;artifactId&gt;neo4j&lt;/artifactId&gt;<br>      &lt;version&gt;${neo4j.version}&lt;/version&gt;<br>      &lt;scope&gt;provided&lt;/scope&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;dependency&gt;<br>      &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;<br>      &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;<br>      &lt;version&gt;${jackson.version}&lt;/version&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;!-- Test Dependencies --&gt;<br>    &lt;dependency&gt;<br>      &lt;!-- This is used for a utility that lets us start Neo4j with<br>           a specific Procedure, which is nice for writing tests. --&gt;<br>      &lt;groupId&gt;org.neo4j.test&lt;/groupId&gt;<br>      &lt;artifactId&gt;neo4j-harness&lt;/artifactId&gt;<br>      &lt;version&gt;${neo4j.version}&lt;/version&gt;<br>      &lt;scope&gt;test&lt;/scope&gt;<br>      &lt;exclusions&gt;<br>        &lt;exclusion&gt;<br>          &lt;groupId&gt;org.slf4j&lt;/groupId&gt;<br>          &lt;artifactId&gt;slf4j-nop&lt;/artifactId&gt;<br>        &lt;/exclusion&gt;<br>      &lt;/exclusions&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;dependency&gt;<br>      &lt;!-- Used to send cypher statements to our procedure. --&gt;<br>      &lt;groupId&gt;org.neo4j.driver&lt;/groupId&gt;<br>      &lt;artifactId&gt;neo4j-java-driver&lt;/artifactId&gt;<br>      &lt;version&gt;${neo4j-java-driver.version}&lt;/version&gt;<br>      &lt;scope&gt;test&lt;/scope&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;dependency&gt;<br>      &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;<br>      &lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt;<br>      &lt;version&gt;${junit-jupiter.version}&lt;/version&gt;<br>      &lt;scope&gt;test&lt;/scope&gt;<br>    &lt;/dependency&gt;<br><br>    &lt;dependency&gt;<br>      &lt;groupId&gt;org.assertj&lt;/groupId&gt;<br>      &lt;artifactId&gt;assertj-core&lt;/artifactId&gt;<br>      &lt;version&gt;${assertj.version}&lt;/version&gt;<br>      &lt;scope&gt;test&lt;/scope&gt;<br>    &lt;/dependency&gt;<br><br>  &lt;/dependencies&gt;<br><br>  &lt;build&gt;<br>    &lt;plugins&gt;<br>      &lt;plugin&gt;<br>        &lt;artifactId&gt;maven-enforcer-plugin&lt;/artifactId&gt;<br>        &lt;version&gt;${maven-enforcer-plugin.version}&lt;/version&gt;<br>        &lt;executions&gt;<br>          &lt;execution&gt;<br>            &lt;id&gt;enforce&lt;/id&gt;<br>            &lt;goals&gt;<br>              &lt;goal&gt;enforce&lt;/goal&gt;<br>            &lt;/goals&gt;<br>            &lt;phase&gt;validate&lt;/phase&gt;<br>            &lt;configuration&gt;<br>              &lt;rules&gt;<br>                &lt;requireJavaVersion&gt;<br>                  &lt;version&gt;${java.version}&lt;/version&gt;<br>                &lt;/requireJavaVersion&gt;<br>                &lt;requireMavenVersion&gt;<br>                  &lt;version&gt;${maven.version}&lt;/version&gt;<br>                &lt;/requireMavenVersion&gt;<br>              &lt;/rules&gt;<br>            &lt;/configuration&gt;<br>          &lt;/execution&gt;<br>        &lt;/executions&gt;<br>      &lt;/plugin&gt;<br>      &lt;plugin&gt;<br>        &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;<br>        &lt;version&gt;${maven-compiler-plugin.version}&lt;/version&gt;<br>      &lt;/plugin&gt;<br>      &lt;plugin&gt;<br>        &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;<br>        &lt;version&gt;${maven-surefire-plugin.version}&lt;/version&gt;<br>      &lt;/plugin&gt;<br>      &lt;plugin&gt;<br>        &lt;!-- This generates a jar-file with our procedure code,<br>             plus any dependencies marked as `compile` scope.<br>             This should then be deployed in the `plugins` directory<br>             of each Neo4j instance in your deployment.<br>             After a restart, the procedure is available for calling. --&gt;<br>        &lt;artifactId&gt;maven-shade-plugin&lt;/artifactId&gt;<br>        &lt;version&gt;${maven-shade-plugin.version}&lt;/version&gt;<br>        &lt;configuration&gt;<br>          &lt;createDependencyReducedPom&gt;false&lt;/createDependencyReducedPom&gt;<br>        &lt;/configuration&gt;<br>        &lt;executions&gt;<br>          &lt;execution&gt;<br>            &lt;phase&gt;package&lt;/phase&gt;<br>            &lt;goals&gt;<br>              &lt;goal&gt;shade&lt;/goal&gt;<br>            &lt;/goals&gt;<br>          &lt;/execution&gt;<br>        &lt;/executions&gt;<br>      &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>  &lt;/build&gt;<br>&lt;/project&gt;</pre><p>The above procedure will be invoked to generate embeddings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PB2MBvTOtNYhdI_AS6Sezg.png" /><figcaption>Sample Embeddings</figcaption></figure><h4>Time to generate embeddings for Movie nodes</h4><p>Now with setup to create embeddings is in place, its time to define relevant information in Movie nodes which will be translated to embeddings.</p><p>To do this, we condensed information from all the connected Person nodes for a movie node and created a new source field which summarises all information like movie title, release year, plot, actors, directors in a single source field (highlighted in green section below).</p><p>Then we generate embeddings from the text in source field using our custom procedure and store that in embeddings field/property (highlighted in orange section below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*je5aKf4ulSmt4pcVpCOYKQ.png" /></figure><p>With embeddings in place on Movie nodes, we can define our Neo4j vector index (name: <em>movies_extended_info_embeddings</em>) now on the embeddings field.</p><pre>#create vector index<br>CALL db.index.vector.createNodeIndex(&#39;movies_extended_info_embeddings&#39;, &#39;Movie&#39;, &#39;embeddings&#39;, 384, &#39;cosine&#39;)</pre><p>The index would take some time to setup and post setup we can query this index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YonAxTUFdbvGmWR-VzvQlQ.png" /></figure><h3>Setup RAG</h3><p>With neo4j index in place, we will setup our RAG QA pipeline.</p><p>Here we will use langchain to define a vector db handle on our existing index.</p><pre><br>from langchain.vectorstores import Neo4jVector<br>from langchain.embeddings import HuggingFaceEmbeddings</pre><pre>index_name = &quot;movies_extended_info_embeddings&quot;<br>embeddings = HuggingFaceEmbeddings(model_name=&#39;sentence-transformers/all-MiniLM-L6-v2&#39;,<br>                                   model_kwargs={&#39;device&#39;: &#39;cpu&#39;})<br>vectorDb = Neo4jVector.from_existing_graph(<br>        embedding=embeddings,<br>        url=&#39;bolt://localhost:7687&#39;,<br>        username=&#39;neo4jadmin&#39;,<br>        password=&#39;XXXXXX&#39;,<br>        index_name=index_name,<br>        node_label=&quot;Movie&quot;,<br>        text_node_properties=[&quot;title&quot;, &quot;tagline&quot;],<br>        embedding_node_property=&quot;embeddings&quot;,<br>        search_type=&quot;vector&quot;<br>    )</pre><p>Testing with a similarity search with score:</p><pre>query = &quot;Who played in the Matrix?&quot;<br>retriever = vectorDb.as_retriever()<br>retriever.get_relevant_documents(query)[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VGVWP2VUJUaIfwkf5Fx0Dw.png" /></figure><h4>Setting up the RetrievalQA chain</h4><pre>import os<br>from langchain.llms import HuggingFaceHub<br><br>os.environ[&quot;HUGGINGFACEHUB_API_TOKEN&quot;] = &quot;XXXXXXXXXXXXXXXXXX&quot;<br><br>repo_id = &quot;HuggingFaceH4/zephyr-7b-beta&quot;<br>llm = HuggingFaceHub(<br>    repo_id=repo_id, model_kwargs={&quot;temperature&quot;: 0.5, &quot;max_new_tokens&quot;:512}<br>)</pre><pre>chain = RetrievalQA.from_chain_type(<br>    llm=llm, chain_type=&quot;stuff&quot;, retriever=retriever<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1bqfpRyL40cpLus8ClZ3g.png" /></figure><h3>Summary</h3><p>We see that Zephyr-7B even though being significantly smaller in size than popular LLM models like gpt-3.5-turbo and llama-70B and is equally performant in summarisation tasks, understanding the context and instructions following.</p><p>With Neo4j support for vector index has tremendous potential to exploit relationships in a natural language query format.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f34f99a9747" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>