<?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 AILearning on Medium]]></title>
        <description><![CDATA[Stories by AILearning on Medium]]></description>
        <link>https://medium.com/@AILearning?source=rss-60a408e3c0aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ifWx_xc1e2KUvsJ0rbPH1Q.jpeg</url>
            <title>Stories by AILearning on Medium</title>
            <link>https://medium.com/@AILearning?source=rss-60a408e3c0aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:28:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AILearning/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[Zero → Hero: A Self-Improving Prompt for Your LLM]]></title>
            <link>https://medium.com/@AILearning/zero-hero-a-self-improving-prompt-for-your-llm-0399be6989a2?source=rss-60a408e3c0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/0399be6989a2</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[AILearning]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 06:18:09 GMT</pubDate>
            <atom:updated>2025-10-10T22:11:42.092Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><a href="https://adalflow.sylph.ai/use_cases/classification.html">AdalFlow Prompt Tuning</a> × Self-Supervised (OvO) Prompt Optimization — Dual-Engine Recipe (with drop-in code &amp; runnable skeleton)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VYf-54vn06RrBYGB" /><figcaption>Source: Image by the author.</figcaption></figure><h3><strong><em>TL;DR</em></strong></h3><ul><li><strong>I<em>f you have labeled data</em></strong><em>: use </em><strong><em>AdalFlow</em></strong><em>’s </em><strong><em>LLM-AutoDiff</em></strong><em> to automatically tune your PROMPT and DEMOS for higher accuracy/F1 with full observability.</em></li><li><strong><em>If you lack labels</em></strong><em>: use </em><strong><em>Output-vs-Output (OvO)</em></strong><em> </em><strong><em>self-supervised prompt battles</em></strong><em>. A separate </em><strong><em>judge</em></strong><em> model picks winners — no ground truth required — so your prompt gets stronger over rounds.</em></li><li><strong><em>Best of both</em></strong><em>: </em><strong><em>pretrain</em></strong><em> a good base prompt with OvO on unlabeled data, then </em><strong><em>fine-tune</em></strong><em> that prompt (plus auto-bootstrapped few-shot demos) with AdalFlow on a small labeled set for faster convergence and lower cost.</em></li></ul><h3>Who is this for?</h3><ul><li>ML/LLM engineers who want <strong>practical, cheap</strong> accuracy gains without a huge labeling campaign.</li><li>Product teams that need <strong>observable</strong> tuning and <strong>versioned</strong> artifacts (prompts/demos/metrics).</li><li>Researchers evaluating <strong>self-play</strong> style prompt optimization.</li></ul><h3>Post road map</h3><ol><li><a href="#why-combine-these-two"><em>Why combine these two?</em></a></li><li><a href="#two-optimization-paths-who-does-what"><em>Two optimization paths (who does what)</em></a></li><li><a href="#a-unified-classification-pipeline"><em>A unified classification pipeline</em></a></li><li><a href="#hands-on-copy-paste-friendly"><em>Hands-on (copy-paste friendly)</em></a></li><li><a href="#step-2-in-depth-self-by-self--ovo-battle-loop"><em>Step 2 in depth: Self-by-Self + OvO battle loop</em></a></li><li><a href="#step-34-in-depth-adalflow-integration-parameterized-promptdemos--training"><em>Step 3–4 in depth: AdalFlow integration (parameterized PROMPT/DEMOS + training)</em></a></li><li><a href="#production--monitoring-tips"><em>Production &amp; monitoring tips</em></a></li><li><a href="#faq-which-path-to-prioritize-when"><em>FAQ: which path to prioritize when?</em></a></li></ol><h3>Why combine these two?</h3><p>In real life you usually have <strong>a little labeled data</strong> and <strong>a lot of unlabeled data</strong>.</p><blockquote><strong>Only supervised</strong> → slow cold start, costly labeling.</blockquote><blockquote><strong>Only self-supervised</strong> → weaker guarantees, harder to validate for prod.</blockquote><p><strong>The hybrid plan</strong>:</p><blockquote>1. run <strong>OvO self-supervision</strong> first to <strong>forge a stronger base prompt</strong> (no labels needed),</blockquote><blockquote>2. feed that base prompt as a <strong>PROMPT initialization</strong> to <strong>AdalFlow</strong> and add a few <strong>few-shot DEMOS</strong> (auto-bootstrapped from high-confidence OvO outputs) to do <strong>LLM-AutoDiff</strong> on a <strong>small labeled set</strong>.</blockquote><blockquote>You get <strong>faster convergence, better metrics, and lower token spend</strong>.</blockquote><h3>Two optimization paths (who does what)</h3><h4>Path A — AdalFlow (supervised, with labels)</h4><ul><li><strong>Goal:</strong> Auto-optimize <em>PROMPT</em> and <em>DEMOS</em> against validation metrics (accuracy, F1).</li><li><strong>Mechanics:</strong> Treat prompts/demos as <strong>parameters</strong>; define metrics; run <strong>LLM-AutoDiff</strong>; get observability and reproducibility.</li><li><strong>Use when:</strong> You have at least a small labeled set and you want <strong>stable, auditable</strong> improvements.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDhI12S-Bq9Ecpzfago3KQ.png" /><figcaption>Representing an LLM application as an auto-differentiable computation graph, Source: Ref[5]</figcaption></figure><h4>Path B — OvO self-supervision (no/weak labels)</h4><ul><li><strong>Goal:</strong> Make progress <strong>without ground truth</strong>; a <strong>judge</strong> model chooses winner between two outputs (A vs B).</li><li><strong>Mechanics:</strong> Candidate prompts fight on small batches; judge picks winners; we mutate the winner to produce the next generation; early-stop, debias, and cap costs.</li><li><strong>Use when:</strong> <strong>Cold start</strong> on mostly unlabeled data, to get a solid <strong>P₀</strong> (base prompt) before supervised tuning.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*nAaoC1mtbBgFFkGaoIKe1A.png" /><figcaption>Self-Supervised Prompt Optimization, Source: Ref[4]</figcaption></figure><p><strong><em>Signal summary:</em></strong><em> AdalFlow optimizes with </em><strong><em>metric alignment</em></strong><em> (needs labels). OvO optimizes with </em><strong><em>preference alignment</em></strong><em> (no labels). </em><strong><em>Chaining both</em></strong><em> is robust and economical.</em></p><h3>A unified classification pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HqIIYWhdBMBaE3h-" /><figcaption>Overall Workflow, Source: Image by the author.</figcaption></figure><h3>Hands-on (copy-paste friendly)</h3><h4>Step 1 — Task spec &amp; structured outputs (non-negotiable)</h4><ul><li>Pick your model(s).</li><li>Define <strong>input fields</strong> and your <strong>label set</strong>, e.g., {&quot;label&quot;: &quot;...&quot;, &quot;score&quot;: ...}.</li><li>Split system prompt into <strong>Task Definition / Output Format / Guardrails</strong> for controllability and future tuning.</li></ul><h4>Step 2 in depth: Self-by-Self + OvO battle loop</h4><p>Below is a <strong>drop-in skeleton</strong>. Replace run_model(...) and judge_outputs(...) with your actual LLM calls. The mock is there so you can run end-to-end immediately.</p><p>2.1 Prompt candidate proposer</p><pre>from typing import List<br>BASE_TEMPLATES = [<br>    &quot;You are a precise classifier. Output JSON with fields {label, score}. Task: {task}&quot;,<br>    &quot;Classify strictly into target labels. Respond as JSON {{\&quot;label\&quot;: ..., \&quot;score\&quot;: ...}}. Task: {task}&quot;,<br>    &quot;Follow format: {{\&quot;label\&quot;: \&quot;positive|negative|unknown\&quot;, \&quot;score\&quot;: 0~1}}. Task: {task}&quot;,<br>    &quot;Return only JSON. No extra text. Task: {task}&quot;,<br>    &quot;Be conservative; choose &#39;unknown&#39; if low confidence. Task: {task}&quot;,<br>]<br>def propose_prompts(task_desc: str, k: int = 5) -&gt; List[str]:<br>    import random<br>    random.shuffle(BASE_TEMPLATES)<br>    return [t.format(task=task_desc) for t in BASE_TEMPLATES[:k]]</pre><p>2.2 Execution &amp; judge templates</p><pre>EXEC_TEMPLATE = &quot;&quot;&quot;&lt;SYS&gt;<br>You are a strict text classifier. Only output JSON: {{&quot;label&quot;: &quot;...&quot;, &quot;score&quot;: 0~1}}.<br>Valid labels: {labels}. If unclear, use &quot;unknown&quot;. No extra text.<br>&lt;/SYS&gt;<br>User text:<br>{input}<br>&quot;&quot;&quot;<br>JUDGE_TEMPLATE = &quot;&quot;&quot;&lt;SYS&gt;<br>You are a judge. Two model outputs (A/B) are given for the same input.<br>Pick the better one ONLY by JSON: {{&quot;winner&quot;: &quot;A&quot;|&quot;B&quot;}}. Criteria:<br>1) Correct label (if deducible), 2) Format validity, 3) Cautious use of &#39;unknown&#39;.<br>No explanation, no extra fields.<br>&lt;/SYS&gt;<br>Input: {input}<br>Output A: {out_a}<br>Output B: {out_b}<br>&quot;&quot;&quot;</pre><p>2.3 Single duel + naive scoring</p><pre>import json<br>from typing import Tuple, Dict<br>def run_model(prompt: str, x: str, labels: str) -&gt; Dict:<br>    # Replace with your actual LLM call using `prompt`<br>    # --- MOCK so the script runs end-to-end ---<br>    def mock(x):<br>        xl = x.lower()<br>        if any(k in xl for k in [&quot;good&quot;, &quot;love&quot;, &quot;great&quot;, &quot;awesome&quot;]):<br>            return {&quot;label&quot;: &quot;positive&quot;, &quot;score&quot;: 0.9}<br>        if any(k in xl for k in [&quot;bad&quot;, &quot;awful&quot;, &quot;terrible&quot;, &quot;hate&quot;]):<br>            return {&quot;label&quot;: &quot;negative&quot;, &quot;score&quot;: 0.9}<br>        return {&quot;label&quot;: &quot;unknown&quot;, &quot;score&quot;: 0.55}<br>    return mock(x)<br>def judge_outputs(x: str, out_a: Dict, out_b: Dict) -&gt; str:<br>    # Replace with a real judge LLM call using JUDGE_TEMPLATE if desired<br>    def valid(y): return isinstance(y, dict) and &quot;label&quot; in y and &quot;score&quot; in y<br>    if valid(out_a) and not valid(out_b): return &quot;A&quot;<br>    if valid(out_b) and not valid(out_a): return &quot;B&quot;<br>    return &quot;A&quot; if out_a.get(&quot;score&quot;, 0) &gt;= out_b.get(&quot;score&quot;, 0) else &quot;B&quot;</pre><p>2.4 OvO multi-round evolution (early-stop, mutation, cost control)</p><pre>from typing import Sequence<br>import random<br><br>def mutate(p: str) -&gt; str:<br>    tweaks = [<br>        &quot; Be conservative.&quot;,<br>        &quot; Only output JSON.&quot;,<br>        &quot; Prefer &#39;unknown&#39; on ambiguity.&quot;,<br>        &quot; Ensure reproducibility with stable format.&quot;,<br>        &quot; Use robust label reasoning.&quot;,<br>    ]<br>    return p + random.choice(tweaks)<br><br>def ovo_optimize(<br>    unlabeled_samples: Sequence[str],<br>    task_desc: str,<br>    labels: Sequence[str],<br>    rounds: int = 8,<br>    k: int = 4,<br>    n_per_round: int = 4,<br>    patience: int = 2,<br>    seed: int = 7,<br>):<br>    random.seed(seed)<br>    label_str = &quot;|&quot;.join(labels)<br>    pool = propose_prompts(task_desc, k=k)<br>    best_prompt, best_win = None, -1<br>    stall = 0<br>    for r in range(1, rounds + 1):<br>        wins = [0] * len(pool)<br>        batch = random.sample(list(unlabeled_samples), min(n_per_round, len(unlabeled_samples)))<br>        for x in batch:<br>            i, j = random.sample(range(len(pool)), 2)<br>            p_i, p_j = pool[i], pool[j]<br>            out_i = run_model(EXEC_TEMPLATE.format(input=x, labels=label_str), x, label_str)<br>            out_j = run_model(EXEC_TEMPLATE.format(input=x, labels=label_str), x, label_str)<br>            w = judge_outputs(x, out_i, out_j)  # &quot;A&quot;|&quot;B&quot;<br>            if w == &quot;A&quot;: wins[i] += 1<br>            else: wins[j] += 1<br>        idx = max(range(len(pool)), key=lambda t: wins[t])<br>        gen_best, gen_win = pool[idx], wins[idx]<br>        if gen_win &gt; best_win:<br>            best_prompt, best_win = gen_best, gen_win<br>            stall = 0<br>        else:<br>            stall += 1<br>        if stall &gt;= patience:<br>            break<br>        pool = [gen_best] + [mutate(gen_best) for _ in range(k - 1)]<br>    return best_prompt<br><br>def bootstrap_demos_from_ovo(unlabeled_samples, best_prompt, topk=6):<br>    demos = []<br>    for x in unlabeled_samples[: topk * 3]:<br>        y = run_model(EXEC_TEMPLATE.format(input=x, labels=&quot;positive|negative|unknown&quot;),<br>                      x, &quot;positive|negative|unknown&quot;)<br>        if y.get(&quot;score&quot;, 0) &gt;= 0.8 and y.get(&quot;label&quot;) in {&quot;positive&quot;, &quot;negative&quot;}:<br>            demos.append({&quot;input&quot;: x, &quot;output&quot;: y})<br>        if len(demos) &gt;= topk:<br>            break<br>    return demos</pre><h4>Step 3 in depth: AdalFlow integration (parameterized PROMPT/DEMOS + training)</h4><p>We will use the following overall template with system_prompt, output_format_str, and few_shot_demos varaibles. task_desc_template will be used to render the final classification task description from class names and each label’s description. TRECExtendedData is a dataclass that extends <a href="https://adalflow.sylph.ai/apis/datasets/datasets.types.html#datasets.types.TrecData">TrecData</a> with a rationale field. This will ensure our generator to first levarage ‘Chain-of-Thought’ reasoning before predicting the final class_name.</p><pre>template = r&quot;&quot;&quot;&lt;START_OF_SYSTEM_MESSAGE&gt;<br> {{system_prompt}}<br> {% if output_format_str is not none %}<br> {{output_format_str}}<br> {% endif %}<br> {% if few_shot_demos is not none %}<br> Here are some examples:<br> {{few_shot_demos}}<br> {% endif %}<br> &lt;END_OF_SYSTEM_MESSAGE&gt;<br> &lt;START_OF_USER_MESSAGE&gt;<br> {{input_str}}<br> &lt;END_OF_USER_MESSAGE&gt;<br> &quot;&quot;&quot;<br>task_desc_template = r&quot;&quot;&quot;You are a classifier. Given a question, you need to classify it into one of the following classes:<br> Format: class_index. class_name, class_description<br> {% if classes %}<br> {% for class in classes %}<br> {{loop.index-1}}. {{class.label}}, {{class.desc}}<br> {% endfor %}<br> {% endif %}<br> - Do not try to answer the question:<br> &quot;&quot;&quot;<br> @dataclass<br> class TRECExtendedData(TrecData):<br>     rationale: str = field(<br>         metadata={<br>             &quot;desc&quot;: &quot;Your step-by-step reasoning to classify the question to class_name&quot;<br>         },<br>         default=None,<br>     )<br>     __input_fields__ = [&quot;question&quot;]<br>     __output_fields__ = [&quot;rationale&quot;, &quot;class_name&quot;] # it is important to have the rationale before the class_name</pre><p>We will subclass from Component for our final task pipeline. We use <a href="https://adalflow.sylph.ai/apis/components/components.output_parsers.dataclass_parser.html#components.output_parsers.dataclass_parser.DataClassParser">DataClassParser</a> to streamline the process of output formatting and parsing.</p><pre>class TRECClassifierStructuredOutput(adal.Component):<br>  def __init__(self, model_client: adal.ModelClient, model_kwargs: Dict):<br>         super().__init__()<br>         label_desc = [<br>             {&quot;label&quot;: label, &quot;desc&quot;: desc}<br>             for label, desc in zip(_COARSE_LABELS, _COARSE_LABELS_DESC)<br>         ]<br>         task_desc_str = adal.Prompt(<br>             template=task_desc_template, prompt_kwargs={&quot;classes&quot;: label_desc}<br>         )()<br>         self.data_class = TRECExtendedData<br>         self.data_class.set_task_desc(task_desc_str)<br>         self.parser = adal.DataClassParser(<br>             data_class=self.data_class, return_data_class=True, format_type=&quot;yaml&quot;<br>         )<br>         prompt_kwargs = {<br>             &quot;system_prompt&quot;: adal.Parameter(<br>                 data=self.parser.get_task_desc_str(),<br>                 role_desc=&quot;Task description&quot;,<br>                 requires_opt=True,<br>                 param_type=adal.ParameterType.PROMPT,<br>             ),<br>             &quot;output_format_str&quot;: adal.Parameter(<br>                 data=self.parser.get_output_format_str(),<br>                 role_desc=&quot;Output format requirements&quot;,<br>                 requires_opt=False,<br>                 param_type=adal.ParameterType.PROMPT,<br>             ),<br>             &quot;few_shot_demos&quot;: adal.Parameter(<br>                 data=None,<br>                 requires_opt=True,<br>                 role_desc=&quot;Few shot examples to help the model&quot;,<br>                 param_type=adal.ParameterType.DEMOS,<br>             ),<br>         }<br>         self.llm = adal.Generator(<br>             model_client=model_client,<br>             model_kwargs=model_kwargs,<br>             prompt_kwargs=prompt_kwargs,<br>             template=template,<br>             output_processors=self.parser,<br>             use_cache=True,<br>         )<br>     def _prepare_input(self, question: str):<br>         input_data = self.data_class(question=question)<br>         input_str = self.parser.get_input_str(input_data)<br>         prompt_kwargs = {<br>             &quot;input_str&quot;: adal.Parameter(<br>                 data=input_str, requires_opt=False, role_desc=&quot;input to the LLM&quot;<br>             )<br>         }<br>         return prompt_kwargs<br>     def call(<br>         self, question: str, id: Optional[str] = None<br>     ) -&gt; Union[adal.GeneratorOutput, adal.Parameter]:<br>         prompt_kwargs = self._prepare_input(question)<br>         output = self.llm(prompt_kwargs=prompt_kwargs, id=id)<br>         return output</pre><p>In this taske pipeline, we have prepared two trainable prameters: system_prompt and few_shot_demos and each is of type adal.ParameterType.PROMPT and adal.ParameterType.DEMOS respectively. We will need <a href="https://adalflow.sylph.ai/apis/optim/optim.text_grad.tgd_optimizer.html#optim.text_grad.tgd_optimizer.TGDOptimizer">TGDOptimizer</a> to optimize system_prompt and <a href="https://adalflow.sylph.ai/apis/optim/optim.few_shot.bootstrap_optimizer.html#optim.few_shot.bootstrap_optimizer.BootstrapFewShot">BootstrapOptimizer</a> to optimize few_shot_demos.</p><p>Now, we will define a subclass of AdalComponent to prepare the pipeline for training. We have set up the eval_fn, loss_fn, along with methods to configure backward engine for the text optimizer, as well as a method method to configure teacher generator for the demo optimizer.</p><pre>class TrecClassifierAdal(adal.AdalComponent):<br>    def __init__(<br>        self,<br>        model_client: adal.ModelClient,<br>        model_kwargs: Dict,<br>        teacher_model_config: Dict,<br>        backward_engine_model_config: Dict,<br>        text_optimizer_model_config: Dict,<br>    ):<br>        task = TRECClassifierStructuredOutput(model_client, model_kwargs)<br>        eval_fn = AnswerMatchAcc(type=&quot;exact_match&quot;).compute_single_item<br>        loss_fn = adal.EvalFnToTextLoss(<br>            eval_fn=eval_fn,<br>            eval_fn_desc=&quot;exact_match: 1 if str(y) == str(y_gt) else 0&quot;,<br>        )<br>        super().__init__(<br>            task=task,<br>            eval_fn=eval_fn,<br>            loss_fn=loss_fn,<br>            backward_engine_model_config=backward_engine_model_config,<br>            text_optimizer_model_config=text_optimizer_model_config,<br>            teacher_model_config=teacher_model_config,<br>        )<br>  def prepare_task(self, sample: TRECExtendedData):<br>        return self.task.call, {&quot;question&quot;: sample.question, &quot;id&quot;: sample.id}<br>    def prepare_eval(<br>        self, sample: TRECExtendedData, y_pred: adal.GeneratorOutput<br>    ) -&gt; float:<br>        y_label = -1<br>        if y_pred and y_pred.data is not None and y_pred.data.class_name is not None:<br>            y_label = y_pred.data.class_name<br>        return self.eval_fn, {&quot;y&quot;: y_label, &quot;y_gt&quot;: sample.class_name}<br>    def prepare_loss(<br>        self, sample: TRECExtendedData, y_pred: adal.Parameter, *args, **kwargs<br>    ) -&gt; Tuple[Callable[..., Any], Dict]:<br>        full_response = y_pred.full_response<br>        y_label = -1<br>        if (<br>            full_response<br>            and full_response.data is not None<br>            and full_response.data.class_name is not None<br>        ):<br>            y_label = full_response.data.class_name<br>        y_pred.eval_input = y_label<br>        y_gt = adal.Parameter(<br>            name=&quot;y_gt&quot;,<br>            data=sample.class_name,<br>            eval_input=sample.class_name,<br>            requires_opt=False,<br>        )<br>        return self.loss_fn, {&quot;kwargs&quot;: {&quot;y&quot;: y_pred, &quot;y_gt&quot;: y_gt}}</pre><p>The following code shows our default training configuration. We use a batch size of 4, 12 steps, and 4 workers to call LLMs in parallel. The optimize_order is set to sequential to first train the text optimizer and then the demo optimizer. This training strategy has been working well. With the text optimized, this might boost the performance for the teacher model. With the teacher model’s reasoning, the demo optimizer can learn to reason better even with merefly one demonstration from the teacher. When we are at the sequential optimization order, we will end up with 24 steps trained.</p><p>In addition, you can try mixed for the optimization order, where at each step, it will update both the text optimizer and the demo optimizer.</p><pre>def train(<br>    model_client: adal.ModelClient,<br>    model_kwargs: Dict,<br>    train_batch_size=4,  # larger batch size is not that effective, probably because of llm&#39;s lost in the middle<br>    raw_shots: int = 0,<br>    bootstrap_shots: int = 1,<br>    max_steps=12,<br>    num_workers=4,<br>    strategy=&quot;constrained&quot;,<br>    optimization_order=&quot;sequential&quot;,<br>    debug=False,<br>):<br>    adal_component = TrecClassifierAdal(<br>        model_client=model_client,<br>        model_kwargs=model_kwargs,<br>        text_optimizer_model_config=gpt_4o_model,<br>        backward_engine_model_config=gpt_4o_model,<br>        teacher_model_config=gpt_4o_model,<br>    )<br>    print(adal_component)<br>    trainer = adal.Trainer(<br>        train_batch_size=train_batch_size,<br>        adaltask=adal_component,<br>        strategy=strategy,<br>        max_steps=max_steps,<br>        num_workers=num_workers,<br>        raw_shots=raw_shots,<br>        bootstrap_shots=bootstrap_shots,<br>        debug=debug,<br>        weighted_sampling=True,<br>        optimization_order=optimization_order,<br>        exclude_input_fields_from_bootstrap_demos=True,<br>    )<br>    print(trainer)<br><br>    train_dataset, val_dataset, test_dataset = load_datasets()<br>    trainer.fit(<br>        train_dataset=train_dataset,<br>        val_dataset=test_dataset,<br>        debug=debug,<br>    )</pre><p>In this case, we did not use val_dataset as we did diagnose and as shown in Table 1, the val dataset is not a good indicator for the test accuracy. Thus, our final training strategy is to directly validate on the test dataset.</p><p><strong>Training checkpoints</strong>:</p><p>At the end of the training, we will print out the ckpt path where you can look up all the details about the trained prompt. Here is our above training:</p><pre>Loading Data: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 144/144 [00:00&lt;00:00, 51011.81it/s]<br>Evaluating step(24): 0.8426 across 108 samples, Max potential: 0.8819:  75%|█████████████████████████████████████████████████████████████████████▊                       | 108/144 [00:00&lt;00:00, 1855.48it/s]<br>Fail validation: 0.8348623853211009 &lt;= 0.8819444444444444, revert<br>Training Step: 24: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 12/12 [03:05&lt;00:00, 15.46s/it]<br>Saved ckpt to /Users/liyin/.adalflow/ckpt/TrecClassifierAdal/constrained_max_steps_12_848d2_run_7.json<br>Training time: 823.8977522850037s</pre><p>We can see that the training takes only 14 minutes. We use 12 steps, and the learning curve is shown in Fig 1. Here is our trained system prompt and the demo prompt:</p><pre>system_prompt = &quot;You are a classifier. Given a question, you need to classify it into one of the following classes:\nFormat: class_index. class_name, class_description\n0. ABBR, Abbreviation or acronym\n1. ENTY, Entity, including specific terms, brand names, or other distinct entities\n2. DESC, Description and abstract concept, including explanations, characteristics, and meanings\n3. HUM, Human being\n4. LOC, Location, including spatial information, geographical places\n5. NUM, Numeric value, including measurable figures, quantities, distances, and time\n- Focus on correctly identifying the class based on the question&#39;s main inquiry:&quot;<br>few_shot_demos = &quot;rationale: The question is asking for a specific term used to describe the sum of\n  all genetic material in an organism.\nclass_name: ENTY&quot;</pre><p>We can see that compared with our initial prompt, it adds some concise explanation to each class. The demo prompt is also short, directly from a teacher model teaching the student model to do rationale to reach to the final class_name.</p><p>Evaluate before shipping</p><pre>def eval_on_valid(final_prompt, final_demos, valid_labeled):<br>    tp = 0<br>    for x, y in valid_labeled:<br>        out = run_model(EXEC_TEMPLATE.format(input=x, labels=&quot;positive|negative|unknown&quot;),<br>                        x, &quot;positive|negative|unknown&quot;)<br>        tp += int(out.get(&quot;label&quot;) == y)<br>    return {&quot;accuracy&quot;: tp / max(1, len(valid_labeled))}<br>metrics = eval_on_valid(final_prompt, final_demos, valid_labeled)<br>print(&quot;Final metrics:&quot;, metrics)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*3oDvs6nRndt9DDZO.png" /><figcaption>Learning Curve on training system task instruction and on one-shot demonstration, Source : [1]</figcaption></figure><blockquote><strong><em>Key takeaways:</em></strong></blockquote><ul><li>Treat <strong>PROMPT</strong> and <strong>DEMOS</strong> as <strong>trainable parameters</strong>. AdalFlow will refactor them towards your supervised metric.</li><li>Seeding AdalFlow with <strong>OvO’s P₀★ and few-shot demos</strong> typically <strong>cuts iterations</strong> and <strong>saves tokens</strong>.</li><li><strong>Version everything</strong>: dataset snapshot, seeds, metrics, final prompt/demos, and model versions for reproducibility.</li></ul><h3>Production &amp; monitoring tips</h3><p><strong><em>Data &amp; labeling</em></strong></p><ul><li>Start with <strong>OvO</strong> when labels are scarce; allocate <strong>5–10%</strong> of budget to later label a <strong>small</strong> calibration/validation set for AdalFlow.</li><li>Use <strong>stratified sampling</strong> for that small labeled split to stabilize metrics.</li></ul><p><strong><em>Judging</em></strong></p><ul><li>Keep a <strong>separate judge model</strong> (smaller is often fine).</li><li>Add judge <strong>format checks</strong> (valid JSON, valid label, sensible score range).</li><li>Occasionally <strong>audit</strong> judge decisions with a human review sample to catch bias.</li></ul><p><strong><em>Mutation &amp; early stop</em></strong></p><ul><li>Mutate <strong>one dimension at a time</strong> (format strictness, conservativeness, tie-breaking).</li><li>Stop after <strong>patience</strong> rounds without win-rate gains; log <strong>win curves</strong>.</li></ul><p><strong><em>Cost control</em></strong></p><ul><li>Use <strong>small batches</strong> (n_per_round) for OvO; gradually increase if variance is high.</li><li>Cache model outputs; dedupe prompts.</li><li>During AdalFlow, <strong>warm-start</strong> with P₀★ and limit <strong>max_iters</strong>.</li></ul><p><strong><em>Observability</em></strong></p><ul><li>Version prompts/demos, seeds, data snapshots, model names.</li><li>Log: <strong>win rates per generation</strong>, <strong>judge rationales</strong> (if allowed), <strong>metric curves</strong>, <strong>token/$$</strong>.</li></ul><h3>FAQ: which path to prioritize when?</h3><ul><li><strong>Only unlabeled data?</strong> Start with <strong>OvO</strong> to get a competent <strong>P₀★</strong>; later label a <strong>tiny</strong> set and finish with AdalFlow.</li><li><strong>Some labels available?</strong> Seed with OvO briefly (1–3 rounds) for a better init, then switch to <strong>AdalFlow</strong>.</li><li><strong>Tight budget?</strong> Favor <strong>OvO</strong> (cheap exploration), then <strong>short</strong> AdalFlow runs for calibrated improvements.</li><li><strong>Strict SLA / compliance?</strong> Heavier <strong>AdalFlow</strong> (supervised, reproducible, observable) and a conservative execution prompt.</li></ul><h3>Appendix: Plugging in a real LLM</h3><p>Replace the mocks with your stack (OpenAI/Anthropic/Gemini/vLLM, etc.):</p><pre>def run_model(prompt: str, x: str, labels: str) -&gt; Dict:<br>    # Example pseudocode<br>    # resp = client.chat.completions.create(<br>    #     model=&quot;...&quot;,<br>    #     messages=[{&quot;role&quot;:&quot;system&quot;,&quot;content&quot;:prompt}],<br>    #     temperature=0<br>    # )<br>    # content = resp.choices[0].message.content<br>    # return json.loads(content)  # must be {&quot;label&quot;: &quot;...&quot;, &quot;score&quot;: ...}<br>    raise NotImplementedError<br><br>def judge_outputs(x: str, out_a: Dict, out_b: Dict) -&gt; str:<br>    # Example pseudocode<br>    # judge_msg = JUDGE_TEMPLATE.format(input=x, out_a=json.dumps(out_a), out_b=json.dumps(out_b))<br>    # resp = judge_client.chat.completions.create(...)<br>    # winner = json.loads(resp.choices[0].message.content)[&quot;winner&quot;]<br>    # return winner<br>    raise NotImplementedError</pre><p><strong>Pro tips</strong></p><ul><li>Set <strong>temperature=0</strong> for both executor and judge.</li><li>Strictly <strong>validate JSON</strong>; auto-repair with a tiny rule if necessary.</li><li>For multi-class tasks, start with an <strong>“unknown”</strong> fallback label to avoid over-confident errors.</li></ul><h3>Conclusion</h3><p>This dual-engine recipe lets you <strong>pretrain</strong> a strong base prompt with <strong>OvO self-supervision</strong> (no labels, low cost) and then <strong>finish</strong> with <strong>AdalFlow’s LLM-AutoDiff</strong> on a <strong>small labeled set</strong> to lock in stable, observable gains. Treat <strong>PROMPT</strong> and <strong>DEMOS</strong> as first-class, trainable parameters; initialize them from OvO; and version everything. In practice, this combo reduces iterations, controls token spend, and yields a <strong>self-improving classifier</strong> you can confidently ship.</p><p>Thanks for trying us out, we’re here to provide you with the best LLM application development experience you can dream of 😊 any questions or concerns you may have, <a href="https://www.google.com/url?q=https%3A%2F%2Fdiscord.gg%2FezzszrRZvT">come talk to us on discord,</a> we’re always here to help! ⭐ <em>Star us on </em><a href="https://github.com/SylphAI-Inc/AdalFlow"><em>Github</em></a><em> </em>⭐</p><h3>Quick Links</h3><p>[1] <strong>SylphAI Inc.</strong>, “AdalFlow (GitHub repository),” <em>GitHub</em>, [Online]. Available: <a href="https://github.com/SylphAI-Inc/AdalFlow">https://github.com/SylphAI-Inc/AdalFlow</a>. Accessed: Sep. 23, 2025.</p><p>[2] <strong>SylphAI Inc.</strong>, “AdalFlow Tutorials,” <em>SylphAI Documentation</em>, [Online]. Available: <a href="https://adalflow.sylph.ai/index.html">https://adalflow.sylph.ai/index.html</a>. Accessed: Sep. 23, 2025.</p><p>[3] <strong>SylphAI Inc.</strong>, “AdalFlow Developer Notes,” <em>SylphAI Documentation</em>, [Online]. Available: <strong>[insert developer notes URL]</strong>. Accessed: Sep. 23, 2025.</p><p>[4] <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Xiang,+J">Jinyu Xiang</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Zhang,+J">Jiayi Zhang</a>, <a href="https://arxiv.org/search/cs?searchtype=author&amp;query=Yu,+Z">Zhaoyang Yu</a>,…, “Self-Supervised Prompt Optimization,” 2025</p><p>[5] Li Yin1, Zhangyang “Atlas” Wang, “LLM-AutoDiff: Auto-Differentiate Any LLM Workflow,” [2025<strong>]</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0399be6989a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Hallucinations to Honesty: Teaching LLMs When (Not) to Call Tools]]></title>
            <link>https://medium.com/@AILearning/from-hallucinations-to-honesty-teaching-llms-when-not-to-call-tools-242df41c9513?source=rss-60a408e3c0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/242df41c9513</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[AILearning]]></dc:creator>
            <pubDate>Tue, 23 Sep 2025 02:56:01 GMT</pubDate>
            <atom:updated>2025-09-23T02:56:01.753Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8Dq4da8JhItFF1iky_E2g.png" /></figure><p>Large Language Models are no longer just text generators , they are becoming <strong>tool-augmented agents</strong>. They can fetch real-time data, query APIs, run code, or even control external systems.</p><p>But there’s a subtle challenge:</p><p>👉 <em>When should a model call a tool, and when should it not?</em></p><p>This is the focus of the new benchmark <strong>When2Call</strong>, which evaluates not just whether a model can call tools correctly, but also whether it can decide <em>if it should call them in the first place</em>.</p><h3>Why “When to Call” Matters</h3><p>Most benchmarks today assume tools are always available and useful. But in real-world scenarios:</p><ul><li><em>Sometimes parameters are </em><strong><em>missing</em></strong><em> → the model should </em><strong><em>ask a follow-up question</em></strong><em>.</em></li><li><em>Sometimes tools don’t exist → the model should </em><strong><em>refuse politely</em></strong><em>.</em></li><li><em>Sometimes the answer is already obvious → no tool call needed.</em></li><li><em>Sometimes the model hallucinates tools or parameters → leading to </em><strong><em>misleading outputs</em></strong><em>.</em></li></ul><p>Bad tool-calling decisions lead to wasted computation, higher costs, or worse — <strong>hallucinated answers that users may trust.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*lQxWaWX2BTtLZeJJRKI1aw.png" /></figure><h3>What is When2Call?</h3><p>When2Call introduces a <strong>benchmark + dataset + training regime</strong> to evaluate this decision-making step.</p><p>It defines <strong>four possible model behaviors</strong>:</p><ol><li><strong>Tool Call</strong> — use an available tool with correct parameters.</li><li><strong>Follow-Up Question</strong> — ask for clarification if inputs are missing.</li><li><strong>Direct Answer</strong> — respond directly if possible (but risky if tools are needed).</li><li><strong>Unable to Answer</strong> — explicitly say tools are insufficient.</li></ol><p>📊 The dataset ensures that <em>all questions require tools to answer correctly</em>, so any direct answer is flagged as a hallucination.</p><h3>Key Findings</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*J42EajRiftOIdw7Ww-sp0A.png" /><figcaption>Table 3: Results on When2Call, BFCL v2 Live AST and BFCL v2 Irrelevance for community tool-calling models</figcaption></figure><ul><li><strong><em>Models often get it wrong.</em></strong><em> Even GPT-4–level models sometimes hallucinate tools or parameters, or answer directly when they shouldn’t.</em></li><li><strong><em>Current datasets are biased.</em></strong><em> Most training data only shows positive tool calls, so models lack exposure to “don’t call” scenarios.</em></li><li><strong><em>Adding When2Call helps.</em></strong><em> Fine-tuning on this benchmark improves judgment, especially around follow-ups and refusals.</em></li><li><strong><em>But trade-offs exist.</em></strong><em> Some models become too conservative — refusing to call tools even when they should.</em></li><li><strong><em>Preference optimization (RPO)</em></strong><em> balances the trade-offs better than supervised fine-tuning (SFT).</em></li></ul><h3>Practical Takeaways</h3><p>If you’re building LLM applications with tool use:</p><ul><li><em>Train with </em><strong><em>negative examples</em></strong><em> (missing info, unavailable tools).</em></li><li><em>Monitor </em><strong><em>tool hallucination</em></strong><em> just like content hallucination.</em></li><li><em>Use both </em><strong><em>MCQ evaluation</em></strong><em> (structured) and </em><strong><em>LLM-as-judge</em></strong><em> (free-form) to test decisions.</em></li><li><em>Consider </em><strong><em>preference optimization</em></strong><em> for more balanced behavior.</em></li></ul><h3>Conclusion</h3><p><em>When2Call</em> is a step toward making LLMs <strong>smarter, safer, and more honest</strong> in tool use.</p><p>It’s not enough for models to know <em>how</em> to call a tool — they also need to know <em>when not to call one</em>.</p><p>That decision-making ability is what will separate today’s chatbots from tomorrow’s reliable AI agents.</p><h3>References</h3><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//arxiv.org/pdf/2504.18851&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5d4107ce02f7e55a848eb47ad8538db/href">https://medium.com/media/c5d4107ce02f7e55a848eb47ad8538db/href</a></iframe><p><a href="https://github.com/NVIDIA/When2Call">GitHub - NVIDIA/When2Call: A dataset for training and evaluating LLMs on decision making about &quot;when (not) to call&quot; functions</a></p><p><a href="https://huggingface.co/datasets/nvidia/When2Call">https://huggingface.co/datasets/nvidia/When2Call</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=242df41c9513" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AdalFlow: A PyTorch-Like Framework for Building and Auto-Optimizing LLM Workflows]]></title>
            <link>https://medium.com/@AILearning/adalflow-a-pytorch-like-framework-for-building-and-auto-optimizing-llm-workflows-84f95a03f22b?source=rss-60a408e3c0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/84f95a03f22b</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[AILearning]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 05:48:31 GMT</pubDate>
            <atom:updated>2025-09-23T21:42:23.552Z</atom:updated>
            <content:encoded><![CDATA[<h3>AdalFlow: A PyTorch-Like Framework to Auto-Optimizing Prompt for your LLM agent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnwQ6EaWA9_BsBOqUKTUPg.png" /></figure><blockquote>Say goodbye to manual prompt engineering. AdalFlow is the all-in-one, auto-differentiative solution for optimizing prompts, whether you’re using zero-shot or few-shot learning. Backed by our state-of-the-art research (LLM-AutoDiff and Learn-to-Reason), our framework achieves the highest accuracy among all automatic prompt optimization libraries.</blockquote><p>The rise of large language models has completely changed the way we build applications — whether it’s chatbots, RAG systems, or fully autonomous agents. But as an AI engineer, trying to bring these models into production often feels like stitching together a bunch of experiments, rather than building a stable and reliable system.</p><p>We introduce AdalFlow: a PyTorch-like library designed to bring structure, clarity, and optimization to the world of LLM application development. Built as a community-driven project, AdalFlow is uniting AI research and production engineering into a single ecosystem.</p><p><a href="https://github.com/SylphAI-Inc/AdalFlow">GitHub - SylphAI-Inc/AdalFlow: AdalFlow: The library to build &amp; auto-optimize LLM applications.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6t--xpTlaKpe7HR7P5Cbw.jpeg" /><figcaption>Figure 1. The overview of AdalFlow</figcaption></figure><h3>Why We Built AdalFlow</h3><p>Modern AI development faces a paradox. On one hand, researchers push the boundaries of model capabilities with new techniques in prompting, evaluation, and optimization. On the other, production teams need reproducibility, scalability, and a way to iterate safely on real-world data.</p><p>Most libraries excel at one side of the equation but leave the other underserved. AdalFlow was born to bridge this gap. With 100% control and clarity of source code, it empowers researchers to experiment freely while giving product engineers the tools to build and ship with confidence.</p><h3>Why AdalFlow Matters</h3><p>By treating prompts as first-class citizens and introducing LLM-AutoDiff, AdalFlow provides what’s been missing in the LLM ecosystem:</p><ul><li>For researchers: A familiar PyTorch-like environment to prototype new prompting and training methods.</li><li>For engineers: Production-ready workflows that are debuggable, reproducible, and optimizable.</li><li>For teams: A shared framework that unites research and production into one healthy ecosystem.</li></ul><p><strong>Core Philosophy: Prompt Is the New Programming Language</strong></p><p>If PyTorch turned tensors into the lingua franca of deep learning, AdalFlow treats prompts as the new programming primitives.</p><p>Every LLM application boils down to structured prompts and their transformations. AdalFlow embraces this reality by making prompt engineering explicit and optimizable. Behind the scenes, it uses the jinja2 templating engine to let developers define composable prompt structures, ensuring that LLM apps are both modular and debuggable.</p><h3>Components: The Building Blocks of LLM Workflows</h3><p><a href="https://adalflow.sylph.ai/new_tutorials/core_concepts.html">Core Concepts - Build and Optimize LM Workflows</a></p><p>At the heart of AdalFlow lies the Component abstraction. Just as nn.Module became the foundation for PyTorch models, Components unify every stage of an LLM pipeline.</p><ul><li>Component: The base class for all workflows. Handles both training (forward) and inference (call) modes, with bicall bridging the two.</li><li>GradComponent: Components capable of backpropagation (e.g., Generators, Retrievers).</li><li>DataComponent: Lightweight components for formatting and parsing data (e.g., DataClassParser).</li><li>LossComponent: Wraps evaluation metrics and enables gradient-like feedback for text optimization.</li></ul><h3>Example 1: Q&amp;A with Object Counting (Component + DataComponent)</h3><p><a href="https://adalflow.sylph.ai/use_cases/question_answering.html">Question Answering - Build and Optimize LM Workflows</a></p><pre>template = r&quot;&quot;&quot;&lt;START_OF_SYSTEM_PROMPT&gt;<br>{{system_prompt}}<br>&lt;END_OF_SYSTEM_PROMPT&gt;<br>&lt;START_OF_USER&gt;<br>{{input_str}}<br>&lt;END_OF_USER&gt;&quot;&quot;&quot;<br><br>@adal.func_to_data_component<br>def parse_integer_answer(answer: str):<br>    numbers = re.findall(r&quot;\d+&quot;, answer)<br>    return int(numbers[-1])</pre><h3>What’s happening here?</h3><ul><li>parse_integer_answer is wrapped with @adal.func_to_data_component.</li><li>This turns a plain Python function into a DataComponent, which handles structured output parsing.</li><li>In this case, it ensures the model’s answer ends with a numerical value.</li></ul><p>Next , we define a full pipeline:</p><pre>class ObjectCountTaskPipeline(adal.Component):<br>    def __init__(self, model_client: adal.ModelClient, model_kwargs: Dict):<br>        super().__init__()<br>        system_prompt = adal.Parameter(<br>            data=&quot;You will answer a reasoning question. Think step by step. The last line should be &#39;Answer: $VALUE&#39;.&quot;,<br>            role_desc=&quot;Task instruction for the model&quot;,<br>            requires_opt=True,<br>            param_type=ParameterType.PROMPT,<br>        )<br>        self.llm_counter = adal.Generator(<br>            model_client=model_client,<br>            model_kwargs=model_kwargs,<br>            template=template,<br>            prompt_kwargs={&quot;system_prompt&quot;: system_prompt},<br>            output_processors=parse_integer_answer,<br>        )<br><br>    def bicall(self, question: str, id: str = None):<br>        return self.llm_counter(prompt_kwargs={&quot;input_str&quot;: question}, id=id)</pre><p><strong>ObjectCountTaskPipeline</strong> subclasses Component.</p><p>Inside it, we define:</p><ul><li>A Parameter of type PROMPT, which AdalFlow can later auto-optimize.</li><li>A Generator (a GradComponent) that executes the prompt, then passes the raw LLM output through our parse_integer_answer DataComponent.</li></ul><blockquote>The workflow is:<br> Prompt → LLM Generation → Structured Output Parsing → Final Numerical Answer.</blockquote><h3>Example 2: Classification with Structured Output (Component + DataClass)</h3><p><a href="https://adalflow.sylph.ai/use_cases/classification.html">Classification Optimization - Build and Optimize LM Workflows</a></p><p>Classification tasks are a perfect showcase of AdalFlow’s DataClass feature.</p><pre>@dataclass<br>class TRECExtendedData(adal.DataClass):<br>    question: str = field(metadata={&quot;desc&quot;: &quot;The question to be classified&quot;})<br>    rationale: str = field(metadata={&quot;desc&quot;: &quot;Step-by-step reasoning&quot;}, default=None)<br>    class_name: Literal[&quot;ABBR&quot;, &quot;ENTY&quot;, &quot;DESC&quot;, &quot;HUM&quot;, &quot;LOC&quot;, &quot;NUM&quot;] = field(<br>        metadata={&quot;desc&quot;: &quot;The class name&quot;}, default=None<br>    )<br><br>    __input_fields__ = [&quot;question&quot;]<br>    __output_fields__ = [&quot;rationale&quot;, &quot;class_name&quot;]</pre><ul><li>TRECExtendedData extends DataClass, which (like Pydantic) gives us schema enforcement.</li><li>Input: a question.</li><li>Output: a rationale (reasoning trace) and a class_name (final label).</li></ul><p>Now let’s plug it into a pipeline:</p><pre>class TRECClassifierStructuredOutput(adal.Component):<br>    def __init__(self, model_client: adal.ModelClient, model_kwargs: Dict):<br>        super().__init__()<br>        # Task description prompt<br>        task_desc_str = adal.Prompt(<br>            template=task_desc_template,<br>            prompt_kwargs={&quot;classes&quot;: [{&quot;label&quot;: l, &quot;desc&quot;: d} for l, d in zip(_COARSE_LABELS, _COARSE_LABELS_DESC)]}<br>        )()<br><br>        parser = adal.DataClassParser(<br>            data_class=TRECExtendedData,<br>            return_data_class=True,<br>            format_type=&quot;yaml&quot;<br>        )<br><br>        prompt_kwargs = {<br>            &quot;system_prompt&quot;: adal.Parameter(<br>                data=task_desc_str,<br>                role_desc=&quot;Task description&quot;,<br>                requires_opt=True,<br>                param_type=adal.ParameterType.PROMPT,<br>            ),<br>            &quot;output_format_str&quot;: parser.get_output_format_str(),<br>        }<br><br>        self.llm = adal.Generator(<br>            model_client=model_client,<br>            model_kwargs=model_kwargs,<br>            prompt_kwargs=prompt_kwargs,<br>            template=template,<br>            output_processors=parser,<br>        )<br><br>    def bicall(self, question: str, id: Optional[str] = None):<br>        return self.llm(prompt_kwargs={&quot;input_str&quot;: question}, id=id)</pre><ul><li>The Prompt defines the system instruction with class definitions.</li><li><strong>DataClassParser</strong> enforces structured YAML output that matches TRECExtendedData.</li><li>Generator (a GradComponent) runs the LLM with prompt + parser.</li></ul><p>Output is guaranteed to follow schema: rationale + class name. This ensures the model never drifts into free-form answers — it always returns structured classification results.</p><h3>Example 3: Training With Loss Component</h3><p>Finally, how do we train or optimize these components? That’s where <strong>LossComponent</strong> comes in:</p><pre>eval_fn = AnswerMatchAcc(type=&quot;exact_match&quot;).compute_single_item<br>loss_fn = adal.EvalFnToTextLoss(<br>    eval_fn=eval_fn,<br>    eval_fn_desc=&quot;exact_match: 1 if str(y) == str(y_gt) else 0&quot;<br>)</pre><ul><li><strong>AnswerMatchAcc</strong> is the evaluation metric.</li><li><strong>EvalFnToTextLoss</strong> wraps it as a <strong>LossComponent</strong>, enabling LLM-AutoDiff to optimize prompts automatically during training.</li></ul><blockquote>By attaching this to your pipeline, you get a full training loop:<br> Forward pass → Eval metric → Backward engine → Prompt optimization.</blockquote><h3>Agents: Reasoning Meets Action</h3><p>AdalFlow embraces the ReAct paradigm — combining reasoning (plan) with acting (tool use) — to build autonomous, auditable AI systems. An agent reasons about the task, selects tools, executes them, observes results, and iterates until it can deliver a final answer.</p><p><a href="https://adalflow.sylph.ai/new_tutorials/agents_runner.html">https://adalflow.sylph.ai/new_tutorials/agents_runner.html</a></p><p><a href="https://colab.research.google.com/github/SylphAI-Inc/AdalFlow/blob/main/notebooks/agents/agent_tutorial.ipynb">https://colab.research.google.com/github/SylphAI-Inc/AdalFlow/blob/main/notebooks/agents/agent_tutorial.ipynb</a></p><h3>Architecture at a Glance</h3><ul><li>Agent (planner + tool manager)<br> Handles <em>planning and decision-making</em> via a Generator-based planner, and knows what tools are available and how to call them.</li><li>Runner (executor + conversation loop)<br> Orchestrates <em>multi-step execution</em>, tool calling, observation handling, timeouts, and final answer synthesis.</li></ul><p>This separation lets you swap or customize planning vs. execution independently.</p><h3>Execution Flow (ReAct Loop Recap)</h3><ol><li>Planning — The Agent (Generator planner) analyzes input and proposes the next action.</li><li>Tool Selection — Chooses a tool from the registered set.</li><li>Tool Execution — The Runner invokes the tool with arguments.</li><li>Observation — The result is fed back to the planner.</li><li>Iteration — Repeat 1–4 up to max_steps or until confident.</li></ol><p>Final Answer — The planner synthesizes the answer (optionally into a structured type).</p><h3>Minimal, End-to-End Example</h3><blockquote>1) Define a Tool (callable or FunctionTool)</blockquote><pre># Tool: a plain Python callable works, or wrap with FunctionTool for extras.<br>def calculator(expression: str) -&gt; str:<br>    &quot;&quot;&quot;Evaluate a mathematical expression.&quot;&quot;&quot;<br>    try:<br>        result = eval(expression)<br>        return f&quot;Result: {result}&quot;<br>    except Exception as e:<br>        return f&quot;Error: {e}&quot;</pre><blockquote>2) Build the Agent (Planner + Tools)</blockquote><pre>from adalflow import Agent, Runner<br>from adalflow.components.model_client.openai_client import OpenAIClient<br><br>agent = Agent(<br>    name=&quot;CalculatorAgent&quot;,                 # Agent identifier<br>    tools=[calculator],                     # List of tools (callables or FunctionTool)<br>    model_client=OpenAIClient(),            # LLM client used by the planner (Generator-based)<br>    model_kwargs={&quot;model&quot;: &quot;gpt-4o&quot;, &quot;temperature&quot;: 0.3},<br>    max_steps=6,                            # Upper bound for ReAct loops<br>)</pre><p>What this maps to:</p><ul><li>Planner: An internal Generator that decides the next step (think: “reasoning trace”).</li><li><strong>ToolManager</strong>: The agent’s registry of permitted tools.</li><li>max_steps: Safety rail to prevent runaway loops.</li></ul><p><strong>Model Configuration</strong> (Swap Backends Easily)</p><pre># OpenAI<br>from adalflow.components.model_client.openai_client import OpenAIClient<br>agent = Agent(model_client=OpenAIClient(), model_kwargs={&quot;model&quot;: &quot;gpt-4o&quot;})<br><br># Anthropic<br>from adalflow.components.model_client.anthropic_client import AnthropicAPIClient<br>agent = Agent(model_client=AnthropicAPIClient(), model_kwargs={&quot;model&quot;: &quot;claude-3-sonnet-20240229&quot;})</pre><blockquote>3) Execute with the Runner (Multi-step Orchestration)</blockquote><pre>runner = Runner(agent=agent)  # Manages turns, tool calls, observations, and finalization<br><br>result = runner.call(<br>    prompt_kwargs={&quot;input_str&quot;: &quot;Invoke the calculator tool and calculate 15 * 7 + 23&quot;}<br>)<br><br>print(result.answer)<br># -&gt; &quot;The result of 15 * 7 + 23 is 128.&quot;</pre><p><strong>RunnerResult</strong> schema (returned by Runner.call)</p><pre># result has:<br># - result.step_history: [StepOutput(...)]  # Each step&#39;s action + observation<br># - result.answer: str | structured type     # Final synthesized answer<br># - result.error: None | Exception info      # Error if something failed<br># - result.ctx: dict | None                  # Optional execution metadata</pre><blockquote>This is the full ReAct loop in action:</blockquote><blockquote>Plan → Select Tool → Execute → Observe → Iterate → Answer.</blockquote><h3>Advanced Features (Production-Ready)</h3><blockquote>1) Streaming Execution (Real-Time Updates)</blockquote><pre># Pseudocode: actual API may differ slightly in your version.<br>stream = runner.stream(prompt_kwargs={&quot;input_str&quot;: &quot;Compute 42 * 73 and explain.&quot;})<br>for update in stream:<br>    # update contains partial thoughts, tool calls, observations, etc.<br>    print(update)</pre><p>Use streaming to surface <em>live</em> reasoning/tool progress in UIs.</p><blockquote>2) Human-in-the-Loop (Permission Management)</blockquote><pre>from adalflow.permissions import PermissionManager<br><br>class MyPerms(PermissionManager):<br>    def approve(self, tool_name: str, args: dict) -&gt; bool:<br>        # Example policy: only allow calculator; prompt user otherwise<br>        return tool_name == &quot;calculator&quot;<br><br>agent = Agent(<br>    name=&quot;GuardedAgent&quot;,<br>    tools=[calculator, search_tool],<br>    model_client=OpenAIClient(),<br><br>    model_kwargs={&quot;model&quot;: &quot;gpt-4o&quot;},<br>    permission_manager=MyPerms(),  # &lt;- Every tool call can be inspected/approved)</pre><p>Great for tools that hit external systems (files, emails, APIs).</p><blockquote>3) Custom System Templates (Planner Behavior)</blockquote><pre>custom_role_desc = &quot;&quot;&quot;<br>You are a careful, step-by-step data analyst.<br>When you use a tool, explain why and what you expect to get.<br>&quot;&quot;&quot;<br>agent = Agent(<br>    name=&quot;DataAnalyst&quot;,<br>    role_desc=custom_role_desc,        # Custom planner persona and guardrails<br>    model_client=OpenAIClient(),<br>    model_kwargs={&quot;model&quot;: &quot;gpt-4o&quot;, &quot;temperature&quot;: 0.2},<br>)</pre><blockquote>4) Tracing (Observability)</blockquote><pre># Configure tracing once (destination: console, file, or tracing backend)<br>from adalflow.tracing import enable_tracing<br>enable_tracing(project=&quot;adalflow-agents-demo&quot;)<br><br>result = runner.call(prompt_kwargs={&quot;input_str&quot;: &quot;Use the calculator for 88*19.&quot;})<br># Inspect step_history, tool IO, latency, errors, etc.</pre><p>Agent Summary:</p><ul><li>Agent = Reasoning + Tool selection (Generator-based planner + ToolManager)</li><li>Runner = Controlled execution loop (steps, tools, observations, final answer)</li><li>Tools = Safe, permissioned extensions to the agent’s capabilities</li><li>Production = Streaming, human approvals, tracing, structured outputs</li></ul><h3>Real-World Use Case: LinkedIn Recruitment Agent with AdalFlow</h3><p><a href="https://github.com/SylphAI-Inc/AdalFlow">GitHub - SylphAI-Inc/AdalFlow: AdalFlow: The library to build &amp; auto-optimize LLM applications.</a></p><p>Hiring top talent is one of the most resource-intensive parts of building a company. Recruiters spend hours scrolling LinkedIn, opening profiles, copying notes, and crafting outreach messages.</p><p>What if we could automate that entire workflow — turning hours of manual searching into minutes of AI-assisted sourcing?</p><p>That’s exactly what we built using AdalFlow’s Agent + Runner architecture combined with browser automation via Chrome DevTools Protocol (CDP).</p><h3>Before vs. After</h3><blockquote>❌ BEFORE: 2–3 hours per role. Traditional Recruiting Workflow (Manual)</blockquote><blockquote>1. Navigate to LinkedIn people search</blockquote><blockquote>2. Type in “Product Manager, San Francisco”</blockquote><blockquote>3. Scroll endlessly, click into profiles</blockquote><blockquote>4. Skim experience, education, skills</blockquote><blockquote>5. Take notes in spreadsheets</blockquote><blockquote>6. Write &amp; send DMs manually</blockquote><blockquote>✅ AFTER: 10 minutes per role. Automated Workflow with AdalFlow (Agentic)</blockquote><blockquote>1. Run: linkedin-agent — query “Product Manager” — limit 10</blockquote><blockquote>2. Agent plans and executes:</blockquote><blockquote>Extract profiles via browser automation</blockquote><blockquote>Evaluate candidates with scoring models</blockquote><blockquote>Draft personalized outreach messages</blockquote><blockquote>Smart search strategy</blockquote><blockquote>3. Get structured output: JSON/CSV with names, titles, LinkedIn URLs, evaluation scores, outreach drafts. Recruiters get to focus on talking to people, not copy-pasting data.</blockquote><h3>How It Works — Global State Architecture</h3><p>We structured the solution around a global state shared between tools. Each tool contributes partial data (search results, profiles, evaluations, outreach drafts), which the Agent combines into a full pipeline. Agent combines into a full pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFycNJUjvdMf8jdPlC6L8w.png" /><figcaption>Figure 2. Full Pipeline of LinkedInAgent</figcaption></figure><h3>Implementation with AdalFlow</h3><p>We implemented the <strong>LinkedInAgent</strong> by encapsulating:</p><blockquote><strong>Agent → Planner + Tools (search, extract, evaluate, outreach)</strong></blockquote><blockquote><strong>Runner → Execution loop with error handling and logging</strong></blockquote><pre>class LinkedInAgent:<br>    &quot;&quot;&quot;<br>    LinkedIn recruitment agent powered by AdalFlow.<br>    - Encapsulates Agent + Runner<br>    - Provides default recruitment tools<br>    - Supports both sync call() and async acall()<br>    &quot;&quot;&quot;<br><br><br>    def __init__(<br>        self,<br>        model_client: Optional[OpenAIClient] = None,<br>        model_kwargs: Optional[Dict[str, Any]] = None,<br>        max_steps: Optional[int] = None,<br>        role_desc: Optional[str] = None,<br>        **kwargs,<br>    ):<br>        # Defaults<br>        model_client = model_client or OpenAIClient()<br>        model_kwargs = model_kwargs or {&quot;model&quot;: &quot;gpt-4o&quot;, &quot;temperature&quot;: 0.3}<br>        max_steps = max_steps or 6<br><br><br>        # Recruitment workflow tools<br>        self.tools = [<br>            SmartCandidateSearchTool,        # 1. Search LinkedIn via CDP<br>            ExtractCandidateProfilesTool,    # 2. Extract structured profile data<br>            CandidateEvaluationTool,         # 3. Score candidates<br>            CandidateOutreachGenerationTool, # 4. Draft personalized outreach<br>            SaveOutreachResultsTool,         # 5. Persist results<br>        ]<br><br><br>        # Agent role description (personality / instructions)<br>        role_desc = role_desc or &quot;You are a recruitment assistant that sources and evaluates LinkedIn candidates.&quot;<br><br><br>        # Initialize Agent + Runner<br>        self.agent = Agent(<br>            name=&quot;LinkedInRecruiter&quot;,<br>            tools=self.tools,<br>            model_client=model_client,<br>            model_kwargs=model_kwargs,<br>            max_steps=max_steps,<br>            role_desc=role_desc,<br>            **kwargs,<br>        )<br>        self.runner = Runner(agent=self.agent, max_steps=max_steps)<br><br><br>    def call(self, query: str, context: Optional[Dict[str, Any]] = None):<br>        return self.runner.call(prompt_kwargs={&quot;input_str&quot;: query})<br><br><br>    async def acall(self, query: str, context: Optional[Dict[str, Any]] = None):<br>        return await self.runner.acall(prompt_kwargs={&quot;input_str&quot;: query})</pre><h3>Full Workflow Execution</h3><p>Here’s how we stitch the agent into a production workflow:</p><pre>def execute_search_workflow(self, progress_tracker=None) -&gt; List[Dict[str, Any]]:<br>    logger = get_logger()<br>    logger.set_workflow_context(&quot;workflow_main&quot;, &quot;initialization&quot;)<br><br><br>    log_phase_start(&quot;WORKFLOW_START&quot;, f&quot;Target: {self.limit} candidates for {self.query} in {self.location}&quot;)<br><br><br>    candidates = []<br>    try:<br>        log_info(&quot;🤖 Initializing LinkedIn agent...&quot;)<br>        agent, user_query = self.initialize_agent()<br><br><br>        if progress_tracker:<br>            progress_tracker.start_workflow()<br><br><br>        # Run full pipeline<br>        result = agent.call(query=user_query)<br>        self._print_agent_execution_steps(result)<br><br><br>        # Collect data from global state<br>        from ..core.workflow_state import get_complete_workflow_data<br>        workflow_data = get_complete_workflow_data()<br><br><br>        candidates = self._build_complete_candidate_data(workflow_data)<br><br><br>        log_info(f&quot;✅ Found {len(candidates)} candidates&quot;)<br>        return candidates<br><br><br>    except Exception as e:<br>        log_error(f&quot;❌ Workflow failed: {e}&quot;)<br>        return candidates</pre><h3>Example Output</h3><pre>linkedin-agent --query &quot;Product Manager San Francisco&quot; --limit 10</pre><p>We get structured results like:</p><pre>[<br>  {<br>    &quot;name&quot;: &quot;Alex Chen&quot;,<br>    &quot;title&quot;: &quot;Senior Product Manager @ Stripe&quot;,<br>    &quot;location&quot;: &quot;San Francisco Bay Area&quot;,<br>    &quot;profile_url&quot;: &quot;https://linkedin.com/in/alexchen&quot;,<br>    &quot;score&quot;: 0.92,<br>    &quot;outreach_message&quot;: &quot;Hi Alex, I came across your experience at Stripe...&quot;<br>  },<br>  {<br>    &quot;name&quot;: &quot;Maria Lopez&quot;,<br>    &quot;title&quot;: &quot;PM, Growth @ Airbnb&quot;,<br>    &quot;location&quot;: &quot;San Francisco Bay Area&quot;,<br>    &quot;profile_url&quot;: &quot;https://linkedin.com/in/marialopez&quot;,<br>    &quot;score&quot;: 0.88,<br>    &quot;outreach_message&quot;: &quot;Hi Maria, your background in growth product design really stood out...&quot;<br>  }<br>]</pre><blockquote>============================================================</blockquote><blockquote>WORKFLOW COMPLETION SUMMARY</blockquote><blockquote>============================================================</blockquote><blockquote>Success: ✅ Yes</blockquote><blockquote>Total Candidates: 2</blockquote><blockquote>Duration: 68.8 seconds</blockquote><blockquote>Session: 20250909_220617</blockquote><blockquote>Log Files:</blockquote><blockquote>• Main: logs/workflow_20250909_220617.log</blockquote><blockquote>• Debug: logs/debug_20250909_220617.log</blockquote><blockquote>• Agent Steps: logs/agent_steps_20250909_220617.log</blockquote><blockquote>• Errors: logs/errors_20250909_220617.log</blockquote><blockquote>============================================================</blockquote><blockquote>🏁 MAIN ✅ COMPLETED — Processed 2 candidates</blockquote><blockquote>[RESULTS] ✅ Recruitment workflow completed!</blockquote><blockquote>[RESULTS] 📊 Final result: Successfully processed 2 candidates</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5rd_35icranD0PS3bzHbA.jpeg" /><figcaption>Figure 3. Screenshot of the LinkedInAgent</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*iTfeAj1fLGfzMVrm" /></figure><h3>Looking Ahead</h3><p>As the LLM landscape evolves, frameworks like AdalFlow will become the backbone of application development. Just as PyTorch accelerated deep learning, AdalFlow has the potential to democratize LLM app building — from chatbots to agents to beyond.</p><p>If you’re excited about shaping the future of AI workflows, the project is open-source and community-driven. Whether you’re an AI researcher, product engineer, or just curious about building smarter applications, now’s the time to get involved.</p><p>🚀 AdalFlow isn’t just another library. It’s a paradigm shift in how we think about programming with language models.</p><p>AdalFlow is an open-source project created by <a href="https://medium.com/u/9e96fcccfe65">Li Yin</a>, the CEO and Founder of SYLPH.AI. The team is also preparing to launch an exciting new terminal-based agent product soon. Check it out and join the waitlist to be among the first to try it!</p><p><a href="https://adal.ml/">https://adal.ml/</a></p><p>Reference:</p><p><a href="https://github.com/SylphAI-Inc/AdalFlow">GitHub - SylphAI-Inc/AdalFlow: AdalFlow: The library to build &amp; auto-optimize LLM applications.</a></p><p>LLM-AutoDiff: Auto-Differentiate Any LLM Workflow : <a href="https://arxiv.org/abs/2501.16673">https://arxiv.org/abs/2501.16673</a></p><p><a href="https://adalflow.sylph.ai/index.html#">Build and Optimize LM Workflows</a></p><p><a href="https://colab.research.google.com/drive/1_YnD4HshzPRARvishoU4IA-qQuX9jHrT?usp=sharing">https://colab.research.google.com/drive/1_YnD4HshzPRARvishoU4IA-qQuX9jHrT?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84f95a03f22b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling NSA: A Paradigm Shift in Transformer Architecture for Long-Context AI from DeepSeek]]></title>
            <link>https://medium.com/@AILearning/unveiling-nsa-a-paradigm-shift-in-transformer-architecture-for-long-context-ai-from-deepseek-02e8deb087c3?source=rss-60a408e3c0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/02e8deb087c3</guid>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[AILearning]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 04:37:22 GMT</pubDate>
            <atom:updated>2025-02-20T18:24:22.374Z</atom:updated>
            <content:encoded><![CDATA[<p>The Relentless Pursuit of Artificial General Intelligence (AGI) and the Role of Native Sparse Attention (NSA) in Long-Context Processing</p><p>As the pursuit of Artificial General Intelligence (AGI) accelerates, the demand for more powerful Large Language Models (LLMs) grows, particularly in their ability to process long contexts. However, the traditional attention mechanism, with its quadratic computational complexity (O(N²)), presents a significant bottleneck in handling long sequences efficiently. This limitation becomes especially evident during training and inference stages. Enter <strong>Native Sparse Attention (NSA)</strong> — an innovative breakthrough that aims to reshape the Transformer architecture and usher in a new era of AI efficiency and high-performance capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*An9YVT1fpoisVkFGfBgA8Q.jpeg" /></figure><h3>1. What is Native Sparse Attention (NSA) and why was it developed?</h3><p>NSA is a novel, natively trainable sparse attention mechanism designed for efficient long-context modeling in large language models (LLMs). It addresses the quadratic computational complexity (O(N²)) of standard attention mechanisms when processing long sequences, which becomes a bottleneck in training and inference. <strong>Specifically, with softmax architectures, attention computation can account for 70–80% of the total latency when decoding 64k-length contexts.</strong> To address this, NSA employs a dynamic hierarchical sparse strategy. It combines coarse-grained token compression with fine-grained token selection to balance global context awareness and local precision. NSA reduces computation per query by organizing keys and values into <strong>temporal blocks</strong>.</p><pre># Define batch size, sequence length, and embedding dimensions<br>batch_size, seq_length, embed_dim = 4, 8, 32<br>x = torch.randn(batch_size, seq_length, embed_dim)  # Random input tensor<br><br># Define head size for multi-head attention<br>head_size = 16<br><br># Initialize linear layers for key, query, and value projections<br>key_layer = nn.Linear(embed_dim, head_size, bias=False)<br>query_layer = nn.Linear(embed_dim, head_size, bias=False)<br>value_layer = nn.Linear(embed_dim, head_size, bias=False)<br><br># Compute key, query, and value matrices<br>keys = key_layer(x)   # Shape: (batch_size, seq_length, head_size)<br>queries = query_layer(x)  # Shape: (batch_size, seq_length, head_size)<br>values = value_layer(x)  # Shape: (batch_size, seq_length, head_size)<br><br># Compute attention scores using dot product of queries and transposed keys<br>attention_scores = queries @ keys.transpose(-2, -1)  # Shape: (batch_size, seq_length, seq_length)<br><br># Create lower triangular mask for causal attention (prevents attending to future tokens)<br>mask = torch.tril(torch.ones(seq_length, seq_length))<br><br># Apply the mask: set attention scores for future positions to negative infinity<br>attention_scores = attention_scores.masked_fill(mask == 0, float(&#39;-inf&#39;))<br><br># Apply softmax to obtain attention weights<br>attention_weights = F.softmax(attention_scores, dim=-1)  # Shape: (batch_size, seq_length, seq_length)<br><br># Compute final output by applying attention weights to values<br>output = attention_weights @ values  # Shape: (batch_size, seq_length, head_size)</pre><h3>2. How does NSA work? What are its key algorithmic components?</h3><p>NSA employs a dynamic hierarchical sparse strategy, processing keys and values through parallel attention paths:</p><ul><li><strong>Token Compression:</strong> Aggregates sequential blocks of keys and values into block-level representations using MLPs to capture coarse-grained information, reducing computational burden. <strong>This is like summarizing the main idea of a few sentences into a single, shorter sentence.</strong></li><li><strong>Token Selection:</strong> Selectively retains individual keys and values deemed most relevant, identified using block-wise selection based on attention scores derived from the compressed tokens. This is like choosing to only read the most important paragraphs in a document. This preserves fine-grained information.</li><li><strong>Sliding Window:</strong> Maintains recent tokens in a window to explicitly handle local context, preventing the compression and selection branches from being shortcuts by local patterns.</li><li><strong>Gating Mechanism</strong>: Finally, NSA combines the information from the compressed tokens, selected tokens, and sliding window to make a final decision. It uses a “gate” to decide how much weight to give to each source of information.</li></ul><pre>class NSATokenProcessor(nn.Module):<br>    def __init__(self, input_dim, block_size, compressed_dim, selected_dim):<br>        super(NSATokenProcessor, self).__init__()<br>        self.block_size = block_size<br>        self.compressed_dim = compressed_dim<br>        self.selected_dim = selected_dim<br><br>        # Token Compression MLPs<br>        self.key_compression_mlp = nn.Sequential(<br>            nn.Linear(input_dim * block_size, compressed_dim),<br>            nn.ReLU(),<br>            nn.Linear(compressed_dim, compressed_dim)<br>        )<br>        self.value_compression_mlp = nn.Sequential(<br>            nn.Linear(input_dim * block_size, compressed_dim),<br>            nn.ReLU(),<br>            nn.Linear(compressed_dim, compressed_dim)<br>        )<br><br>        # Token Selection Attention<br>        self.selection_attention = nn.MultiheadAttention(compressed_dim, num_heads=1)<br><br>        # Selection MLPs<br>        self.key_selection_mlp = nn.Linear(input_dim, selected_dim)<br>        self.value_selection_mlp = nn.Linear(input_dim, selected_dim)<br><br>        # Gating Mechanism<br>        self.gate_compressed = nn.Linear(compressed_dim, 1)<br>        self.gate_selected = nn.Linear(selected_dim, 1)<br>        self.gate_window = nn.Linear(input_dim, 1)<br><br>    def forward(self, keys, values, window_keys, window_values):<br>        &quot;&quot;&quot;<br>        Args:<br>            keys: (batch_size, seq_len, input_dim)<br>            values: (batch_size, seq_len, input_dim)<br>            window_keys: (batch_size, window_size, input_dim)<br>            window_values: (batch_size, window_size, input_dim)<br>        Returns:<br>            output_keys: (batch_size, seq_len, output_dim)<br>            output_values: (batch_size, seq_len, output_dim)<br>        &quot;&quot;&quot;<br>        batch_size, seq_len, input_dim = keys.size()<br><br>        # Token Compression<br>        compressed_keys = []<br>        compressed_values = []<br>        for i in range(0, seq_len, self.block_size):<br>            block_keys = keys[:, i:i + self.block_size, :].reshape(batch_size, -1)<br>            block_values = values[:, i:i + self.block_size, :].reshape(batch_size, -1)<br>            compressed_keys.append(self.key_compression_mlp(block_keys))<br>            compressed_values.append(self.value_compression_mlp(block_values))<br><br>        compressed_keys = torch.stack(compressed_keys, dim=1)  # (batch_size, num_blocks, compressed_dim)<br>        compressed_values = torch.stack(compressed_values, dim=1)<br><br>        # Token Selection<br>        selection_attention_output, _ = self.selection_attention(<br>            keys.transpose(0, 1), compressed_keys.transpose(0, 1), compressed_keys.transpose(0, 1)<br>        ) # (seq_len, batch_size, compressed_dim)<br><br>        selection_attention_output = selection_attention_output.transpose(0,1)<br><br>        selected_keys = self.key_selection_mlp(keys)<br>        selected_values = self.value_selection_mlp(values)<br><br>        # Gating Mechanism<br>        gate_compressed_weights = torch.sigmoid(self.gate_compressed(compressed_keys).squeeze(-1)) # (batch_size, num_blocks)<br>        gate_selected_weights = torch.sigmoid(self.gate_selected(selected_keys).squeeze(-1)) # (batch_size, seq_len)<br>        gate_window_weights = torch.sigmoid(self.gate_window(window_keys).squeeze(-1)) # (batch_size, window_size)<br><br>        # Reshape for element-wise multiplication.<br>        gate_compressed_weights = torch.repeat_interleave(gate_compressed_weights, self.block_size, dim=1)[:, :seq_len] # (batch, seq_len) to match selected and keys.<br>        gate_window_weights = torch.mean(gate_window_weights, dim = 1, keepdim=True).repeat(1, seq_len) # average window gate to match seq_len<br><br>        # Combine using gates<br>        output_keys = gate_compressed_weights.unsqueeze(-1) * compressed_keys.repeat_interleave(self.block_size, dim=1)[:, :seq_len, :] + \<br>                      gate_selected_weights.unsqueeze(-1) * selected_keys + \<br>                      gate_window_weights.unsqueeze(-1) * keys<br><br>        output_values = gate_compressed_weights.unsqueeze(-1) * compressed_values.repeat_interleave(self.block_size, dim=1)[:, :seq_len, :] + \<br>                      gate_selected_weights.unsqueeze(-1) * selected_values + \<br>                      gate_window_weights.unsqueeze(-1) * values<br><br>        return output_keys, output_values</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAr4l5xzd_cH7AmZiyASAw.png" /><figcaption>Overview of NSA’s architecture[1]</figcaption></figure><h3>3. What are the hardware-aligned optimizations in NSA?</h3><p>To achieve efficient processing of long sequences, Native Sparse Attention (NSA) incorporates several hardware-aligned optimizations, focusing on maximizing the utilization of modern hardware capabilities such as Tensor Cores and memory access efficiency.</p><p>Key aspects of NSA’s hardware-aligned optimizations include:</p><ul><li><strong>Blockwise Sparse Attention:</strong> NSA processes keys and values in continuous blocks, which is essential for efficient computation on modern GPUs. Modern GPU architectures offer significantly higher throughput for continuous block accesses compared to random index-based reads. This design enables optimal utilization of Tensor Cores.</li><li><strong>Arithmetic Intensity Balancing:</strong> NSA’s design ensures a balanced ratio of compute operations to memory accesses, aligning with the hardware’s capabilities. The goal is to keep the arithmetic intensity above a critical threshold so that computation is compute-bound (limited by GPU FLOPS) rather than memory-bound (limited by memory bandwidth).</li><li><strong>Group-Centric Data Loading:</strong> During the kernel implementation, NSA loads queries by Grouped-Query Attention (GQA) groups. For each inner loop, all heads’ queries in the GQA group at a given position and their shared sparse key/value block indices are loaded. This facilitates shared KV (key/value) fetching.</li><li><strong>Shared KV Fetching:</strong> The kernel sequentially loads continuous key/value blocks indexed by ( I ) into SRAM (Static Random-Access Memory) to minimize memory loading. This is particularly important because decoding is memory-bandwidth constrained.</li><li><strong>Kernel Design for Sparse Selection Attention:</strong> NSA uses a specialized kernel design for sparse selection attention. Instead of loading temporally continuous query blocks into SRAM, it loads all query heads within a GQA group into SRAM for each position on the query sequence. This optimization addresses the issue of queries within a block requiring disjoint KV blocks, which would result in inefficient memory access.</li><li><strong>Optimization for Tensor Core Utilization:</strong> By using blockwise memory access patterns, NSA maximizes Tensor Core utilization through coalesced loads8. This involves loading data in a way that optimizes the use of Tensor Cores, which are designed for efficient matrix multiplication.</li><li><strong>Efficient Loop Scheduling:</strong> The kernel’s loop scheduling eliminates redundant KV transfers, further improving arithmetic intensity. The outer loop is placed on the grid to simplify and optimize the kernel since the inner-loop length remains nearly identical for different query blocks.</li><li><strong>Specialized Kernels:</strong> NSA implements specialized kernels to maximize its practical efficiency. The computations for compression and sliding window attention are compatible with existing FlashAttention-2 kernels. However, a specialized kernel design is introduced for sparse selection attention</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*Zrskx4saT5OLj02usJSzXg.png" /><figcaption>Kernel design for NSA. The kernel loads queries by GQA groups (Grid Loop), fetches corresponding sparse KV blocks (Inner Loop), and performs attention computation on SRAM[1]</figcaption></figure><p>These optimizations minimize memory access and improve arithmetic intensity, leading to faster training and inference.</p><h3>4. How does NSA enable end-to-end training, and why is this important?</h3><p>NSA enables stable end-to-end training through efficient algorithms and backward operators. This is crucial because it allows the model to fully exploit the sparsity patterns of attention during training, unlike many existing sparse attention methods that primarily focus on inference and retain a pretrained Full Attention backbone. Native training allows the sparse attention module to adapt in sync with other model components during pretraining, further optimizing efficiency.</p><h3>5. How does NSA compare to Full Attention and other sparse attention methods in terms of performance and efficiency?</h3><p>Experiments demonstrate that NSA achieves comparable or superior performance to full attention baselines on general benchmarks, long-context evaluations, and chain-of-thought reasoning evaluations. It also outperforms existing sparse attention approaches. Critically, NSA delivers substantial speedups across decoding, forward, and backward stages compared to Full Attention, with the speedup ratio increasing for longer sequences. For example, it achieves speedups of up to 11.6x during decoding of 64k-length sequences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLtwMf8NxChCvCYqEiifXA.png" /><figcaption>Comparison of Triton-based NSA kernel with Triton-based FlashAttention-2 kernel [1]</figcaption></figure><h3>6. What are the advantages of blockwise token selection compared to other selection strategies?</h3><p>Blockwise selection is crucial to achieve efficient computation on modern GPUs. Modern GPU architectures exhibit significantly higher throughput for continuous block accesses compared to random index-based reads. Also, blockwise computation enables optimal utilization of Tensor Cores. Furthermore, attention scores often exhibit spatial continuity, suggesting that neighboring keys tend to share similar importance levels. This allows the model to choose blocks more efficiently, rather than individual tokens.</p><h3>7. What are Mixture of Block Attention (MoBA) and other alternative token pruning strategies, and how do they relate to NSA?</h3><p>MoBA is a related approach from Moonshot AI that also employs a block-sparse attention mechanism, dynamically selecting relevant blocks for computation. Like NSA, MoBA emphasizes trainable sparsity and aims for efficient long-context processing. Alternative token pruning strategies, such as clustering-based methods (ClusterKV), fixed sparse patterns (SlidingWindow), and KV-cache eviction methods (H2O, SnapKV), each have their limitations. Some introduce non-trivial computational overhead, others lack flexibility, and some suffer from issues in multi-turn dialogues due to token eviction. The hardware-aware design and end-to-end trainability of NSA address many of these challenges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2BU3G4NiU1mt8jMhnorsqA.png" /><figcaption>MoBA Structure [2]</figcaption></figure><h3>8. How does NSA challenge current hardware design and existing Transformer optimizations?</h3><p>NSA potentially disrupts the hardware design landscape optimized for traditional Transformer architectures, especially attention layers. It may require redesign of Transformer-optimized hardware and libraries (e.g., NVIDIA’s Transformer Engine), since they may not be optimal for sparse attention patterns. By showing the importance of algorithm-hardware co-design, NSA encourages a shift towards hardware that can efficiently handle sparse computations, opening the door for a new wave of hardware innovation.</p><h3>Glossary of Key Terms:</h3><ul><li><strong>Attention Mechanism:</strong> A neural network layer that allows the model to focus on the most relevant parts of the input sequence when processing it.</li><li><strong>Sparse Attention:</strong> A variant of the attention mechanism that reduces computational cost by selectively computing attention scores for only a subset of query-key pairs.</li><li><strong>Full Attention:</strong> The standard attention mechanism where attention scores are computed for all query-key pairs.</li><li><strong>Long-Context Modeling:</strong> The ability of a language model to process and understand very long sequences of text.</li><li><strong>KV-Cache:</strong> The key-value cache, used in transformer models to store the keys and values from previous layers, which are needed to compute attention scores.</li><li><strong>MQA (Multi-Query Attention):</strong> A variation of attention where multiple query heads share the same key and value projections, reducing memory access during decoding.</li><li><strong>GQA (Grouped-Query Attention):</strong> A generalization of MQA where query heads are grouped, and each group shares the same key and value projections.</li><li><strong>Arithmetic Intensity:</strong> The ratio of compute operations to memory accesses, which determines whether a computation is compute-bound or memory-bound.</li><li><strong>Tensor Core:</strong> Specialized hardware units in GPUs designed for accelerating matrix multiplication operations.</li><li><strong>FlashAttention:</strong> A hardware-aware attention algorithm that optimizes memory access patterns to improve performance.</li><li><strong>Triton:</strong> An open-source programming language and compiler for writing efficient GPU kernels.</li><li><strong>SRAM:</strong> Static Random-Access Memory, a type of fast memory used in GPUs for storing intermediate data during computation.</li><li><strong>HBM:</strong> High Bandwidth Memory, a type of memory designed for high-speed data transfer, commonly used in GPUs.</li><li><strong>Autoregressive Decoding:</strong> A decoding method where the model generates one token at a time, conditioned on the previously generated tokens.</li><li><strong>Prefilling:</strong> The initial stage of inference where the model processes the input prompt before generating the output.</li><li><strong>Chain-of-Thought Reasoning:</strong> A prompting technique where the language model is encouraged to generate intermediate reasoning steps before arriving at the final answer.</li><li><strong>MoE (Mixture of Experts):</strong> A model architecture where different parts of the model (experts) are specialized in handling different types of inputs.</li><li><strong>SwiGLU:</strong> A type of activation function used in neural networks.</li><li><strong>YaRN:</strong> A method for extending the context window of large language models.</li></ul><h3>Reference:</h3><p>[1]<a href="https://arxiv.org/pdf/2502.11089">https://arxiv.org/pdf/2502.11089</a></p><p>[2]<a href="https://github.com/MoonshotAI/MoBA/blob/master/MoBA_Tech_Report.pdf">https://github.com/MoonshotAI/MoBA/blob/master/MoBA_Tech_Report.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02e8deb087c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Retrieval-Augmented Generation with Knowledge Graphs]]></title>
            <link>https://medium.com/@AILearning/enhancing-retrieval-augmented-generation-with-knowledge-graphs-0350c823369d?source=rss-60a408e3c0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/0350c823369d</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[AILearning]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 01:18:17 GMT</pubDate>
            <atom:updated>2024-07-08T01:18:17.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aXRuNpzR7pFVegA_" /></figure><p>Retrieval-Augmented Generation (RAG) is a technique designed to enhance large language model (LLM) outputs by incorporating real-world information. This technique is a cornerstone of most LLM-based tools, with the majority of RAG approaches employing vector similarity as their primary search method. This standard approach is referred to as Baseline RAG.</p><p><strong>Baseline RAG</strong> relies on vector similarity to retrieve relevant information chunks, which it then uses to augment LLM responses. While this method has been beneficial, especially for reasoning about private datasets — data that the LLM has not been trained on or encountered before, such as proprietary research, business documents, or internal communications — it has notable limitations:</p><ol><li><strong>Connecting Disparate Information</strong>: Baseline RAG often struggles to synthesize insights when answering questions that require linking disparate pieces of information through their shared attributes. This limitation prevents it from effectively “connecting the dots” across various data points.</li><li><strong>Holistic Understanding</strong>: Baseline RAG performs poorly when tasked with comprehending and summarizing broad semantic concepts over large data collections or extensive singular documents. Its vector similarity approach fails to grasp the overarching themes and nuanced relationships within the data.</li></ol><p>To address these shortcomings, the tech community has been developing methods to extend and enhance RAG. One such advanced method is <strong>GraphRAG</strong>, developed by Microsoft Research.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*UUgFt2KauMuOI4vS.jpg" /><figcaption>An LLM-generated knowledge graph built using GPT-4 Turbo [<a href="https://microsoft.github.io/graphrag/">https://microsoft.github.io/graphrag/</a>]</figcaption></figure><p><strong>GraphRAG</strong> leverages LLMs to construct a knowledge graph from an input corpus. This knowledge graph, enriched with community summaries and outputs from graph machine learning, is used to enhance prompts at query time. GraphRAG demonstrates significant improvements in handling complex information, outperforming Baseline RAG in key areas:</p><ul><li><strong>Enhanced Connectivity</strong>: By using a knowledge graph, GraphRAG excels at connecting disparate pieces of information. It navigates through shared attributes and relationships, providing synthesized insights that are more coherent and comprehensive.</li><li><strong>Deep Semantic Understanding</strong>: GraphRAG’s ability to generate and utilize community summaries and graph-based insights allows it to better understand and summarize broad semantic concepts. This makes it particularly effective in dealing with large data collections or extensive documents.</li></ul><p>GraphRAG represents a substantial advancement in the application of RAG techniques, showing marked improvements in question-and-answer performance, particularly in scenarios where reasoning about complex information is required. This method demonstrates a level of intelligence and mastery that surpasses other approaches previously applied to private datasets, setting a new benchmark for LLM-based information retrieval and comprehension.</p><p>The basic steps of the GraphRAG process are as follows:</p><h3>Index</h3><ol><li>Slice the input corpus into a series of TextUnits, serving as analyzable units and providing fine-grained references in our outputs.</li><li>Use an LLM to extract all entities, relationships, and key claims from the TextUnits.</li><li>Perform hierarchical clustering of the graph using the <a href="https://arxiv.org/pdf/1810.08473.pdf">Leiden technique</a>. Each circle represents an entity (e.g., a person, place, or organization), with size indicating the degree and color indicating the community.</li><li>Generate summaries of each community and its constituents from the bottom up, aiding in holistic dataset understanding.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*eE54orKO3cke918jMOq1mQ.png" /><figcaption>Indexing Dataflow [<a href="https://microsoft.github.io/graphrag/posts/index/1-default_dataflow/">https://microsoft.github.io/graphrag/posts/index/1-default_dataflow/</a>]</figcaption></figure><h4>Phase 1: Compose TextUnits</h4><ul><li><strong>Objective</strong>: Transform input documents into manageable chunks called TextUnits, which are central to subsequent graph extraction techniques.</li><li><strong>Process</strong>: Documents are split into TextUnits, typically of 300 tokens by default, although configurations up to 1200 tokens have been used for efficiency.</li><li><strong>Configurations</strong>: Users can configure the chunk size and the grouping of TextUnits, aligning them strictly with document boundaries or allowing more flexible associations, particularly for shorter documents.</li></ul><h4>Phase 2: Graph Extraction</h4><ul><li><strong>Objective</strong>: Analyze TextUnits to extract graph primitives: Entities, Relationships, and Claims.</li><li><strong>Process</strong>: Entities and relationships are identified and extracted simultaneously, followed by claim extraction. The resulting data forms subgraphs which are then merged based on shared characteristics to avoid redundancy.</li></ul><h4>Phase 3: Graph Augmentation</h4><ul><li><strong>Objective</strong>: Enhance the graph with additional information to uncover community structures and improve graph understanding.</li><li><strong>Techniques</strong>: Use of Hierarchical Leiden Algorithm for community detection and Node2Vec for graph embedding, culminating in the creation of detailed graph tables.</li></ul><h4>Phase 4: Community Summarization</h4><ul><li><strong>Objective</strong>: Generate and summarize reports for each community detected in the graph to provide insights at various granular levels.</li><li><strong>Process</strong>: Community reports are generated using summaries that capture distinct information, further enhanced by embeddings to deepen the understanding of the community structure.</li></ul><h4>Phase 5: Document Processing</h4><ul><li><strong>Objective</strong>: Create and refine a Documents table for the knowledge model.</li><li><strong>Process</strong>: Documents are linked back to the original TextUnits and embedded to represent relationships and relevance accurately, facilitating an organized network visualization in later stages.</li></ul><h4>Phase 6: Network Visualization</h4><ul><li><strong>Objective</strong>: Visualize the network based on the high-dimensional vector spaces of the Entity-Relationship and Document graphs.</li><li><strong>Technique</strong>: Utilize UMAP dimensionality reduction to create a 2D visualization of the graph, making complex relationships easier to understand.</li></ul><h3>Query</h3><p>At query time, these structures provide materials for the LLM context window when answering a question. The primary query modes are:</p><ul><li><a href="https://microsoft.github.io/graphrag/posts/query/0-global_search"><em>Global Search</em></a>: Uses community summaries to reason about holistic questions concerning the corpus.</li><li><a href="https://microsoft.github.io/graphrag/posts/query/1-local_search"><em>Local Search</em></a>: Focuses on specific entities by exploring their neighbors and associated concepts.</li></ul><p><strong>Global Search:</strong> Given a user query and, optionally, the conversation history, the global search method uses a collection of LLM-generated community reports from a specified level of the graph’s community hierarchy as context data to generate responses in a map-reduce manner. Community reports are segmented into text chunks of predefined size. Each chunk produces an intermediate response containing a list of points with numerical ratings indicating importance. The most important points are aggregated to generate the final response, using LLM to score and filter the responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8nZw-kbuDa6_drAnssMyog.png" /><figcaption>Methodology for global search [<a href="https://microsoft.github.io/graphrag/posts/query/0-global_search/">https://microsoft.github.io/graphrag/posts/query/0-global_search/</a>]</figcaption></figure><p><strong>Local Search:</strong> Given a user query and, optionally, the conversation history, the local search method identifies a set of semantically-related entities from the knowledge graph. These entities serve as access points, enabling the extraction of further relevant details such as connected entities, relationships, entity covariates, and community reports. Relevant text chunks from the raw input documents associated with the identified entities are also extracted. These data sources are prioritized and filtered to fit within a single context window, generating a response to the user query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnYQqZVlWVMtMo5XbAlu4w.png" /><figcaption>Methodology for local search [<a href="https://microsoft.github.io/graphrag/posts/query/1-local_search/">https://microsoft.github.io/graphrag/posts/query/1-local_search/</a>]</figcaption></figure><h3>Prompt Tuning</h3><p>Using GraphRAG with your data out of the box may not yield the best results. We strongly recommend fine-tuning your prompts following the <a href="https://microsoft.github.io/graphrag/posts/index/3-prompt_tuning">Prompt Tuning Guide</a> in our documentation.</p><p><strong>Prompt Tuning⚙️</strong> The GraphRAG indexer, by default, runs with a set of prompts designed for broad knowledge discovery. However, you might want to tune the prompts to better suit your specific use case. We provide a means for this by allowing custom prompt files with token-replacements internally. Each prompt may be overridden by writing a custom prompt file in plaintext, using tokens such as {input_text}, {entity_types}, {tuple_delimiter}, {record_delimiter}, and {completion_delimiter}.</p><p><strong>Entity/Relationship Extraction</strong> <a href="http://github.com/microsoft/graphrag/blob/main/graphrag/index/graph/extractors/graph/prompts.py">Prompt Source</a></p><p><strong>Summarize Entity/Relationship Descriptions</strong> <a href="http://github.com/microsoft/graphrag/blob/main/graphrag/index/graph/extractors/summarize/prompts.py">Prompt Source</a></p><p><strong>Claim Extraction</strong> <a href="http://github.com/microsoft/graphrag/blob/main/graphrag/index/graph/extractors/claims/prompts.py">Prompt Source</a></p><p>Note: There is an additional parameter for Claim Description used in claim extraction. The default value is &quot;Any claims or facts that could be relevant to information discovery.&quot; See the <a href="https://microsoft.github.io/graphrag/posts/config/overview/">configuration documentation</a> for details on how to change this.</p><p><strong>Generate Community Reports</strong> <a href="http://github.com/microsoft/graphrag/blob/main/graphrag/index/graph/extractors/community_reports/prompts.py">Prompt Source</a></p><p><strong>Tokens (values provided by extractor)</strong> • <strong>{input_text}</strong> — The input text to generate the report with, containing tables of entities and relationships.</p><h3>Insides:</h3><p>Many critical real-world applications, such as scientific literature reviews, legal case briefings, and medical diagnoses, necessitate the ability to understand and integrate knowledge spread across multiple documents or chunks of information. However, traditional Retrieval-Augmented Generation (RAG) methods fall short in assisting large language models (LLMs) with tasks that demand comprehension across these chunk boundaries, as each chunk is processed independently without considering the broader context.</p><p>To address this limitation, this article introduces four groundbreaking methods designed to enhance the global understanding of documents or corpora. These methods incorporate advanced techniques to facilitate a more holistic integration and comprehension of dispersed information, thereby improving the performance and utility of LLMs in complex, real-world scenarios.</p><p><strong>HippoRAG</strong>: Inspired by the hippocampal indexing theory of human long-term memory, HippoRAG combines the strengths of LLMs, knowledge graphs, and personalized PageRank algorithms. This framework mimics the way humans store and retrieve long-term memories, offering a more natural and efficient way to manage and access large volumes of information.</p><p><strong>spRAG</strong>: This method enhances the standard RAG system through two key techniques: AutoContext and Relevant Segment Extraction (RSE). AutoContext dynamically adjusts the context provided to the LLM based on the specific query, while RSE identifies and extracts the most pertinent segments of information. Together, these techniques significantly improve the precision and relevance of the responses generated by the LLM.</p><h3>Reference:</h3><p><a href="https://arxiv.org/pdf/2402.15183">https://arxiv.org/pdf/2402.15183</a></p><p><a href="https://github.com/XiaoxinHe/Awesome-Graph-LLM">GitHub - XiaoxinHe/Awesome-Graph-LLM: A collection of AWESOME things about Graph-Related LLMs.</a></p><p><a href="https://arxiv.org/pdf/2405.20139">https://arxiv.org/pdf/2405.20139</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0350c823369d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Pitfalls of Mocking: Enhancing Python Code Test Quality!]]></title>
            <link>https://medium.com/@AILearning/the-pitfalls-of-mocking-enhancing-python-code-test-quality-81475f272f82?source=rss-60a408e3c0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/81475f272f82</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[AILearning]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 22:28:41 GMT</pubDate>
            <atom:updated>2024-06-19T22:28:41.703Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HgXTZp9xEh8R7Qv4" /></figure><p>Using mocking in testing is often criticized because it can lead to a false sense of security and does not adequately test interactions with services, such as databases or external APIs. 🤔 Mocking typically tests only the “happy path,” ignoring potential errors that could arise in the real world. 🚫</p><p><strong>🔧 Fundamentals of Mocking</strong> Mocking involves simulating service behavior to test code in isolation. However, isolating code from its real-world interactions is often the root of the problem, not the solution. 💡 This isolation can lead to undiscovered errors, as mocks may not fully simulate the edge cases or failure modes of the services they represent. 😨</p><p><strong>🚀 To address the issues with mocking, here are several alternatives to enhance the quality of Python code testing:</strong></p><ul><li><strong>🛠️ Enhanced Unit Testing:</strong> Refactor code to improve testability, such as decomposing conditional logic or introducing parameter objects. This allows for more detailed testing of different paths and scenarios. 💡</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6f63eEs433vw4q8E0ObFQ.png" /><figcaption><strong>Enhanced Unit Testing</strong></figcaption></figure><ul><li><strong>🗄️ Using In-Memory Databases:</strong> Replace real I/O with faster alternatives like in-memory databases for more effective unit testing. This can reduce reliance on mocks while speeding up testing. ⚡</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HlMBD8X2bHpRl6c1ioFvWg.png" /><figcaption><strong>Using In-Memory Databases</strong></figcaption></figure><ul><li><strong>💾 Direct I/O Testing:</strong> With the improvement of modern hardware performance, emphasize real I/O operations in tests to reduce the need for mocking. This approach more accurately simulates the actual operating environment. 📈</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNh0q7HJjhPQEJmqv3R2yg.png" /><figcaption><strong>Direct I/O Testing</strong></figcaption></figure><ul><li><strong>🧩 Focus on Separation:</strong> Extract business logic from I/O operations to simplify testing. Separating core logic and external dependencies facilitates more convenient independent testing. 📝</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xgatAGIqsCAYJ0mprGYhw.png" /><figcaption><strong>Focus on Separation</strong></figcaption></figure><ul><li><strong>🌐 End-to-End (E2E) Integration Testing:</strong> Focus on backend server-side testing and minimal UI-driven testing to ensure all components work together as expected. E2E testing can verify the system’s overall functionality, not just individual modules. ✅</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KSTPQ_RT-o4_umkjuVBYw.png" /></figure><p>These methods can more effectively capture potential errors in the system, enhancing the quality and reliability of testing. 🌟</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81475f272f82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[In the evolving landscape of artificial intelligence, the synergy between Large Language Models…]]></title>
            <link>https://medium.com/@AILearning/in-the-evolving-landscape-of-artificial-intelligence-the-synergy-between-large-language-models-7c235c11ad7a?source=rss-60a408e3c0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c235c11ad7a</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[AILearning]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 05:00:48 GMT</pubDate>
            <atom:updated>2023-11-27T03:54:07.752Z</atom:updated>
            <content:encoded><![CDATA[<h3>Review of Survey: Recommendation Systems with LLM</h3><p>In the evolving landscape of artificial intelligence, the synergy between Large Language Models (LLMs) and recommendation systems has emerged as a pivotal area of research. There are many works delving into this intriguing intersection, exploring how the advanced capabilities of LLMs can be harnessed to revolutionize the field of recommender systems.</p><blockquote><em>The GitHub repository at </em><a href="https://github.com/WLiK/LLM4Rec-Awesome-Papers"><em>https://github.com/WLiK/LLM4Rec-Awesome-Papers</em></a><em> serves as an excellent starting point. It is highly recommended for everyone to add it to their bookmarks.</em></blockquote><p>Our journey commences with a comprehensive analysis of generative recommendation — a novel paradigm where LLMs directly generate recommendations or related content, circumventing traditional ranking-based approaches. We systematically address fundamental questions regarding the nature, necessity, and implementation strategies of LLM-based generative recommendation for various tasks, including rating prediction, top-N recommendation, sequential recommendation, explainable recommendation, and review generation.</p><blockquote><em>&lt;&lt;Large Language Models for Generative Recommendation: A Survey and Visionary Discussions&gt;&gt;</em></blockquote><p>The paper addresses three key questions:</p><p><strong>What is Generative Recommendation?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*OlOyffMkoqlRIoai" /><figcaption>image from origin paper</figcaption></figure><p>This approach directly generates recommendations or related content without needing to rank each candidate individually.</p><p><strong>Why Should Recommendation Systems Adopt Generative Recommendation?</strong></p><p>The strength of LLMs in this context is their ability to represent a vast array of items with a limited number of tokens.</p><p><strong>How to Implement LLM-based Generative Recommendation for Various Tasks?</strong></p><p>The paper discusses different methods such as rating prediction, top-N recommendation, sequential recommendation, explainable recommendation, and review generation, illustrating how LLMs can be utilized in each scenario.</p><p>For example, Rating Prediction instruction prompt p(u, i), e.g., “how would user 1234 rate item 5678”, such that LLM can understand this task. Top-N Recommendation “select one item to recommend for user 1234 from the following candi- dates: item 6783, …, item 9312, item 2834”, the LLM can generate an item ID, e.g., “9312” as recommendation</p><blockquote><em>&lt;&lt;When Large Language Models Meet Personalization: Perspectives of Challenges and Opportunities&gt;&gt;</em></blockquote><p>The paper explores the concept of LLMs in personalization, defining various roles like <strong>system reasoner, knowledge base, content interpreter, explainer, and conversational agent</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*5iQRAbDxGEW1JouD" /><figcaption>image from origin paper</figcaption></figure><p><em>&lt;&lt;Recommender Systems in the Era of Large Language Models (LLMs)&gt;&gt;</em></p><p>Similar ideas as others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*RY9NqnVmKpsRgo-Y" /><figcaption>image from origin paper</figcaption></figure><blockquote><em>&lt;&lt;How Can Recommender Systems Benefit from Large Language Models: A Survey&gt;&gt;</em></blockquote><p>The article further delves into different strategies for integrating LLMs with recommendation systems, categorized into four quadrants:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*7DtlPp46MvUOrUe0" /><figcaption>image from origin paper</figcaption></figure><ol><li>Tuning LLMs, Inference with CRM: Here, smaller language models serve as feature encoders for enhancing semantic representation, with a conventional recommendation model (CRM) making the final recommendations.</li><li>Not Tuning LLMs, Inference without CRM: This approach involves zero-shot learning using models like GPT-2 for predicting user behavior, without any tuning of the LLM.</li><li>Not Tuning LLMs, Inference with CRM: In this method, the semantic representations from the LLM are aligned with a recommendation module, enhancing recommendation performance.</li><li>Tuning LLMs, Inference without CRM: This strategy involves fine-tuning large language models to function as scoring/ranking mechanisms, without the involvement of a CRM.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c235c11ad7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bypassing the V100 : Train LLM on a Single 3060 Card]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@AILearning/bypassing-the-v100-train-llm-on-a-single-3060-card-3165aef506c4?source=rss-60a408e3c0aa------2"><img src="https://cdn-images-1.medium.com/max/1792/0*JqDkYtsilwEqv2J5" width="1792"></a></p><p class="medium-feed-snippet">Introduce the LoRA and quantization methods. Using these two approaches, we can significantly reduce the GPU memory usage of the model.</p><p class="medium-feed-link"><a href="https://medium.com/@AILearning/bypassing-the-v100-train-llm-on-a-single-3060-card-3165aef506c4?source=rss-60a408e3c0aa------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@AILearning/bypassing-the-v100-train-llm-on-a-single-3060-card-3165aef506c4?source=rss-60a408e3c0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/3165aef506c4</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[AILearning]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 03:10:54 GMT</pubDate>
            <atom:updated>2023-11-24T04:40:34.407Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Amidst OpenAI’s turmoil, Claude 2.1 is quietly released.]]></title>
            <link>https://medium.com/@AILearning/amidst-openais-turmoil-claude-2-1-is-quietly-released-6837f5057600?source=rss-60a408e3c0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/6837f5057600</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[AILearning]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 03:38:51 GMT</pubDate>
            <atom:updated>2023-11-22T03:38:51.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*LzpytpfF42XAx1HsNr8X6w@2x.jpeg" /></figure><blockquote>There is no definitive conclusion to the internal strife at OpenAI, yet OpenAI’s old rival Anthropic has quietly updated their model, Claude 2.1, to support a 200k context, surpassing GPT-4 Turbo’s 128k.</blockquote><p>Anthropic recently released their latest model, Claude 2.1, which has the following features:</p><p>1. 200K Token Context Window:</p><p>Claude 2.1 expands the context window to 200,000 tokens, roughly equivalent to 150,000 words or over 500 pages of material. This enables users to upload large technical documents, financial statements, or even lengthy literary works, and utilize Claude for summarization, Q&amp;A, trend prediction, and comparing multiple documents.</p><blockquote>Comparison with GPT-4 Turbo: While GPT-4 Turbo can handle inputs up to 128K tokens, Claude 2.1&#39;s 200K token capacity is significantly larger.</blockquote><p>2. Reduced Rate of Hallucinations: Claude 2.1 has made significant progress in terms of honesty, halving the rate of false statements. This allows businesses to build more efficient AI applications, solve real business problems, and deploy AI more reliably.</p><p>3. Improved Comprehension and Summarization Abilities: Particularly in handling long, complex documents requiring high accuracy, such as legal documents, financial reports, and technical specifications.</p><p>4. Improved Comprehension and Summarization Abilities: Particularly in handling long, complex documents requiring high accuracy, such as legal documents, financial reports, and technical specifications.</p><p>for more detail： https://www.anthropic.com/index/claude-2-1</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6837f5057600" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your own ChatGPT from scratch in Python numpy]]></title>
            <link>https://medium.com/@AILearning/build-your-own-chatgpt-from-scratch-in-python-numpy-9401acd68af5?source=rss-60a408e3c0aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/9401acd68af5</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[AILearning]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 16:41:09 GMT</pubDate>
            <atom:updated>2023-11-18T08:08:47.077Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IV3RA_zMohD0Xb_3" /></figure><p>Generative Pre-trained Transformers, or GPTs, represent a significant leap forward in natural language processing technology. These models, especially notable ones like OpenAI’s GPT-3, are celebrated for producing text that is not only fluent but also contextually aware, marking a new era in our engagement with AI-driven language models. But constructing a GPT model involves what specific processes? We shall explore the intricacies of Transformer technology and outline the steps to assemble a GPT from the ground up using Python and NumPy.</p><p>GPTs are distinguished by their vast network size, with some housing billions of parameters and being honed on wide-ranging datasets. This immense size equips them to handle diverse linguistic tasks, ranging from composing emails to distilling intricate ideas into accessible language.</p><p>In embarking on the journey to craft a GPT model using Python and NumPy, it’s crucial to grasp the architecture’s underlying elements and their synergy, particularly within the sphere of NLP. We will delve into these fundamental concepts and offer an in-depth breakdown of each aspect to forge an exhaustive tutorial.</p><h3>Step 1: Setting Up the Environment</h3><p>First, clone the necessary repository and set up the environment:</p><p><a href="https://github.com/jaymody/picoGPT">GitHub - jaymody/picoGPT: An unnecessarily tiny implementation of GPT-2 in NumPy.</a></p><pre>import numpy as np<br>import sys<br>!git clone https://github.com/jaymody/picoGPT.git<br># Pretrained weights are from https://github.com/jaymody/picoGPT<br>sys.path.append(&#39;./picoGPT&#39;)</pre><h3>Step 2: Defining Basic Functions</h3><p>The building blocks of our GPT are functions like GELU (Gaussian Error Linear Unit), linear layers, softmax, and layer_norm mechanisms:</p><pre><br>def gelu(x):<br>    # GELU activation function applies a non-linear activation to the input &#39;x&#39;<br>    # It&#39;s used to introduce nonlinearity in the model and helps with learning complex patterns<br>    return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) <br>                                  * (x + 0.044715 * x**3)))<br>def linear(x, w, b):<br>    # Linear transformation function that computes the weighted sum of the inputs &#39;x&#39; plus a bias &#39;b&#39;<br>    # &#39;w&#39; are the weights and &#39;b&#39; is the bias term, this is a basic building block of neural networks<br>    return x @ w + b<br><br>def softmax(x):<br>    exp_x = np.exp(x - np.max(x, axis=-1, keepdims=True))<br>    return exp_x / np.sum(exp_x, axis=-1, keepdims=True)<br><br>def ffn(x, c_fc, c_proj):<br>    a = gelu(linear(x, **c_fc))<br>    x = linear(a, **c_proj)<br>    return x<br><br>def layer_norm(x, g, b, eps: float = 1e-5):<br>    # Feedforward network function that applies a GELU activation after a linear transformation<br>    # followed by another linear transformation<br>    # It&#39;s a sequence of operations commonly used in transformers<br>    mean = np.mean(x, axis=-1, keepdims=True)<br>    variance = np.var(x, axis=-1, keepdims=True)<br>    x = (x - mean) / np.sqrt(variance + eps)<br>    return g * x + b</pre><h4>2.1 GELU vs other activefunction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*Dq_3mhxA_zarj0Rb.png" /><figcaption>Figure 2 from the GELU paper</figcaption></figure><p>GPT employs GELU (Gaussian Error Linear Unit) as its activation function due to its superior performance demonstrated in practice. GELU is a relatively new type of activation function introduced by Hendrycks and Gimpel in 2016. It incorporates characteristics of the ReLU (Rectified Linear Unit) and the probability distribution properties of the normal distribution. The specific expression for the GELU function is:</p><p>Some advantages of GELU include:</p><ul><li>Non-saturating: GELU provides non-linear activation, but unlike ReLU, it is not entirely saturated for negative values, which helps with the flow of gradients and reduces the problem of vanishing gradients.</li><li>Smooth Gradients: Due to its smooth nature, GELU can provide continuous gradients, which contributes to stability and performance during the training process.</li><li>Probabilistic Interpretation: Since it emulates the “gating” of input values (i.e., the probabilistic weight of the input value x), it introduces a degree of natural randomness, which can help with regularization of the model and potentially improve its generalization ability.</li><li>Empirical Performance: GELU has shown better performance than other activation functions across various tasks and benchmarks. Particularly in NLP tasks, the combination of GELU with the Transformer model has proven to be highly effective.</li></ul><h4>2.2 Softmax implementation</h4><p>We can observe that there are certain differences between the softmax function’s theoretical formula and its implementation in code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/0*aWC6P4s8Kb58gFpp.png" /></figure><p>Modifications have been made to the softmax computation within the code, primarily to enhance numerical stability.</p><pre>def softmax(x):<br>    exp_x = np.exp(x - np.max(x, axis=-1, keepdims=True))<br>    return exp_x / np.sum(exp_x, axis=-1, keepdims=True)</pre><ul><li><strong>Overflow</strong> and Underflow: <strong>Direct computation of </strong><strong>exp(x_i) can be problematic because the exponentiation can result in very large</strong> numbers for moderate values of x_i (overflow) or very small numbers for large negative values of x_i (underflow), leading to numerical instability. Subtracting the max value np.max(x) from each element in x before exponentiation helps to mitigate this risk because the largest value in the adjusted vector will be 0, which, when exponentiated, equals 1. This subtraction makes the largest of the exp values 1, preventing overflow in the numerator and denominator.</li><li>Numerical Stability: By normalizing the values (shifting the inputs to a smaller range), the softmax function becomes more numerically stable. Without this step, the computation of exp(x_i) for large x_i could result in an infinite value in floating-point arithmetic, which would lead to NaN values during division.</li><li>Efficiency: The use of axis=-1 and keepdims=True allows the function to be applied to multi-dimensional arrays and maintain their shape, which is useful when computing softmax across certain dimensions (like batches of data or different features) in more complex models.</li></ul><h4>2.3 LayerNorm vs BatchNorm</h4><p>Layer Normalization (LayerNorm) and Batch Normalization (BatchNorm) are both techniques used to stabilize and accelerate the training of deep neural networks, but they work in slightly different ways and are used in different contexts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*-sWF7ctMNX5OOE8z.png" /><figcaption>Figure 3 from <a href="https://www.kaggle.com/code/halflingwizard/how-does-layer-normalization-work">https://www.kaggle.com/code/halflingwizard/how-does-layer-normalization-work</a></figcaption></figure><p>Here’s a comparison:</p><p>Batch Normalization (BatchNorm):</p><ul><li>Normalizes the output of a previous activation layer by subtracting the batch mean and dividing by the batch standard deviation (hence the name “batch” normalization).</li><li>The normalization is done over the batch dimension, i.e., for each feature, BN computes the mean and variance over the batch of data.</li><li>It is typically applied to the inputs of the activation function in a layer.</li><li>BatchNorm has parameters (scale and shift) that are learnable during training. It requires a sufficiently large batch size to work well since the statistics are computed over the batch.</li><li>It can lead to significant improvements in convergence for convolutional neural networks (CNNs) and fully connected layers.</li></ul><p>Layer Normalization (LayerNorm):</p><ul><li>Normalizes the inputs across the features instead of the batch. For each data point in the batch, LayerNorm computes the mean and variance used for normalization across the features.</li><li>It is particularly useful in recurrent neural networks (RNNs) and Transformer models, where the batch size can often be one, or the sequence length can vary.</li><li>LayerNorm also has learnable parameters (gain and bias) that can be adjusted during training. Since LayerNorm does not rely on the batch dimension, it behaves consistently during training and inference.</li><li>It has been found to be more effective than BatchNorm in sequence models where the temporal dynamic is important, as it normalizes across the features at each time step.</li></ul><p>In summary, BatchNorm is effective for tasks where the batch size is large and consistent, and it’s commonly used in CNNs. LayerNorm, on the other hand, is more suited to sequence models like RNNs and Transformers because it doesn’t depend on batch statistics and therefore can handle variable sequence lengths and smaller batch sizes.</p><h3>Step 3: Implementing Multi-Head Attention and Feed-Forward Networks</h3><p>Multi-head attention and feed-forward networks are crucial for the model:</p><pre>def attention(q, k, v, mask):<br>    s = q @ k.T<br>    s = s / np.sqrt(q.shape[-1]) + mask<br>    p = softmax(s)<br>    o = p @ v<br>    return o<br><br># Multi-head attention<br>def mha(x, c_attn, c_proj, n_head):<br>    x = linear(x, **c_attn)<br>    qkv = np.split(x, 3, axis=-1)<br>    qkv_heads = list(map(lambda x : np.split(x, n_head, axis=-1), qkv))<br>    <br>    causal_mask = (1 - np.tri(x.shape[0], dtype=x.dtype)) * -1e10<br>    out_heads = [attention(q,k,v, causal_mask) for q, k, v in zip(*qkv_heads)]<br>    x = np.hstack(out_heads)<br>    x = linear(x, **c_proj)<br>    return x</pre><p>The foundation of GPT lies in the Transformer model, a type of deep learning model designed to handle sequential data like text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*hl1m3YYZw1V0VuON.png" /><figcaption>Figure 4 from <a href="https://jalammar.github.io/illustrated-transformer/">https://jalammar.github.io/illustrated-transformer/</a></figcaption></figure><p><strong>Self-attention Mechanism</strong>: This allows the model to weigh the importance of different words in a sentence, providing a dynamic understanding of textual context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*PhSIUdt8Ze8EPPUS.png" /><figcaption>Figure 5 from <a href="https://zhuanlan.zhihu.com/p/365550383">https://zhuanlan.zhihu.com/p/365550383</a></figcaption></figure><p>Imagine you’re reading a complex novel, and in each sentence, some words are more important to the meaning than others. For instance, in the sentence “The cat sat on the mat,” words like “cat” and “mat” are more crucial to understanding the sentence than “the” or “on.” Self-attention in a neural network works similarly. It helps the model to focus more on certain words (or parts of the input) when trying to understand or generate text.</p><p>In essence, self-attention is like a smart, dynamic highlighter that helps AI models determine which words in a sentence are the most important for understanding the meaning and context, much like how we focus on certain words while reading or listening to make sense of the information.</p><p>Here, for each word, we have <em>k</em>, <em>v</em>, <em>q</em>; <em>k</em> and <em>v</em> represent the associations between them. In the self-attention mechanism, “K,” “Q,” and “V” stand for “Key,” “Query,” and “Value,” respectively. These terms come from the field of information retrieval and are used to help the model determine how much attention to give to a given input, such as a word or phrase. Here’s how they work:</p><ul><li>Query: The query represents the current word or item being considered, which can be thought of as a search query looking for other related information.</li><li>Key: The key corresponds to the representation of all other words or items in the database, which can be imagined as index keywords used by the query to find matching items.</li><li>Value: Once a query finds a matching item through a key, the associated value is used to calculate a new representation of the input word or item. The value contains the actual information you want to retain in the output of the attention mechanism.</li></ul><p>In the self-attention mechanism, each input element, such as a word, is transformed into representations of query, key, and value. The model allocates attention scores by calculating the compatibility between the query and all keys, typically done by taking their dot product and then applying the softmax function to ensure that all attention scores add up to 1. These scores are then used to weight the corresponding values, resulting in the final output representation of each input element. This output captures the context information of all elements in the input sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*rtFPE_JBMNGn2ehr.png" /><figcaption>Figure 6from <a href="http://jalammar.github.io/illustrated-transformer/">http://jalammar.github.io/illustrated-transformer/</a></figcaption></figure><p>In fact, matrix operations are used in the implementation:</p><ul><li>Efficiency: Matrix operations can efficiently utilize modern hardware architectures, especially GPUs (Graphics Processing Units) and TPUs (Tensor Processing Units), which are designed for large-scale parallel computations. Converting the calculations of the attention mechanism into matrix operations can significantly speed up training and inference processes.</li><li>Batch Processing: Matrix operations allow us to process multiple data samples simultaneously, known as batch processing. This means that the network can learn from multiple examples at once, making more effective use of computational resources.</li><li>Vectorization: Matrix and vectorized computations reduce the number of necessary iterations, eliminating the need for explicit loops for each operation. This not only simplifies the complexity of writing code but also reduces computation time.</li></ul><h3>Step 4: Building the Transformer Blocks</h3><p>Each transformer block in GPT consists of multi-head attention and feed-forward networks, along with layer normalization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*y3sneSkKk1MKmKPc.png" /><figcaption>Figure 7 from Attention is All You Need Paper (where h is number of heads)</figcaption></figure><pre>def transformer_block(x, mlp, attn, ln_1, ln_2, n_head):<br>    x = x + mha(layer_norm(x, **ln_1), **attn, n_head=n_head)<br>    x = x + ffn(layer_norm(x, **ln_2), **mlp)<br>    return x</pre><h3>Step 5: Assembling the GPT Model</h3><p>Now, we assemble these components to create the GPT model:</p><p>GPT is built upon the Transformer architecture, focusing on the decoder part for text generation.</p><ul><li>Decoder Blocks: These are the building blocks of GPT. Each block includes a self-attention layer followed by a feed-forward neural network.</li><li>Layer Normalization and Skip Connections: These components help in stabilizing the learning process and enabling the training of deep networks.</li></ul><pre>def gpt2(inputs, wte, wpe, blocks, ln_f, n_head):<br>    x = wte[inputs] + wpe[range(len(inputs))]<br>    for block in blocks:<br>        x = transformer_block(x, **block, n_head=n_head)<br>    x = layer_norm(x, **ln_f)<br>    return x @ wte.T</pre><h3>Step 6: Generating Text</h3><p>The process of generating text in GPT involves predicting the next word in a sequence given the previous words.</p><ul><li>Tokenization: The input text is broken into tokens (words or subwords) which are then converted into numerical representations.</li><li>Predictive Modeling: The model predicts the next token based on the previous tokens, using its learned understanding of language patterns.</li></ul><p>To generate text, we use the model to predict the next token in a sequence iteratively:</p><pre>def generate(inputs, params, n_head, n_tokens_to_generate):<br>    from tqdm import tqdm<br>    <br>    for _ in tqdm(range(n_tokens_to_generate), &quot;generating&quot;):<br>        logits = gpt2(inputs, **params, n_head=n_head)<br>        next_id = np.argmax(logits[-1])<br>        inputs.append(int(next_id))<br>    return inputs[len(inputs) - n_tokens_to_generate :]</pre><h3>Step 7: Running the Model</h3><p>Finally, we create a function to run our model with a given prompt:</p><pre>def main(prompt: str, n_tokens_to_generate: int = 40, <br>         model_size: str = &quot;124M&quot;, models_dir: str = &quot;models&quot;):<br>    from utils import load_encoder_hparams_and_params<br>    encoder, hparams, params = load_encoder_hparams_and_params(model_size, models_dir)<br>    input_ids = encoder.encode(prompt)<br>    <br>    assert len(input_ids) + n_tokens_to_generate &lt; hparams[&quot;n_ctx&quot;]<br>    <br>    output_ids = generate(input_ids, params, hparams[&quot;n_head&quot;], n_tokens_to_generate)<br>    <br>    output_text = encoder.decode(output_ids)<br>    return output_text</pre><pre>main(&quot;What is LLM?&quot;)</pre><pre>2023-10-25 22:49:45.842762: I tensorflow/core/platform/cpu_feature_guard.cc:182] This TensorFlow binary is optimized to use available CPU instructions in performance-critical operations.<br>To enable the following instructions: SSE4.1 SSE4.2 AVX AVX2 FMA, in other operations, rebuild TensorFlow with the appropriate compiler flags.<br>Fetching checkpoint: 1.00kb [00:00, 6.07Mb/s]                                                       <br>Fetching encoder.json: 1.04Mb [00:00, 3.13Mb/s]                                                     <br>Fetching hparams.json: 1.00kb [00:00, 4.89Mb/s]                                                     <br>Fetching model.ckpt.data-00000-of-00001: 498Mb [00:22, 22.0Mb/s]                                    <br>Fetching model.ckpt.index: 6.00kb [00:00, 7.37Mb/s]                                                 <br>Fetching model.ckpt.meta: 472kb [00:00, 1.95Mb/s]                                                   <br>Fetching vocab.bpe: 457kb [00:00, 1.90Mb/s]                                                         <br>generating: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████| 40/40 [00:02&lt;00:00, 13.49it/s]<br></pre><p>Now you can find you own GPT works~</p><pre>&#39;\n\nLLM is a programming language that is designed to be used in a variety of applications. It is a programming language that is designed to be used in a variety of applications. It is a&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y6WluI56twDE2E98" /></figure><h3>Conclusions</h3><p>In conclusion, constructing your own Generative Pre-trained Transformer (GPT) from scratch is a challenging yet incredibly rewarding endeavor that underscores the remarkable capabilities of Python and NumPy in the realm of natural language processing. Throughout this article, we have navigated the foundational elements of GPT architecture, from understanding the intricacies of self-attention and position encoding to grappling with the complexities of large-scale model training. The process reveals not just the technicalities of building a state-of-the-art language model but also illuminates the nuances of machine learning workflows and the importance of computational efficiency. Armed with the insights and methodologies discussed, one is well-equipped to embark on the journey of creating a custom GPT model, tailored to unique tasks and capable of pushing the boundaries of what we expect from AI in language understanding and generation. Whether for academic exploration, industry innovation, or personal projects, the knowledge to build a GPT model from scratch in Python using NumPy is a powerful tool in any developer’s arsenal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9401acd68af5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>