<?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 AdMor on Medium]]></title>
        <description><![CDATA[Stories by AdMor on Medium]]></description>
        <link>https://medium.com/@adrien_morvan?source=rss-fe665bcbeb38------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*e3j3CSYpMBciENvIh5Batg.png</url>
            <title>Stories by AdMor on Medium</title>
            <link>https://medium.com/@adrien_morvan?source=rss-fe665bcbeb38------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 28 May 2026 04:55:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adrien_morvan/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[5 golden rules to deliver a successful GenAI application]]></title>
            <link>https://medium.com/@adrien_morvan/5-golden-rules-to-deliver-a-successful-genai-application-11d53e347943?source=rss-fe665bcbeb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/11d53e347943</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[project-management]]></category>
            <dc:creator><![CDATA[AdMor]]></dc:creator>
            <pubDate>Tue, 17 Jun 2025 10:26:40 GMT</pubDate>
            <atom:updated>2025-06-17T10:26:40.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Bn3RmQC0Htl_UL1xSMLYg.jpeg" /><figcaption>Deploying a GenAI app should look like this to you, generated with Flux.schnell</figcaption></figure><p>You can have dozen of years of experience in the Machine Learning industry but GenAI applications are just starting to appear on the market.<br>While building some myself, I discovered some pattern worth mentionning. So here are the 5 golden rules to building great GenAI applications.</p><h4>🎳 1 — Defining what you are trying to solve has never been more important</h4><p>This sentence has always been true in Machine Learning, but the generation space of GenAI makes these models harder to control.<br>Being clear on what you want to achieve allows better performance.</p><blockquote>For a question like : how does the printing press from Gutenberg work ?<br>You can produce a concise answer in 2 lines or a fully detailed guide in 20 pages.<br>And a smarter Claude or GPT won’t solve this question for you</blockquote><p>So you have to be very precise when defining the inputs and outputs of your AI agent-based system, especially for the output. <br>For outputs, the definition needs to be <strong>understandable by a human</strong> so that it can actually be implemented by a LLM.</p><blockquote>Let’s say you work for building the best customer support agent.<br>In your chat, you decide that the agent should be joyful. <br>What exactly does that mean? <br>It could be many things: making jokes, being friendly, including little encouraging phrases for the user, using emoji. <br>Only you and your team can choose the right set of rules</blockquote><p>However, this kind of responsibility isn’t necessarily the one of data scientists or ML engineers. <br>It should fall to domain expert teams, such as product or business teams. <br>The usually know the best what the product experience should be, exactly like traditional product specifications in traditional engineering.</p><p>One thing is different however : <strong>specification of an “intelligent” system is way harder than traditional software engineering and will require you time</strong>.<br>It will probably be an iterative effort while you learn about your problem space.</p><p>Here are some great references to get started or get inspiration for your use case :</p><ul><li>A great introduction <a href="https://youtu.be/mrYn6_6gJuY">video</a> from Galileo : they give 2 examples of evaluation in the coding assistant and generic agents space</li><li>KPIs that you need to define for your GenAI use case : <a href="https://cloud.google.com/transform/gen-ai-kpis-measuring-ai-success-deep-dive">https://cloud.google.com/transform/gen-ai-kpis-measuring-ai-success-deep-dive</a></li><li>An <a href="https://arxiv.org/html/2501.13282v1">example</a> of metrics used to measure the impact of code assistants on the productivity inside a company</li><li>A <a href="https://oulurepo.oulu.fi/bitstream/handle/10024/54087/nbnfioulu-202502111580.pdf;jsessionid=84BBD554ABBC18C204CA04A2BB110F1F?sequence=1">study</a> on the GenAI use cases in the Procurement industry</li><li>The most surprising use case i’ve encountered it the <a href="https://fractal.ai/wp-content/uploads/2024/05/Pepsi-Cheetos-PYO-case-study.pdf">AI optimized Cheetos</a>. Event thought this is not GenAI</li></ul><p>Once you have defined what you want your GenAI product to look like, you can start to have offline metric implementations by your ML team.</p><h4>📏 2 — Make these definitions measurable with dozen of metrics</h4><p>Having metrics for each of the criterias defined above will allow to know if you achieve your mission successfully. <br>By metrics, I mean offline metrics that will be measured on a dataset representative of the problem you are tackling.</p><p>Most probably, you will use tons of LLM as a judge.<br>Why ? Because there is no traditional metric to measure semantic similarity and it is almost as good as a human review.</p><p>There are great ressources out there to learn how to use LLM as a Judge to make the evaluation of your problem</p><ul><li><a href="https://docs.ragas.io/en/stable/">Ragas</a> is a great start : text comparison and rubrics based scoring can be implemented within minutes.</li><li>Google Cloud also provides a <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/models/metrics-templates">great list</a> of LLMaJ metrics off the shelf : verbosity, safety and many more.</li><li>New metrics are also appearing like <a href="https://galileo.ai/blog/blanc-metric-ai">BLANC</a> : it specializes on summary usefulness.</li></ul><p>Let’s take an example</p><blockquote><strong>Use case </strong>: you have a chatbot responding to your users for Customer Support, you’ll define what tone it should use.<br>For instance, for a cordial tone, you might specify:</blockquote><blockquote>&gt; always start with a greeting,</blockquote><blockquote>&gt; address the person by their first name,</blockquote><blockquote>&gt; always thank them at the end of the conversation,</blockquote><blockquote>&gt; be able to handle angry users by showing empathy</blockquote><blockquote>&gt; emoji usage are forbidden</blockquote><blockquote>This initial definition of cordiality, with these five criteria, can then be implemented as a set of “LLM as a judge” tools that can measure these criteria in your agent’s replies.</blockquote><p>The implementation can be simple once you manage to define these measurements.</p><blockquote><strong>Example</strong>: implementation of “Always start with a greeting”<br>Implementation :<a href="https://docs.ragas.io/en/latest/concepts/metrics/available_metrics/general_purpose/#simple-criteria-scoring"> Ragas Rubric</a><br>Rubric levels : <br>0 : the agent does not say hello to the user and answer directly<br>1 : The user says hello but does not add a reassurance element before answering<br>2: The agent says hello and add a sentence of reassurance before answering the question</blockquote><p>With dozens of these implementation, you can now measure if your AI agent does a good job at serving your users.</p><h4>👸 3 — If data is a king, synthethic data is your prince</h4><p>To measure how well your AI agent scores on your freshly defined metrics, you need data. And a lot of it. But if you build a new product, you don’t have any…</p><p>One of the revolutions around GenAI is that you can generate your own dataset — and this is called synthetic data — but it’s still a process that is more or less custom for each project. <br>So you need to find the right way to generate this synthetic data.</p><p>The simplest approach is usually to ask an LLM to generate a line of your dataset, and then reuse the sample to test your AI Agent. <br>It might sound crazy — especially since you can use the same LLM to create the problem and to answer it — but it’s actually great baseline.</p><p>However, once you go further than this basic version, things start to get more complicated. There’s a lot of research being done on these topics right now.</p><ul><li>There are approaches to transform non-GenAI-oriented datasets into, say, conversational datasets : <a href="https://agentclinic.github.io/">AgentClinic</a> transform a QA dataset into a conversational one, <a href="https://github.com/huggingface/yourbench">YourBench</a> allows to generate more of a dataset</li><li>There are other datasets that try to create LLM traces for LLM fine-tuning from datasets not originally meant for that purpose. <a href="https://arxiv.org/abs/2503.10970">TxAgent</a> creates a guided LLM trace to be used to later finetune a LLM for their specific use case.</li></ul><p>On this step, you should spend a lot of time. These different approaches can give your application the edge to be good enough to collect real user data.</p><h4>👨‍⚖ 4 — Get an expert-level rating with your LLM as a Judge</h4><p>Up to here, we assumed our metrics were perfect.<br>This is usually common in traditional ML, there’s nothing to review about the definition of precision or recall. <br>But for LLM as a judge, which are based on a prompt, it’s not always guaranteed that your metric computation will work exactly as you’d like.<br>So it makes sense to look at the alignment between a LLMaJ and a domain expert review.</p><p>Here is a few things that you may need to fix in your LLMaJ implementations :</p><ul><li><strong>Non-deterministic</strong> : 2 runs on the same data can give different grade</li><li><strong>Narcissistic Bias: </strong>LLMs<strong> </strong>may favor the answers generated by themselves.</li><li><strong>More is More: </strong>LLM judges tend to prefer more verbose text over more concise ones.</li><li><strong>Not-so-Fine-Grained Evaluation Scores: </strong>LLMs can be reliable judges when making high-level decisions. However, as the scoring scale becomes more detailed with finer intervals, LLMs are more likely to produce arbitrary scores.</li><li><strong>Position Bias: </strong>When using LLM judges for pairwise comparisons, it may have preferred positions.</li></ul><p>All these elements can make the judge deviate from what a domain expert would have chosen. <br>It can be useful to measure this gap as a sanity check but also to tune this judge as you would for a normal AI agent.</p><p>Once you reach a certain level of correlation between human and LLM, you successfully automated your domain expert and can run robust experiment to improve your AI agent.</p><h4>🚼 5 — Start simple when building your AI agent</h4><p>Everything is prepared to finally improve. your AI agent. <br>The recommendation here is simple: start simple and add components as your evaluation pipeline improves.</p><ul><li>The baseline is generally prompt engineering, using one of the state-of-the-art LLM providers. For example, GPT-4.1 with the right prompt that precisely describes the task to perform is a good baseline.</li><li>Then, you can think about adding a RAG (Retrieval-Augmented Generation), which will provide contextual information depending on the task assigned to the agent.</li><li>From there, you can start moving in a more agentic direction: first, making tool calls based on context, and finally, truly letting the agent perform an undetermined number of tasks.</li></ul><p>I think it is very important to remind that, without good evaluation, no matter how complex your systems are, their value cannot be proven without a dataset and a clear set of metric to measure its quality.</p><p>With a good base on your dataset and metrics, you can unlock automatic optimisation of your prompts and agents with frameworks like <a href="https://dspy.ai/">DSPy</a> or <a href="https://medium.com/optuna/optuna-v5-roadmap-ac7d6935a878">Optuna</a>.</p><h4>🥁 Conclusion</h4><p>For GenAI applications, you need to prepare a lot of steps before any AI agent development.<br>As the field is new, it can be tempting to do a lot of manual tuning without building the right foundations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11d53e347943" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LlamaIndex, better than LangGraph and LangChain ?]]></title>
            <link>https://medium.com/@adrien_morvan/llamaindex-better-than-langgraph-and-langchain-5e0504b355d0?source=rss-fe665bcbeb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e0504b355d0</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llamaindex]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[AdMor]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 09:50:13 GMT</pubDate>
            <atom:updated>2025-01-06T12:34:33.354Z</atom:updated>
            <content:encoded><![CDATA[<h3>LlamaIndex, better than LangGraph and LangChain ?</h3><p>How you could gain time by learning LlamaIndex</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHNhLjRCHL1eZAxGtAkIfg.jpeg" /><figcaption>Point of view : you just built your “simple” LLM application, generated with Flux.schnell</figcaption></figure><h4>1 — Applications with LLM apps will be complex</h4><p>AI is on everyone’s lips, yet it is hard to see many meaningful adoptions of Large Language Models in a product.</p><p>But the potential exists, we count many examples of applications where automating humans is within reach, like customer support, note taking or maybe soon math and code problems [<a href="https://arcprize.org/blog/oai-o3-pub-breakthrough">1</a>].</p><p>For Natural Language Processing use cases, LLMs are also wonderful zero shot models. But their powers come with large challenges in controllability and performance measurement.</p><p>Some LLM agents frameworks offer to control some of that complexity at the cost of learning their abstraction.<br>Langchain and then Langgraph were among the first to offer a framework to code applications based on LLM. <br>In this post, we will focus on LlamaIndex. In my opinion, it offers the same value with a lower degree of complexity.</p><h4>2 — LlamaIndex : more like a toolbox than a framework</h4><p>My major concerns when I learned to use LangGraph were : <br>- You need to learn many custom operators <br>- Poor typing/classing of the data exchanged by the functions<br>- Function oriented processing lacks flexibility</p><p>In order to illustrate this, I will use a complex <a href="https://langchain-ai.github.io/langgraph/tutorials/tnt-llm/tnt-llm/">example</a> from LangGraph tutorials [2]. <br>Why ? Because with complexity, you discover the hidden design choices made for you by the framework.</p><p>😵 You need to learn many custom operators</p><p>Let’s have a look at the following piece of code. <br>It defines a MapReduce processing. You will see how heterogenous the definition can be.</p><pre>summary_llm_chain = (<br>    summary_prompt | ChatAnthropic(model=&quot;claude-3-haiku-20240307&quot;) | StrOutputParser()<br>    # Customize the tracing name for easier organization<br>).with_config(run_name=&quot;GenerateSummary&quot;)<br>summary_chain = summary_llm_chain | parse_summary<br><br># Now combine as a &quot;map&quot; operation in a map-reduce chain<br># Input: state<br># Output: state U summaries<br># Processes docs in parallel<br>def get_content(state: TaxonomyGenerationState):<br>    docs = state[&quot;documents&quot;]<br>    return [{&quot;content&quot;: doc[&quot;content&quot;]} for doc in docs]<br></pre><pre>map_step = RunnablePassthrough.assign(<br>    summaries=get_content<br>    # This effectively creates a &quot;map&quot; operation<br>    # Note you can make this more robust by handling individual errors<br>    | RunnableLambda(func=summary_chain.batch, afunc=summary_chain.abatch)<br>)</pre><pre>map_reduce_chain = map_step | reduce_summaries</pre><p>If you did not get it or did not read it, it is normal. Too many things happen at once.</p><ul><li>There is a <strong>lack of consistency </strong>: <em>summary_llm_chain</em> is build with pipe operators <em>where summary_chain</em> is build with yet another pipe operator <em>summary_llm_chain</em> and <em>parse_summary</em> : why not everything at once ?</li><li>You need <strong>extra operators</strong> to do the map reduce : a custom user-defined function <em>get_content </em>and glue functions from LangGraph <em>RunnablePassthrough </em>and<em> RunnableLambda</em></li></ul><p>So the purely functional approach is not the most adapted to maintain simple pipelines.</p><p>🔏 Poor typing/classing of the data exchanged by the functions</p><p>In LangGraph, the default way to defined state is through a TypedDict. <br>The state is kept during all the steps of a graph.<br>If new entities appear, you need to have them as elements of the State. So not all keys are filled from the start, so you can make mistakes when filling the state at any time.</p><p>Here is another extract illustrating the idea. <br>A state is defined with 3 different attributes but you only see access the document field in the examples.<br>The true format of the minibatches and clusters remains mysterious to the attentive reader.</p><pre>class TaxonomyGenerationState(TypedDict):<br>    # The raw docs; we inject summaries within them in the first step<br>    documents: List[Doc]<br>    # Indices to be concise<br>    minibatches: List[List[int]]<br>    # Candidate Taxonomies (full trajectory)<br>    clusters: Annotated[List[List[dict]], operator.add]<br><br>def get_content(state: TaxonomyGenerationState):<br>    docs = state[&quot;documents&quot;]<br>    return [{&quot;content&quot;: doc[&quot;content&quot;]} for doc in docs]<br><br>def reduce_summaries(combined: dict) -&gt; TaxonomyGenerationState:<br>    summaries = combined[&quot;summaries&quot;]<br>    documents = combined[&quot;documents&quot;]<br>    return {<br>        &quot;documents&quot;: [<br>            {<br>                &quot;id&quot;: doc[&quot;id&quot;],<br>                &quot;content&quot;: doc[&quot;content&quot;],<br>                &quot;summary&quot;: summ_info[&quot;summary&quot;],<br>                &quot;explanation&quot;: summ_info[&quot;explanation&quot;],<br>            }<br>            for doc, summ_info in zip(documents, summaries)<br>        ]<br>    }</pre><p>Please note that the different functions of the graph feed themselves from the state by using keys ! <br>This can be very error prone when you have a long list of processing.</p><p>Note : In Langgraph, you can define custom input and output states, but you need additional effort (<a href="https://langchain-ai.github.io/langgraph/how-tos/input_output_schema/#define-and-use-the-graph">link</a>).</p><p>💀 This flavour of functional programming lacks flexibility</p><p>There are many minor examples that illustrate why the design pattern of LangGraph is not the most ideal.</p><p>&gt; You need to still draw the edges of the graph yourself</p><p>You have to define the functions, the state. <br>But it won’t protect you from linking the function together</p><pre>graph = StateGraph(TaxonomyGenerationState)<br>graph.add_node(&quot;summarize&quot;, map_reduce_chain)<br>graph.add_node(&quot;get_minibatches&quot;, get_minibatches)<br>graph.add_node(&quot;generate_taxonomy&quot;, generate_taxonomy)<br>graph.add_node(&quot;update_taxonomy&quot;, update_taxonomy)<br>graph.add_node(&quot;review_taxonomy&quot;, review_taxonomy)<br>graph.add_edge(&quot;summarize&quot;, &quot;get_minibatches&quot;)<br>graph.add_edge(&quot;get_minibatches&quot;, &quot;generate_taxonomy&quot;)<br>graph.add_edge(&quot;generate_taxonomy&quot;, &quot;update_taxonomy&quot;)</pre><p>&gt; Doing a for loop over a set of samples for a MapReduce pattern</p><p>From the same example of TNT LLM seen before, the for loop is done in a strange manner… with a conditional edge.</p><pre>def should_review(state: TaxonomyGenerationState) -&gt; str:<br>    num_minibatches = len(state[&quot;minibatches&quot;])<br>    num_revisions = len(state[&quot;clusters&quot;])<br>    if num_revisions &lt; num_minibatches:<br>        return &quot;update_taxonomy&quot;<br>    return &quot;review_taxonomy&quot;<br><br>graph.add_conditional_edges(<br>    &quot;update_taxonomy&quot;,<br>    should_review,<br>    # Optional (but required for the diagram to be drawn correctly below)<br>    {&quot;update_taxonomy&quot;: &quot;update_taxonomy&quot;, &quot;review_taxonomy&quot;: &quot;review_taxonomy&quot;},<br>)<br>graph.add_edge(&quot;review_taxonomy&quot;, END)</pre><p>The reason seems to be for graph representation. But this reason alone is a smell that it could happens for more concerning reasons.</p><p>&gt; Unit testing has revealed to be quite complex</p><p>If you want to test one of the chains defined in the articles by calling it, it may be hard to do without reading the code.</p><pre>class TaxonomyGenerationState(TypedDict):<br>    # The raw docs; we inject summaries within them in the first step<br>    documents: List[Doc]<br>    # Indices to be concise<br>    minibatches: List[List[int]]<br>    # Candidate Taxonomies (full trajectory)<br>    clusters: Annotated[List[List[dict]], operator.add]<br><br># update_taxonomy expects a TaxonomyGenerationState<br>rez = update_taxonomy({<br>    &quot;documents&quot;: my_docs, <br>    &quot;minibatches&quot;: ????, <br>    &quot;clusters&quot;: ????}, <br>    configurable)<br># What is the expected format of minibatches and clusters ?</pre><p>What is the format of the dict and the list[list[int]] ? <br>Well, you need to read and run the code to know.</p><blockquote>In conclusion, there are clear drawbacks to use the Langgraph design patterns.<br>But can another challenger do it better ?</blockquote><h4>3 — LlamaIndex workflow : an object oriented programming way of doing LLM apps</h4><p>LlamaIndex is really not that different from LangGraph. <br>Similar operators for LLM, RAG and other usual suspects. But the main way to build your apps is different : with workflows.</p><p>🚼 — Introduction of the Workflow class</p><p>Here is an example :</p><ul><li>An app with 2 steps : starting with StartEvent and finishing with a StopEvent</li><li>A custom JokeEvent defines, in a joint manner, the routing between the steps of your graph and the content of the state.</li></ul><pre>class JokeEvent(Event):<br>    joke: str # This means generate_joke share a str named joke to critique_joke<br><br>class JokeFlow(Workflow):<br>    @step<br>    async def generate_joke(self, ev: StartEvent) -&gt; JokeEvent:<br>        pass<br><br>    @step<br>    async def critique_joke(self, ev: JokeEvent) -&gt; StopEvent:<br>        pass</pre><p>The goal of this example is to show you that you can run your own experiment in 5 minutes rather than 1 hour.<br>But the most important is how it scales to a complex use case like the TNT LLM examples we have seen before.</p><p>👩‍🔬 — A complex use case with LlamaIndex</p><p>We can reproduce the TNT LLM code by learning only a subset of custom concepts :</p><ul><li>Custom events : you define in a joint manner the routing between the steps of your graph and the content of the state</li><li>PromptTemplate : this one is actually shared by all frameworks, but the syntax changes between them</li></ul><pre># If you have defined TAXONOMY_UPDATE_SYSTEM and TAXONOMY_UPDATE_USER as your <br># prompts, you can easily adapt it to the right format<br>tnt_taxonomy_update_template_msgs = [<br>    ChatMessage(<br>        role=MessageRole.SYSTEM,<br>        content=TAXONOMY_UPDATE_SYSTEM,<br>    ),<br>    ChatMessage(role=MessageRole.USER, content=TAXONOMY_UPDATE_USER),<br>]<br><br>tnt_taxo_update_template = ChatPromptTemplate.from_messages(tnt_taxonomy_update_template_msgs)<br>tnt_taxo_update_template</pre><ul><li>Map Reduce : it is composed of 2 functions ctx.send_event and ctx.collect_events to respectively send map requests and collect the results of map requests. Here is an example :</li></ul><pre>class BatchUpdateTaxnomyWorkflow(Workflow):<br>    @step<br>    async def map_dataset(self, ctx: Context, ev: StartEvent) -&gt; MapEvent:<br>        documents = ev[&quot;documents&quot;]<br>        ...<br>        for doc in documents:<br>            ctx.send_event(MapEvent(text=doc))<br><br>    @step<br>    async def reduce_fn(self, ctx: Context, ev: MapDoneEvent) -&gt; StopEvent:<br>        ...<br>        results = ctx.collect_events(ev, [MapDoneEvent] * 5)<br>        ...</pre><p>If you understood these concepts, this is all you need to implement the TNT-LLM paper in LlamaIndex.</p><p>For the curious, you can see the details of the workflow in the appendix section.</p><h4>🔈 — Conlusion</h4><p>The 3 types of concerns met with LangGraph can be mitigated by simples operators in LlamaIndex :</p><p>😵 — You need to learn many custom operators ==&gt; Workflows in LamaIndex<br>🔏 — Poor typing/classing of the data exchanged by the functions ==&gt; extending Events in LamaIndex<br>💀 — Function oriented processing lacks flexibility ==&gt; the MapReduce pattern is a great example, it is quite simple to implement with LlamaIndex</p><blockquote>I see many benefits in the design pattern of LlamaIndex and this is only a scratch of the use cases that can be met.</blockquote><p><strong>So give it a try.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qWOLqtb37sIGdjviafx7w.jpeg" /><figcaption>Generated with flux.schnell</figcaption></figure><h4>Appendix — The TNT LLM code done with LLamaIndex</h4><p>The TNT LLM has 3 steps :</p><ul><li>Summarize all records</li><li>By group of B records, build or update the taxonomy</li><li>Refine the final taxonomy</li></ul><p>We build a workflow to do the first 2 steps.</p><pre>class BatchUpdateTaxnomyWorkflow(Workflow):<br>    @step<br>    async def map_dataset(self, ctx: Context, ev: StartEvent) -&gt; MapEvent:<br>        documents = ev[&quot;documents&quot;]<br>        taxonomy = ev.get(&quot;taxonomy&quot;)<br>        batch_size = len(documents)<br>        _ = await ctx.set(&quot;batch_size&quot;, batch_size)<br>        _ = await ctx.set(&quot;taxonomy&quot;, taxonomy)<br>        for doc in documents:<br>            ctx.send_event(MapEvent(text=doc))<br><br>    @step<br>    async def map_fn(self, ev: MapEvent) -&gt; SummaryEvent:<br>        tnt_prompt = tnt_template.format_messages(<br>            summary_length=20, explanation_length=30, content=ev.text<br>        )<br>        result = llm.chat(tnt_prompt)<br>        return SummaryEvent(summary=result.message.content)<br><br>    @step<br>    async def reduce_fn(self, ctx: Context, ev: SummaryEvent) -&gt; StopEvent:<br>        batch_size = await ctx.get(&quot;batch_size&quot;)<br>        taxonomy = await ctx.get(&quot;taxonomy&quot;)<br>        results = ctx.collect_events(ev, [SummaryEvent] * batch_size)<br>        if results is None:<br>            return None<br>        summary_xml = format_docs([x.summary for x in results])<br>        if taxonomy is None:<br>            prompt = tnt_taxo_template.format_messages(<br>                content=summary_xml,<br>                nb_categories=15,<br>                cluster_name_length=15,<br>                cluster_description_length=30,<br>                explanation_length=30,<br>            )<br>        else:<br>            #taxonomy_xml = format_taxonomy(taxonomy)<br>            prompt = tnt_taxo_template.format_messages(<br>                data_xml=summary_xml,<br>                cluster_table_xml=taxonomy,<br>                nb_categories=15,<br>                cluster_name_length=15,<br>                cluster_description_length=30,<br>                explanation_length=30,<br>            )<br>            <br>        result = llm.chat(prompt)<br>        rez = parse_taxa(result.message.content)<br>        taxo = format_taxonomy(rez[&quot;clusters&quot;])<br>        return StopEvent(result=taxo)</pre><h4>References</h4><p>[<a href="https://arcprize.org/blog/oai-o3-pub-breakthrough">1</a>] — Cholet et al., <a href="https://arcprize.org/blog">ArcPrize 2024</a><br>[2] — LangChain, <a href="https://langchain-ai.github.io/langgraph/tutorials/tnt-llm/tnt-llm/">TNT LLM implementation tutorial</a><br>[3] — LlamaIndex, <a href="https://docs.llamaindex.ai/en/stable/">documentation reference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e0504b355d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AI streamer experiment ]]></title>
            <link>https://medium.com/@adrien_morvan/the-ai-streamer-experiment-6de678a0ed6d?source=rss-fe665bcbeb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/6de678a0ed6d</guid>
            <category><![CDATA[twitch]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[videos]]></category>
            <dc:creator><![CDATA[AdMor]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 12:41:37 GMT</pubDate>
            <atom:updated>2024-10-13T18:11:16.038Z</atom:updated>
            <content:encoded><![CDATA[<p>A story of scaling a Video+LLM AI system to run on Twitch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMtG2FcUIxsU-_Gwonypyw.png" /><figcaption>Jesus as a streamer</figcaption></figure><p>In the past months, I developed AI Jesus, A LLM based system with interacts with the Twitch interface. <br>Its goal is to interact with people chatting in the stream chat by sending video responses of their questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GfSbj1ku2ppROYAKVrDWQ.png" /><figcaption>An example of the app : people ask question on the right and a video response appears after a few seconds of processing</figcaption></figure><p>This experiment was inspired by other examples. In fact, this is not even the first AI Jesus on Twitch.</p><p>In this article, you will have an overview of some AI entertainment systems but also details about how I built the architecture of this AI Jesus.</p><h3>1 — State of the art review</h3><p>The AI live stream idea is not new. Many tests have been run.<br>I’ll present a few I found.</p><h4>⛪ <a href="https://www.twitch.tv/ask_jesus">AskJesus</a></h4><p>This idea was in fact already an existing one. Ask Jesus offer an english speaking avatar answering people in the chat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5M7U8eTtfgFN6u2ZxHZMA.png" /><figcaption>Interesting to observe their claimed server costs : &gt;10k$</figcaption></figure><p>Interestingly, there is actually a complete service behind this demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*xBkag9qO1Xqf-ESKtdMvvg.png" /></figure><p>I believe several channels on twitch use the same backend. There could be a whole economics study of having AI avatar speaking about niche topics on Twitch.</p><h4>👑 <a href="https://www.twitch.tv/clad3815/clip/HumbleDeadBillKAPOW-aij95Ju_g7JWRlF-">AI Melenchon</a></h4><p>Created by Clad3815. This bot based on a french politician used ElevenLabs and GPT4. <br>It made me laugh on several occasions, I looked to understand the prompt used to make the bot actually funny but did not find all the details.</p><p>One thing I guessed is that using the word “sarcastic” in the prompt makes the bot very aggressive against the person asking the question. Thus providing some elements of surprise and fun.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Cv1ukdoH3DtrgG318XLKQ.png" /><figcaption>One of the clip of the now stopped channel : summary of the program of the candidate using slang words</figcaption></figure><h4>❔<a href="https://www.twitch.tv/watchmeforever">Nothing Forever</a></h4><p>A very weird but captivating show.<br>It reproduces exchanges in the Seinfield sitcom but prompts different topics. On top of it, an animated 3D scene makes the video almost like you watch a real sitcom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*geO-JJGjKlHBbCJtXx8W7w.png" /></figure><h4>💬<a href="https://notebooklm.google/"> NotebookLM</a></h4><p>Even big players like Google started to play with this idea of AI generated content.</p><p>NotebookLM can create REALISTIC podcasts from any content. This way more advanced than the previous examples because they simulate a chain of interactions in a way that was hardly covered in the applications on Twitch.</p><h3>2 — Building a AI streamer factory</h3><p>Now that we have seen the world of possible applications, we can enter the details of how to build a simple one. And there is already quite a collections of challenges to face.</p><h4>🏯 — High level Architecture</h4><p>The general idea is simple, we need to transform an input text into a video that answer this input.</p><p>Multiple steps unfold in order to do this :</p><ul><li>Read the chat message from Twitch as soon as it happens</li><li>Request a LLM to generate an answer to this question</li><li>Transform it into an audio with <a href="https://docs.coqui.ai/en/stable/index.html">txt2speech</a></li><li>Use <a href="https://github.com/Rudrabha/Wav2Lip">wav2lip</a> to morph the template video response based on the audio of the response</li><li>Send the video to twitch</li></ul><p>You can see these steps with the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*Iw6V3uA77uKm6VcGBs2CXg.png" /><figcaption>Main steps of the AI streamer : purple means cloud service, blue means local</figcaption></figure><p>It is possible to host most of the models on a local computer in order to reduce costs. Only the LLM part is using OpenAI gpt4o-mini in order to answer rapidly and at a low cost.</p><h4>🎥 — Streaming</h4><p>The largest challenge in this diagram was not using the model that are all off the shelf, but it was to stream the video.</p><p>You have 2 options : do the low level streaming yourself or use a tool with its associated software stack.<br>I fluctuated between one and the other but finally choose to use OBS, an open source tool and to learn how to use it to achieve the desired outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lzL8tXL6exmY4Iui" /><figcaption>OBS — an open-source live video mixing tool</figcaption></figure><p>OBS is pretty popular in the world of streaming. You can create complex scenes with overlays and several signals mixing. But it is not a tool that automates very well.</p><p>a) On the fly video switch 📺</p><p>The first issue was to be able to launch the latest created video. There is no integrated way to do this in OBS. So you need to start doing custom config from the first minute you use it.</p><p>The first option I found was to enable a script that reads all video starting from the most recent and to switch that script with the OBS API thanks to an external watcher script.<br>It looks already convoluted, this is normal, the logic was insane to do such a simple thing. But it worked at first, until I started to industrialize the codebase.</p><p>b) Dockerization 🐳</p><p>The first version of the system used multiple scripts but switching to a docker compose with separate clean containers made everything easier.</p><p>Dockerizing the services in charge of the ML models was relatively ok. <br>They talk to each other through an API and this works simply with Docker compose.</p><p>But for the video streaming service, things were a bit more subtle. <br>OBS is GUI first, so automating the deployment was not officially supported. <br>Luckily, you can reverse engineer how the default config files work and get it to boot your config.<br>The Docker image also needs to have a UI interface, which is usually not the case when building with a base image of Ubuntu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZC_N1jUqpY0xyoo2pb1xw.png" /><figcaption>A virtual desktop container is needed to launch obs with a GUI and all its options</figcaption></figure><p>With this configuration, the setup is still not 100% automated, closer to 90% but this is ok as it allows to control the “going to production” part.</p><h4>🏃 — Performance and cost control</h4><p>Why not run everything on the cloud ? Because 💸</p><ul><li>The service runs 24/7 so if I rent a GPU at 1$/hour, I won’t be able to support this app for long.</li></ul><p>So running most of it locally is mandatory. Luckily, I’ve already invested in the GPU so the worker can work decently at home.</p><p>The other challenges are the following :</p><ul><li>Reliability of the internet connection : with Wifi access, loss of connection seems to happen more often for the Streamer service</li><li>Everything needs to fit on 16Gb of VRAM : usage of a LLM service was the best of all worlds, not extra VRAM usage, good performance and simple upgrade once newer models come out.</li><li>Speed : users expect almost instantaneous response to their question. Telling them on the stream UI that their question is processed helped. Also the wav2lip model performance could be drastically tuned by reducing image quality. It allowed near real time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*gUb-fflzDXK_6jIS5g8YhQ.png" /><figcaption>The amount of VRAM used is relatively low, GPU usage rarely spikes high</figcaption></figure><p>Beyond this, monitoring can also be challenging.</p><ul><li>Token refresh with Twitch was surprisingly difficult to implement. And it can lead to the system not being responsive to the user anymore.</li><li>Access to the virtual desktop can help to see what is actually broadcasted</li><li>Docker compose can display some of the error encountered, but if spread across multiple machines, it will be difficult to diagnose</li></ul><p>Right now, this is the main blocker to reaching a larger scale of operations.</p><h4>🗽 — Scalability &amp; reliability</h4><p>Once the goal became to scale out of a single machine, new elements to the diagram appeared :</p><ul><li>S3 was needed to store the videos between the services</li><li>A message queue was also used to allow inter process communication</li></ul><p>What explains this decomposition :</p><ul><li>Service 1 is the worker node : it does all the <strong>ML processing</strong>. equipped with a strong GPU</li><li>Service 2 is the streaming node : it hosts the <strong>OBS instance</strong>. It should have a GPU but a budget one should be enough.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqTq2CHfe6BifUZb2cVOHQ.png" /><figcaption>New bricks (S3 and message service) are added once decoupling becomes important. Purple is for cloud services, blue for locally hosted.</figcaption></figure><p>a) What benefits does this new architecture bring ? 💚<br>- The workers can scale independently<br>- 1 worker could serve several streaming services if you have multiple AI streamers<br>- The streaming service can benefit from a reliable internet connection. Having it in the cloud can be a good idea.</p><p>b) Remote video handling 📚</p><p>Scalable design impacted a lot how the videos are read.</p><p>If the two main services are shared across different machines, local video sharing is not possible anymore. The files must be hosted on a cloud storage like S3 in order to be shareable.</p><p>From there, you need an additional service responsible for the orchestration of the video files. The <strong>VideoServer</strong> is used to listen to a message queue about new videos and to download them locally for the streaming OBS service.<br>The VideoServer also owns the video display : when should we display old videos and when should we play the latest answer from a user.</p><h3><strong>Final words</strong></h3><p>I love this project, it started very simple and go quite complex on some very basic needs.<br>Scaling at the lowest possible cost is also something I find very enjoyable but that we don’t get to do so often in professional day-to-day life.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6de678a0ed6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Foundational LLM pre-training on your hardware at home ]]></title>
            <link>https://medium.com/@adrien_morvan/foundational-llm-pre-training-on-your-hardware-at-home-0dd4f2175ea5?source=rss-fe665bcbeb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/0dd4f2175ea5</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[dataset]]></category>
            <dc:creator><![CDATA[AdMor]]></dc:creator>
            <pubDate>Sun, 15 Sep 2024 07:38:39 GMT</pubDate>
            <atom:updated>2024-09-15T19:41:42.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Foundational LLM pre-training on your cheap hardware at home 🏡</h3><p>And it won’t cost you that much, I promise</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*Xq-CSRLwndF2ofAH" /><figcaption>What a successful pretraining will look like</figcaption></figure><h4>Motivation</h4><p>Why not play in the big league ? 👨‍🍳<br>Why not pretrain your own LLM on a large text dataset ?<br>So you can give it a silly name like CharlesGPT or FoxTerrier0.75B.</p><p>But it should be cheap. 💸<br>Let’s avoid the thousand $ bill from AWS for our “small” experiment.</p><p>Where should you start ? 😨<br>There are so many papers, models and more.</p><p>In this article, we decipher all of this for you 🤝.</p><p><strong>Outline :</strong></p><ul><li>Exploring the datasets useful for LLM training</li><li>Hardware : what can we <strong>realistically</strong> train with consumer-grade equipment ?</li><li>Optimization : use the latest innovation to get the most compute / $</li></ul><h4>🏋 Large datasets</h4><p>You know what everybody says : “No data = no AI”. <br>So this is a good starting point to know what is feasible or not.</p><p>The AI will be as good as its data. <br>But there is a lot of datasets out there. <br>What do the grown-ups use ? What is the state of art of good text datasets ?</p><p>We answer all these questions next 🤓.</p><p>Some references [<a href="https://github.com/niderhoff/nlp-datasets">1</a>] can be found to list text datasets.</p><ul><li>Common crawl : 500tb, the majority of the open web is there.</li><li>Project gutenbert : few gb 50k books</li><li>Arxiv 270gb</li><li>The pile 800gb <a href="https://pile.eleuther.ai/">https://pile.eleuther.ai/</a> a collection of text composed of several datasets</li><li>Massive text : 10.5 tb, <a href="https://paperswithcode.com/dataset/massivetext">https://paperswithcode.com/dataset/massivetext</a></li><li>Dolma : 3trillion tokens, <a href="https://github.com/allenai/dolma?tab=readme-ov-file,">https://github.com/allenai/dolma?tab=readme-ov-file,</a> 20tb decompressed</li><li>C4 dataset</li><li>Redpajama : 20t</li></ul><p>There is already too much data for out use case. What should we use ? <br>Luckily for us, HuggingFace has explored this question for us with their <a href="https://huggingface.co/spaces/HuggingFaceFW/blogpost-fineweb-v1">FinedWeb</a> dataset.<br>They show that raw text is not the most optimal to train on. <br>Filtered datasets are usually better : more informative text, removal of explicit or racist content.</p><p>Fineweb is a way to reproduce Refineweb the dataset used to train the Falcom LLM.<br>It consists of : 15trillion tokens, 93tb uncompressed, 44tb</p><p>One direction explored with FineWeb is to create an educative subset. The educativeness is aimed to the boost learning of LLMs.</p><p>Finewev edu : 1.5t, 9tb, HuggingFaceFW/fineweb-edu</p><p>For our purpose, we consider fineweb-edu to be the right balance quality x size vs cost.</p><h4>📏 Dataset references</h4><p>What was the set of the datasets for other well known model ?</p><p>GPT2 was trained on <a href="https://huggingface.co/docs/transformers/model_doc/gpt2">40 Gb of text</a><br>GPT3 approximately on <a href="https://en.wikipedia.org/wiki/GPT-3">500T tokens</a> <br>Phi3 was trained on <a href="https://cheatsheet.md/llm-leaderboard/microsoft-phi-3.en">3T tokens</a></p><p>So a great order of magnitude is 1T tokens. Most probably, we will have to go lower because of budget issues.</p><p>Next, we check if this is indeed possible by doing back of the envelop calculations.<br>We use the <a href="https://en.wikipedia.org/wiki/Neural_scaling_law">Chinchilla scaling law</a> to know how much processing power is needed for our big idea.</p><p>The formula is :</p><blockquote>C = 6 * Nb_of_model_params * Dataset_tokens * epochs</blockquote><p>We use :</p><blockquote>Model size = 1B<br>Dataset size = 1T<br>Epoch = 1</blockquote><p>C = 6 * 1e9 * 1 epoch * 1e12</p><blockquote>C = 6e21 FLOPs</blockquote><p>Next part will investigate what is needed to achieve this number hardware wise.</p><p>💾<strong> Hardware needs</strong></p><p>FineWeb Edu is our starting point. For this, we need 9Tb.<br>Luckily it is easy to find 10+Tb drives on the web.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0-vSBOuVfG7_s4Jl0wSOWQ.png" /><figcaption>Used HDD are a gamble but there are the way to be cheap.</figcaption></figure><p>We go for a 12 TB drive to store our dataset and models.</p><p>Now, the GPU choice</p><p>Model pre-training is a processing hungry task. GPU are in high demand. No miracle will be possible budget wise. <br>The GPU selected will be a RTX 4080.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnEVeAC9IhgR0wM0CnVzXQ.png" /><figcaption>According to HuggingFace, this is the right middle ground between being a GPU poor and a GPU rich.</figcaption></figure><p>It has 48 TFLOPS, this information is important to estimate how fast we can go through the dataset.</p><p>Alternatively, we consider the RTX 4060Ti 16Gb, which is a cheaper option. However much larger trade-off would be needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_Xmgf9R7mvprJve0QegFw.png" /><figcaption>Cheaper option, but the FLOPS are 2 times smaller.</figcaption></figure><p>⏰ <strong>Math time : what can we afford to train ?</strong></p><p>So our initial dataset would cost 6e21 FLOPs to train on.<br>We will need to compare it the processing power of our RTX 4080 of <br>4.874 e13 FLOPS.</p><p>Time needed to train = 6.21 e21 / 4.8E13 / 3600 / 24 = <strong>1497.4 days</strong> of compute for 1 epoch.</p><blockquote><strong>Only 4 years of training</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*wtyjXrbkHBAjftjk.gif" /></figure><p>Ok, let’s redesign the size of everything :</p><ul><li>model size = 100M</li><li>dataset = 0.1T</li></ul><p>Training time now becomes 15 days for 1 epoch 🎉🎉🎉<br>This is long but we could stop it earlier if we want to.</p><p>⏰ <strong>Inference based estimation</strong></p><p>There is another way to estimate the training time needed. <br>It would be in an empirical way. Run one batch of data on your network and see how long it takes.</p><p>This <a href="https://rahulschand.github.io/gpu_poor/">reference</a> allows us to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zU8yxLMmQm64_KmeBhqFrg.png" /><figcaption>An alternative to check how much time will be needed for this pretraining.</figcaption></figure><p>We keep the assumptions of the previous computation. We use the GPT2 architecture as a way to approximate the training cost of one iteration.</p><p>We find :</p><blockquote>374.80 ms for 10 batches of 1000 tokens</blockquote><p>It gives <strong>43 days of training for 1 epoch</strong> of this large dataset.</p><p>So the truth is between 15 and 45 days of training.<br>This is a bit long so we might consider shrinking even more the model size.</p><p><strong>👾 8-bit model training</strong></p><p>However in the previous calculation, we don’t take into account the possibility to train using 8-bit precision.</p><p>The capability exist for approximately 2 years and was enabled on Ada-generation GPUs. <br>Instead of training in 16bit, we can use a 8bit precision, enabling more data to be processed using the same hardware.</p><p>The exact speed up numbers provided by Nvidia are unclear. <br>From +20% to +100%, it will really depend on your implementation details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smiDoJbJ7t7tFPanBZwiag.png" /><figcaption>Throughput gained for LLM training, various precision and hardware used, extracted from the Nvidia conference 2023</figcaption></figure><p>By using a raw pytorch implementation of the model, it is straightforward to use nvidia’s <a href="https://github.com/NVIDIA/TransformerEngine">TransformerEngine</a> autocast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ni-kg9NYuKakmbQ0OPthg.png" /><figcaption>Extracted from the Nvidia conference 2023</figcaption></figure><p>I launched a benchmarking script to validate the speedup</p><pre>root@e485ce1a22f2:/workspace/test# python3 min_example.py --dtype bf16 --depth 4<br>Mean time 253.556015625 ms per iteration (8911.3125 GB used)<br>root@e485ce1a22f2:/workspace/test# python3 min_example.py --dtype fp8 --depth 4<br>Mean time 191.7706640625 ms per iteration (9891.125 GB used)<br>root@e485ce1a22f2:/workspace/test# python3 min_example.py --dtype fp8 --depth 2<br>Mean time 93.829794921875 ms per iteration (5879.4375 GB used)<br>root@e485ce1a22f2:/workspace/test# python3 min_example.py --dtype bf16 --depth 2<br>Mean time 117.90201171875 ms per iteration (5059.3125 GB used)</pre><p>There between 25 to 33% speed for an additional 1gb of space used.<br>So we can expect to reach a training time from 10 to 30 days instead.</p><h4>🌜Conclusion</h4><p>Even tough it is a difficult task to train a LLM at home, it is doable.</p><p>In fact, similar sized experiments have been tested by HuggingFace with their <a href="https://huggingface.co/blog/smollm">SmolLM</a> models (but on the cloud).</p><p>In the next post, we will implement the configuration from this post and report on the results.</p><p>📗 <strong>References</strong></p><p>Nvidia transformer engine : <a href="https://github.com/NVIDIA/TransformerEngine">https://github.com/NVIDIA/TransformerEngine</a></p><h4>💎 Bonus</h4><p>&gt;&gt; How can I find a HDD at the right price ?</p><p>If you buy a brand new HDD, it could be very expensive. By using used HDD, you can greatly reduce the acquisition cost.<br>A good price is 10e / To.</p><p>Where should you go :<br>- Ebay : they may be the cheapeast.<br>- Amazon also works, you could get a better level of guarantee there</p><p>&gt;&gt; Faulty hdd</p><p>For the price listed above, you will have used HDD. It means that they can fail or die on the way to your place.</p><p>Be careful of these tricks used by reseller : <br>- 0-hour usage : it is usually not true. <br>- Disk dead at arrival. Transportation can break some HDD. Don’t be surprised. This is why having a guarantee is important.</p><p>With these few tricks, you should be able to find the right piece of hardware for your need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0dd4f2175ea5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KDD 2024 part 2 : How hard ML problems are framed in different industries]]></title>
            <link>https://medium.com/@adrien_morvan/kdd-2024-highlights-part-2-how-hard-ml-problems-are-framed-in-different-industries-1161af20eb26?source=rss-fe665bcbeb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/1161af20eb26</guid>
            <category><![CDATA[kdd]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[AdMor]]></dc:creator>
            <pubDate>Sun, 08 Sep 2024 15:22:41 GMT</pubDate>
            <atom:updated>2024-09-09T06:24:45.258Z</atom:updated>
            <content:encoded><![CDATA[<h3>KDD 2024 part 2 : How hard product and business problems are framed using machine learning in different tech industries</h3><p>KDD is one of the largest conference for AI and Machine learning in the world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Bsl3IfpKbbyoyh9V.jpeg" /></figure><p>I published a <a href="https://medium.com/@adrien_morvan/kdd-2024-an-overview-of-the-emerging-ai-landscape-4452847d4d28">first post on trends seen at KDD</a>, this second posts will be centered around what I learned about how major ML centered businesses are understanding their main problem and how they solve it using applied math methods.</p><p>What you will see in this post :</p><ul><li>Autonomous agents according to Boeing AI Chief Technologist</li><li>Equilibrium in a 3-sided marketplace with Glovo</li><li>SOON : Why finding something on a map is different by Airbnb</li></ul><h4>1 — Building end-to-end decision &amp; autonomous systems</h4><p>This was an invited talk with Dragos Margineantu, AI chief technologist @ Boeing.<br>He summarized his presentation as “What i learned building end-to-end decision &amp; autonomous systems”</p><p><strong>1-a) High level overview</strong></p><p>An autonomous system will perform tasks that require a high level of reasoning. <br>Dragos presented in this talk a generic design for this kind of AI. This first diagram summarizes it.<br>But the focus for Boeing is to build an autonomous plane which is challenging in today’s standards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8G3bk6ds8ErfK6at3hlFUg.jpeg" /></figure><p>The controller is the main piece of software. I has to do : <br>- High level decision : go to the bakery store<br>- Low level decision : turn right or wait</p><p>To do so, it used an internal list of rules (knowledge base) but most importantly a perception engine (computer vision for exemple).</p><p>A more concrete example of the perception engine is shared for the case of image processing : <br>The use case is an autonomous car or plane case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A88wL_58h2JkCZ3bmkfWWA.jpeg" /><figcaption>Autonomous systems are complex : the perception part is already composed of many pieces</figcaption></figure><p>🖼 — There are multiple levels of complexity to acknowledge : <br> Multiples modalities : different cameras on the plane, lidar<br>👫 — Redundancy : In the object detection box, you can see that several detectors are presented. It is a core aspect of these decision systems, failure will happen for sure, redundancy is not a luxury anymore.<br>🗼— 3 levels of abstraction before reasoning : raw processing (segmentation), concepts extraction (object detection), spatio temporal reasoning (tracking). The tracker output is the basis of high order reasoning.</p><p><strong>1-b) Challenges of these systems</strong></p><p><em>i — Robustness</em></p><blockquote>Learn to say “I don’t know”</blockquote><p>All the AI systems making decisions should have 2 outputs : <br>- value<br>- uncertainty</p><p>This approach is particularly relevant because you have an ensemble of models and not all models may fail at the same time.</p><blockquote>“You don’t understand it if you understand it in 1 way”</blockquote><p>There is a large direction of work in engineering redundancy.</p><p>Example : <br>They created “synthetic” data in places where they have little data.<br>They faked an incursion on the airport</p><p><em>ii — Trust</em></p><p>What took them a lot of time is to comply to the human expected actions or decision.<br>Example given : the avoidance maneuver. The AI would direct the plane to go in the direction of another plan to go beyond it, scaring the pilots at first.</p><p>This direction is very close to the known subject of explainable AI</p><p><em>iii — Anticipation</em></p><p>This topic was less detail but you can understand why it is really relevant here.<br>The high level reasoning module needs to make assumptions on the future.<br>For autonomous plane, maybe you can’t investigate directly to get more information. But for other autonomous system, it could make sense.</p><p>Their goal is : <br>Time series prediction ===&gt; trajectory prediction</p><p>They published a paper on this topic : Generative methods for anticipating unknowns : normalizing flows</p><p><strong>1-c) My take-aways</strong></p><p>You want to build an intelligent AI assistant. You might end up using the following architecture principles in the future. <br><em>Why</em> ? <br>Making your system more robust to edge cases and abuses will bring values to your customer, especially if the core technology like GPT-4 is commoditized.</p><h4>2 — <strong>How do Uber, Deliveroo and Glovo are framing their business ?</strong></h4><p>Introduced by Glovo during the TSMO workshop on 2-sided marketplace : Simulation based Mixed Integer Linear Programming (MILP)</p><p><strong>2-a) The use case</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVHSQcuJPWthdST3ZGgyPw.jpeg" /><figcaption>P1 is the order to deliver and D1 is its destination. The left rider is still working on D0 delivery.</figcaption></figure><p>Give 2 potential drivers, who should take order P1 ?</p><ul><li>Right rider who is available but further.</li><li>or left rider who is already on an order, but once finished, will be closer to P1</li></ul><p>This problem can be solved as an optimization under constraints.</p><p><strong>2-a) The equation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRoHME2wcljBy7Y-kFJXjw.jpeg" /></figure><blockquote>How to understand the equation : <br>x = assignment<br>yo = order is assigned or not<br>fo = the cost of not assigning an order (cost of delay) ==&gt; trick by creating a driver that is very far<br><em>c_ro</em> = is the quality times revenue of the order</blockquote><p>The term C is the core of the system, Glovo defines it with the folowing terms : <br>- cro = α0 · riderDistanceRo + α1 · riderDTRo + α2 · customerDTRo</p><p>🏃 — RiderDistanceRo = Estimated distance traveled by the rider.</p><p>🚴‍ — riderDTro = Estimated time the rider r will spend delivering<br>the order o. This term is used for controlling the quality of<br>our service at peak times, when the number of orders can<br>be considerable higher than the number of riders available.<br>🌯 — customerDTRo = Estimated delivery time of order o if it is<br>assigned to rider r, that is, the elapsed time since the order<br>is created until the order is delivered.</p><p><strong>How do you improve the business ?</strong></p><ul><li>Finding the right alpha : the look for a reduction in delivery time with a limited driver distance increase (eg: &lt;10%)</li><li>They use a simulator to estimate the probable values per city</li><li>Hypothesis testing is done by switch-back testing across different sections of the day in multiple cities.</li></ul><p><strong>2-c) My take-aways</strong></p><p>To me, learning to recognize this class of problem and what tool can be used to solve it is an underrated skill. <br>It has been shadowed by more trendy topics like Deep learning.<br>For a company like Glovo, this Data science are a matter of life and death for the health of the business.<br>It might be worth for you as a readerto wonder if it can be applied in your case.</p><h4>3 — How to display your results on a map with Airbnb</h4><p>Soon</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1161af20eb26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KDD 2024 — An overview of the emerging AI landscape]]></title>
            <link>https://medium.com/@adrien_morvan/kdd-2024-an-overview-of-the-emerging-ai-landscape-4452847d4d28?source=rss-fe665bcbeb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/4452847d4d28</guid>
            <category><![CDATA[kdd2024]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kdd]]></category>
            <dc:creator><![CDATA[AdMor]]></dc:creator>
            <pubDate>Sun, 25 Aug 2024 19:14:05 GMT</pubDate>
            <atom:updated>2024-08-28T13:24:50.722Z</atom:updated>
            <content:encoded><![CDATA[<h3>KDD 2024 — Highlights of the emerging AI landscape</h3><p>The place to explore the latest technical reports and new application fields</p><p>The KDD conference is known to be more applied compared to other A tier ML conferences.<br>For this reason, it is a great place to go to catchup on the latest technical trends but also discover emerging new topics.</p><p>In this post, I’ll present the top ideas that interested, surprised or at least felt novel to me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6uMZEBtm5MiGWO79QXNiBA.jpeg" /><figcaption>So glad to be there :)</figcaption></figure><h4>📝 — Detecting the AI pen</h4><p>This workshop was about <strong>detecting text generated by AI</strong>. <br>It can have many different motivation but a major one is that AI can create more easily misinformation that we want to prevent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WanFTPBDiEXuV6INla44uA.jpeg" /><figcaption>The 5 main classes for AI-text detection : classes are not exclusive</figcaption></figure><p>The main take-aways :</p><ul><li>Soft watermarks may be the most efficient to detect AI writing. Zero shot would be second.</li><li>But you need long chunks of text. With short ones, even human can be detected as AI.</li></ul><p>Some examples</p><p>Zero-shot detection — Detect GPT</p><p>We can do a lot based on the distribution of the text generated. Usually <strong>human don’t produce text with the highest probability</strong> and variations of their text has also different properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJIn44WbORKB42A0sMT1ZQ.jpeg" /><figcaption>x_fake generated by AI has specific properties when rephrased compared to x_real. This is the basis of many approaches.</figcaption></figure><p>Soft Watermark — The green / red algorithm [<a href="https://openreview.net/pdf?id=SsmT8aO45L">ref</a>]</p><ul><li>Split all words in 2 groups, there should be a green synonyms of red words. Red words can represent less than 50% of all words.</li><li>LLM inference will use more red words in order to be flagable.</li><li>Detection is done on the probability to have words only in 1 of the 2 sets</li><li>hypothesis testing is used to detect if a set of text with a lot of red words is AI</li></ul><p>There can be different green-red lists that give better results</p><p>Why is it called “soft” ? <br>It is not always possible to green/red everything like the word “Obama”, as it has no synonym. <br>Efficiency is only reached on longer texts. In that scenario, it starts to be very hard for attacked to remove all traces of AI-ness.</p><h4>🕴 — AI impact on the job market, talent management and recruiting</h4><p>This workshop explore how new AI capabilities could shift the global job market. The topics discussed were in fact very wide.</p><p>&gt;&gt; Human learning direction</p><p>The first lecture from Professor Hui Xiong highlighted that an area of knowledge worker could quickly have a much lower added value : <strong>the describable knowledge</strong>.</p><p>Not describable knowledge is easier to illustrate than the opposite. People management was the first illustration given.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udCtVXO2mX_B1Vx84GuUug.jpeg" /><figcaption>Describable knowledge is where AI could shine in the next years</figcaption></figure><p>Some use cases for application to the job market were interesting to think about (coming from “A compreghensive survey of Artificial Intelligence Techniques for Talent Analytics”)</p><ul><li>Describe your curriculum and the LLM generate a CV</li><li>Given your CV, generate a job description and find the closest matched job THEN find the key skill that you need to learn</li><li>Mutli-modal LLMs could bring a simple structuration of all CV formats</li></ul><p>&gt;&gt; LLM as novice qualitative research assistant, a talk from Talent management research from Amazon</p><p>Talent management research is the usage of science and data to equip employees with resource to best navigate their career.<br>Talent management works on either core research (what does promotion / good employee / etc looks like), product development or metrics and evaluation.</p><p>Their base material is an interview dataset. They don’t reveal their internal dataset but used a public one composed of 8 transcripts of 1 hour interview.<br>A RAG based model achieves close to human performance.</p><p>The key takeaway is especially that they consider the level of the RAG LLM at the level of a junior qualitative researcher.<br>But more realistically, the tool will mainly boost the work of the human more than replacing it. They mentioned the lack of replacement for bias and deduction from LLM.</p><h4>🏭 — Preprocessing large multimodal dataset</h4><p>Another great overview of the first day of this conference is the discovery of the <a href="https://github.com/modelscope/data-juicer">data-juicer</a> package.</p><p>It is aimed at preprocessing very large amount of multimodal data for LLM training. The maintainer explained the key differences that pushed them to develop a tool different than say Spark :</p><ul><li>A model is an operator like any other one</li><li>The Data is AI-native, meaning it is intended for AI primarily. An example could be filtering partially a video</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7SLL7tIc_LvE-Qru1nd_Hw.png" /><figcaption>An example of using GPT3-based score to apply a filter on data from Common Crawl</figcaption></figure><p>I recommend to read the excellent <a href="https://huggingface.co/spaces/HuggingFaceFW/blogpost-fineweb-v1">blog post</a> from HuggingFace on how they build the FineWeb dataset. Many of the custom operator mentioned in their post are present in DataJuicer.<br>The scale and cost of the pre-processing seems new to me as they were maybe more limited to text for the majority of companies.</p><h4>💡 — Conclusion</h4><p>This first day was great in discoveries. <br>I would recommend to attend multiple different session as you can often make random discoveries on topics that you know nothing about.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4452847d4d28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 docker best practices to muscle up your game]]></title>
            <link>https://medium.com/@adrien_morvan/3-docker-best-practices-to-muscle-up-your-game-45663b8e2d94?source=rss-fe665bcbeb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/45663b8e2d94</guid>
            <dc:creator><![CDATA[AdMor]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 20:04:25 GMT</pubDate>
            <atom:updated>2024-08-08T20:04:25.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JwzDvm-kbsLXBmkz.png" /></figure><p>Not so long ago, I realised something disturbing.</p><p>I knew many best practices in different domains : python, how to train a good model, how to save money on the cloud.</p><p>But for Docker, things were not so clear. That was a clear indicator that I should probably learn a lot more about it.</p><p>After a few discussions and reading on the topic, I collected a small set of resources that should help everyone feel more confident that they use Docker properly</p><h3>The essentials of Docker</h3><p>This part is an intro for the best practices.<br>Without it, the article could feel incomplete and frustrating if you did not spend enough time on Docker.</p><h4>Docker in a nutshell</h4><p>Docker is a platform for containerization that had a transformative impact in the software world. Docker enables the packaging of applications and their dependencies into portable containers, which can run <strong>consistently</strong> across diverse computing environments.</p><p>Docker also simplifies application management, accelerates deployment, and optimizes resource utilization by sharing the host operating system’s kernel.</p><h4>Why Docker ?</h4><p>Docker started to be used around 2013 and became a key skill to have in the tech industry. However, this does not tell a lot on the “why” it became popular.</p><p>Docker gained widespread adoption because it provided a better alternative than other option at the time. Let’s see it in details :</p><ul><li>Lighter than Virtual Machines:</li><li>Virtualization technologies, such as VMware and VirtualBox, were commonly used. VMs provide full virtualization of an entire operating system, allowing multiple applications with their dependencies to run on a single physical server. While effective, VMs are heavier than containers in terms of resource usage, and the startup time is typically slower.</li><li>Simpler than traditional configuration management tools:</li><li>Tools like Puppet, Chef, and Ansible were used for automating the configuration of servers and ensuring consistency across different environments. These tools focused on managing the software configuration on servers but didn’t provide the same level of isolation and portability as containers.</li><li>More automated deployment:</li><li>In many cases, deployment involved manual steps, where developers or system administrators configured servers and installed dependencies manually. This manual process often led to inconsistencies between development, testing, and production environments.</li></ul><h4>Docker 101</h4><p>We have seen why Docker has become widespread, but not how to use it.</p><p>However, there are countless tutorials on Docker <a href="https://training.play-with-docker.com/">1</a> <a href="https://www.geeksforgeeks.org/docker-tutorial/">2</a>, so I won’t create a new one.</p><p>But for illustration purpose, here is what you can expect to see in Dockerfile. It will be useful when we will review the best practices.</p><pre># Use an official Python runtime as a base image<br>FROM python:3.9<br># Set the working directory in the container<br>WORKDIR /usr/src/app<br># Copy the application source code to the working directory<br>COPY . .<br># Install app dependencies<br>RUN pip install -r requirements.txt<br># Define the command to run the application<br>CMD [&quot;python&quot;, &quot;app.py&quot;]<br></pre><p>In a nutshell :</p><ul><li>We start with a python:3.9 image</li><li>Create a directory in the system /usr/src/app that will be used for the next operations</li><li>The COPY command will copy all the current directory into the container</li><li>We proceed to dependencies installs</li><li>The default command when the container will run will be python app.py</li></ul><h3>Docker best practices</h3><p>In the previous section, we have seen why Docker is useful. Now the question is how does it work exactly and how can I make it run more efficiently.</p><h4>1 — Avoid unnecessary build time</h4><p>You can increase the speed of consequent build by optimizing the order of the operations.</p><p>Let’s see an example of the consequences of an unoptimized Docker file (like the one of the previous section)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*nNyt6rBHDtTrvzt7.png" /></figure><p>In this example, a COPY . . is done early in the build. Hence, after any modification of a file in the project, the build process will restart from the COPY and redo a potentially unnecessary install of the dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*vxb74Pvi3mFJJHM3.png" /></figure><p>On the other hand, if only the requirements file is copied, one can skip the requirements install if no dependency changed.</p><h4>2 — Multiple stage</h4><p>Stages allow to build your Docker image in separate parts, usually into a builder and a runtime image.</p><p>Let’s see an example.</p><pre># Stage 1: Build Stage<br>FROM python:3.8 AS builder<br><br>WORKDIR /app<br># Copy only the dependency files to leverage Docker cache<br>COPY pyproject.toml poetry.lock .<br># Install build dependencies<br>RUN pip install --upgrade pip poetry &amp;&amp; \<br>    poetry config virtualenvs.create false &amp;&amp; \<br>    poetry install --no-interaction --no-ansi<br># Stage 2: Server Stage<br>FROM python:3.8-slim as server<br>WORKDIR /app<br># Copy installed dependencies from the builder stage<br>COPY --from=builder /usr/local/lib/python3.8/site-packages/ /usr/local/lib/python3.8/site-packages/<br># Copy the rest of the application code<br>COPY . .<br># Command to run your application<br>CMD [&quot;python&quot;, &quot;app.py&quot;]<br># Stage 3: Worker Stage<br>FROM python:3.8-slim as worker<br>WORKDIR /app<br># Copy installed dependencies from the builder stage<br>COPY --from=builder /usr/local/lib/python3.8/site-packages/ /usr/local/lib/python3.8/site-packages/<br># Copy the rest of the application code<br>COPY . .<br># Command to run your application<br>CMD [&quot;python&quot;, &quot;worker.py&quot;]<br></pre><p>What are the benefits ?</p><ul><li>No need to rebuild the builder stage if the dependencies stay the same</li><li>You can build with a full python image and only keep a slim image for runtime, gaining 300Mb of space</li><li>You can use the same set of dependencies once for 2 different runtimes : a server and a worker</li></ul><h4>3 — Add a baked-in healthcheck to your web app</h4><p>You can add a health check to your images.</p><p>Why ? When your app depends on other services, you can know in real-time when things go wrong.</p><p>How to implement it ?</p><pre>FROM nginx:latest<br>HEALTHCHECK CMD curl --fail http://localhost/api/healthcheck || exit 1<br></pre><p>This can also be implemented in a docker compose file, where it makes more sense from a system perspective.</p><pre>version: &#39;3&#39;<br>services:<br>  web:<br>    image: nginx:alpine<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;wget&quot;, &quot;-qO-&quot;, &quot;http://localhost/&quot;]<br>      interval: 30s<br>      timeout: 3s<br>      retries: 3</pre><h3>Conclusion</h3><p>I hope these tips will support you in building more efficient Docker apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45663b8e2d94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dora vs Lora : the new solution to finetune LLMs]]></title>
            <link>https://medium.com/@adrien_morvan/dora-vs-lora-the-new-solution-to-finetune-llms-ed11142bf19b?source=rss-fe665bcbeb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed11142bf19b</guid>
            <category><![CDATA[dora]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[AdMor]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 13:33:17 GMT</pubDate>
            <atom:updated>2024-06-30T13:33:17.921Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dora vs Lora : the new solution to finetune LLMs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TzvOntmoQ-KYG5CCB_vmPg.jpeg" /><figcaption>A new challenger enters the race !</figcaption></figure><h4>💁 — Do you know Dora?</h4><p>It’s the new replacement for Lora!</p><p>Lora stands for Low rank adapter, LLM’s ultra-popular finetuning method thanks to its efficiency.<br>Dora, which stands for Weight decomposed low rank adaptation, is said to be better in term of quality and just as effective as Lora.</p><p>Nvidia recently highlighted this method in <a href="https://developer.nvidia.com/blog/introducing-dora-a-high-performing-alternative-to-lora-for-fine-tuning/?utm_source=pocket_shared">one of its posts</a>.<br>- It compares Dora and Lora on NLP and vision tasks<br>- Dora sometimes wins with very high margins<br>- This prompted Nvidia to include this method in their toolkits (Nemo and others).</p><p>So it might be the tool of the future to learn right now, right ?</p><h4>🥇 — Why is it better?</h4><p>Dora does not offer more freedom to tune models, but less. <br>So why does it work ?</p><p>Reminder about Lora:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jw9zD_3JCSVwI4D0" /><figcaption>Credit to lightning.ai — Common formulation of the finetuning problem, efficiently learn the DW</figcaption></figure><p>- We learn a weight increment dW relative to the main model W.<br>- This weight is learned using low-rank matrices to improve learning speed. dW = AB<br>- For transformers, it is often accepted that only the attention of the model should be tuned.<br>- The lower the rank, the faster and more efficient the learning will be than a complete finetuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*eQuUXVT6XtajD7r2.png" /><figcaption>Caption from the Dora paper : the decomposition of dW into magnitude and direction is visible.</figcaption></figure><p>For dora : <br>- dW is simplified, with only the direction of the vector being modified granularly <br>- The amplitude of the vector will be a multiplier with a lower dimensionality<br>- So there’s a smaller solution space, which may explain why convergence is more efficient.</p><h4>🙋 — Ok I want to use it</h4><p>It’s already available in HuggingFace’s diffuser lib:</p><p>Use the : — use_dora<br><a href="https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/README_sdxl.md?utm_source=pocket_reader#dora-training">https://github.com/huggingface/diffusers/blob/main/examples/dreambooth/README_sdxl.md?utm_source=pocket_reader#dora-training</a></p><p>You can find some example on the model space of HuggingFace and twitter :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iUwQgbeFP9N29sbM" /><figcaption>Ref : <a href="https://x.com/linoy_tsaban/status/1760713331227381950?utm_source=pocket_saves">https://x.com/linoy_tsaban/status/1760713331227381950</a></figcaption></figure><p><a href="https://huggingface.co/linoyts/huggy_dora_edm_v4_pivotal?utm_source=pocket_shared">Example</a> of model</p><p>Overall, the method lacks a wide adoption as of today.</p><p>But it is supported in the main txt-2-image framework, which shows that some precursors are preferring it over other finetuning methods.<br>You can find it in the <a href="https://github.com/AUTOMATIC1111/stable-diffusion-webui/releases?utm_source=pocket_saves">1.9.0 version of the sd-webui</a>.</p><h4>🤔 - I have a sudden doubt, why does it work so well?</h4><p>There has been many attempts to improve over Lora, so why is this one the best ?</p><p>&gt; In the paper, we show the performance gain as a function of rank r.<br>The biggest gain in Dora vs Lora occurs at low r ranks (&lt;= 8).<br>This is understandable: <br>- Fewer parameters: In the low ranks, Lora lacks the parameters to represent well. In comparison, Dora concentrates on direction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1S-r3s-tM5GjLFXnQjkjA.png" /><figcaption>Llama 7B perf improvement with dora vs lora : (caption from the paper)</figcaption></figure><p>&gt; A different correlation between magnitude and direction.<br>Lora does not necessarily learn perfectly.<br>Direction and magnitude are correlated but do not have the same correlation profile as in full finetuning.<br>This implies a certain sub-optimality which motivated this research direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KQ7dxNnZMYiVPy5c_qyjg.png" /><figcaption>The correlation of magnitude M and direction D is truer to the original distribution with Dora (caption from the paper)</figcaption></figure><h4>💯 — Conclusion</h4><p>If Nvidia starts to include a given technic in its frameworks, it is usually a good time to have a look at it.</p><p>As it can work for both text and image, you won’t waste your time testing it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed11142bf19b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do you still do your diagrams yourself in the AI era ?]]></title>
            <link>https://medium.com/@adrien_morvan/do-you-still-do-your-diagrams-yourself-in-the-ai-era-7f983e03ca25?source=rss-fe665bcbeb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f983e03ca25</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[productivity]]></category>
            <dc:creator><![CDATA[AdMor]]></dc:creator>
            <pubDate>Sun, 09 Jun 2024 13:02:47 GMT</pubDate>
            <atom:updated>2024-06-10T06:42:24.368Z</atom:updated>
            <content:encoded><![CDATA[<h3>Still doing your diagrams yourself in the AI era ?!?</h3><p>Free productivity for you with these new tools.</p><h4>🖼 — An image is worth a thousand words</h4><p>Not very original, but very true when you write complex reports.<br>I find it true for diagrams especially : try to explain the following tree in words, your reader will have a hard time figuring it out despite the simplicity of the content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*G2duC8Z9q3s_2rTw8J_Ffw.jpeg" /><figcaption>I took 5 seconds to draw it. How much more would it be on an online tool ?</figcaption></figure><p>But diagrams are slow to build programmatically (using a UI or not).<br>I often use draw.io which is simple and get the job done. <br>But you need to have finished your design first, it is usually as complex to update than to create.</p><p>In the tree before, if D and E are finally attached to B rather than C, I can redraw it quickly. On a digram software, it could be more complex to update it.</p><h4>📝 — The speed of the paper, the slickness of the machine</h4><p>Could we get the best of both world ?</p><p><strong>YES</strong></p><p>I came across this wonderful open source demo : <a href="https://huggingface.co/spaces/nllg/DeTikZify">DeTikzify</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5CYqzSeIwCw-GqeFs3si7w.png" /></figure><p>It accepts many types of input : doodles from a canvas but also pictures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZDqjYQxHZWipWOcyMdkyA.png" /><figcaption>It works out of the box for this simple use case</figcaption></figure><p>It started simple but it went very deep</p><h4>⚙️ — TLDR : how does it work ?</h4><p>They collected <a href="https://github.com/potamides/DaTikZ">many diagrams</a> from Arxiv to build their training set.</p><p>They use a <a href="https://llava-vl.github.io/">LLava</a>-based model to do the image/text embedding and code generation.</p><p>They use <a href="https://arxiv.org/abs/2402.08147">VerMCTS</a> to make sure the code compiles.</p><h4>🤔 — So could we do more ?</h4><p>These authors also produced <a href="https://huggingface.co/spaces/nllg/AutomaTikZ">AutomaTikz</a>.</p><p>The idea is to create a prompt that will build a template of diagram that you could update later on.</p><p>In the following example, you could imagine how much you would need if you wanted to do manually this simple perceptron diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8V88UulhzkRqaGAbob_bfg.png" /><figcaption>Prompt: Visual representation of a multi-layer perceptron: an interconnected network of nodes, showcasing the structure of input, hidden, and output layers that facilitate complex pattern recognition.</figcaption></figure><p>I tried to input a vague concept in the prompt and see what the model would output. Not 100% ready yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vj74OFtyI8BsfB1pf8-Zag.png" /><figcaption>A test on a customer support scenario. This model is not really usable yet.</figcaption></figure><h4>🤑 — We could become rich with this idea</h4><p>Unfortunately, you are not the first to have this idea. There are many many AI diagram startups.</p><p>Let’s quote a few of them :</p><p><strong>Text to diagram :</strong></p><ul><li><a href="https://www.edrawmax.com">EdrawMax</a> : prompt to diagram templates</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ctAY2o8agulEkn-F6hR5w.png" /></figure><ul><li>ChatUML : more focused on a chat experience to iterate on the template</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0vUryIzC7SDvzayPJO1Qg.png" /><figcaption>LLM chat way of building complex diagram templates</figcaption></figure><p>But some of these startups try to offer more than a tool, solution to business problems with their chart tools :</p><ul><li>Database relationship designer : Softbuilder : you write the user stories and you get a tech specification document</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PB0u4KIhpOFgheT6e4yIHw.png" /><figcaption>Softbuilder offer : user need to tech specs</figcaption></figure><ul><li>Decision tree building based on context : Flowcharts.ai. I would escribe it as an advanced GoogleForm</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRukQxIl7DIQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRukQxIl7DIQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRukQxIl7DIQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d44e6ba4a0762a27fa4808cb0ec013af/href">https://medium.com/media/d44e6ba4a0762a27fa4808cb0ec013af/href</a></iframe><p>Most probably, staying too close to the tooling positioning is a dangerous situation. One open-source model can challenge your market position.</p><p>Other applied tools are more complex to challenge. With the text-to-diagram example, you saw how limited the generation was when you explain a use case in a prompt.</p><h4>🔮 — Prediction time : how will all of this evolve</h4><p>For the productivity aspect of LLM based personal assistant, this direction of diagramming looks promising.</p><p>Many companies hire people to compile data into graphs or represent processes with beautiful decision trees. So doing this instantly is very valuable.</p><p>Given how good LLMs are at summarizing information and how compressed the information can be in a diagram, mixing both world would be game-breaker.</p><p>So this is my bet : for the future of Google Gemini, Microsoft Copilot and OpenAI GPT4, generating diagrams will be a big value addition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*jsn9WwLNg6NqBy41UWDGsg.png" /><figcaption>The final conclusion of this article</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f983e03ca25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GPT4o : Is it a breakthrough or an incremental innovation ?]]></title>
            <link>https://medium.com/@adrien_morvan/gpt4o-is-it-a-breakthrough-or-an-incremental-innovation-1aa6d0da54ca?source=rss-fe665bcbeb38------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aa6d0da54ca</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[gpt4-o]]></category>
            <dc:creator><![CDATA[AdMor]]></dc:creator>
            <pubDate>Sun, 19 May 2024 18:40:12 GMT</pubDate>
            <atom:updated>2024-05-24T05:28:51.042Z</atom:updated>
            <content:encoded><![CDATA[<h3>GPT4o : Is it a breakthrough or an incremental innovation ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*lmTQmjgMNKuchd0o" /><figcaption>The demo culture of OpenAI is impressive</figcaption></figure><p>You may have seen the OpenAI <a href="https://openai.com/index/hello-gpt-4o/">demo of GPT4-o</a>, which was impressive. <br>After the emotional shock, it is interesting to decompose what was visible to reverse engineer what is behind the product and <strong>how far ahead OpenAI is</strong> and their new key competitive advantage.</p><p>What are the key improvements of GPT4-o ?</p><ul><li>📹 — Multimodal : video, audio, image. Everything will be understood.</li><li>⏰ — Improved latency and can be interrupted : we get much closer to a human conversation</li><li>🗣 — Improved text-to-speech : high quality voice, singing capacity</li></ul><h4>📹 — Going Further in the multi-modal world</h4><p>ChatGPT has been multi-modal for some time now. It began with GPT4-V the vision+text model of GPT-4.</p><p>It was also possible to chat orally with ChatGPT <a href="https://openai.com/index/chatgpt-can-now-see-hear-and-speak/">since September 2023</a>.</p><p>The main innovation here was the <strong>large reduction in latency</strong>. It was made possible by skipping the speech-to-text step previously done.</p><p>How do you get rid of the speech to text ? <br>The Model has to accept raw audio tokens as input. And this is not much different than having image tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*PJlATYMCJhbNOR00FrJaJQ.png" /><figcaption>Multimodal tokenization — source : <a href="https://docs.google.com/presentation/d/1ZXFIhYczos679r70Yu8vV9uO6B1J0ztzeDxbnBxD1S0/edit">https://docs.google.com/presentation/d/1ZXFIhYczos679r70Yu8vV9uO6B1J0ztzeDxbnBxD1S0/edit</a></figcaption></figure><p>If you dig a bit in recent papers, many people started to train multi-modal networks from large amounts of unlabelled data: <br>- In <a href="https://arxiv.org/pdf/2106.02636">Merlot</a>, a multi-modal network is trained in a masked auto-regressive manner on Youtube videos. It discovers temporal common-sense. It also learns to link image with text. <br>- In <a href="https://arxiv.org/abs/2104.11178">VATT</a> (for Video Audi Text Transformer), a multi modal network is trained on videos with a contrastive loss (similar to the idea of CLIP)</p><h4>⏰ — Improved latency and interrupting the robot</h4><p>The previous architecture allows to avoid the costly speech-to-text. <br>But another improvement makes the complete system more human friendly : a switch activated through a Voice Activity Detection.</p><p>Why ? If there is a voice while GPT speaks maybe it should stop and listen.</p><p>Voice Activity Detection (VAD) was initially designed to identify voice segments from noise in order to activate an agent (think Alexa).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*6EhI3_Nb8_l9GS7n" /><figcaption>With a VAD, you can identify when a person is speaking and when this is only background noise</figcaption></figure><p>But was it new ? Well no.</p><p>Some solo developer even implemented this logic in a local first implementation</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fen6uW595DM8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Den6uW595DM8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fen6uW595DM8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffc7d73e137a74316836867c4f514735/href">https://medium.com/media/ffc7d73e137a74316836867c4f514735/href</a></iframe><p>Some people have also been doing <a href="https://www.reddit.com/r/LocalLLaMA/comments/1cylhce/no_llms_are_not_plateauing_what_is_actually/">estimations</a> of the processing cost on OpenAI side and guessed the network size from there.</p><blockquote>According to Microsoft it’s 12 times less cost to run 4o.</blockquote><p>A smaller model can also explain why the experience can feel more natural.</p><h4>🗣 — Improved text-to-speech</h4><p>The least you can say about the GPT4-o demo is that it starts to be very human like to talk to an AI.</p><p>Much of it also comes from the voice which is very natural : emotion, laughter, singing.</p><p>Did some people achieve this before ? In fact <strong>YES</strong></p><p><a href="https://github.com/suno-ai/bark">Bark</a> from SunoAI released an open-source model capable of singing, generating background noise and more, about a year ago.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8yzcHGzrBMQ%3Fstart%3D150%26feature%3Doembed%26start%3D150&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8yzcHGzrBMQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8yzcHGzrBMQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4d97da54579f67bd57a6cedfcbda4ac/href">https://medium.com/media/b4d97da54579f67bd57a6cedfcbda4ac/href</a></iframe><p>So with enough data, you might actually be able to do like OpenAI and have you expressive voice model ready.</p><h4>🤔 — Guesses about GPT4-o</h4><p>So we have seen some probable GPT4-o innovations. <br>But other guesses are possible :</p><ul><li>Is GPT4-o outputting text or directly audio tokens : it would save additional time when generating an answer to have audio token</li><li>A new closed-source dataset have been used to reach this level of performance on reasoning : probably ones based on educational content given the demo</li></ul><h4>🔚 — Conclusion time</h4><p>When will open-source (or other companies) catch up with OpenAI ?</p><p>Some people (Research Scientist @ Meta AI (FAIR)) already have guesses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjR146MBEAWuLCgR9aZ4Qg.png" /></figure><p>Some others are more confident than post GPT4 release</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*w3PYDRyKb8HlB2hO" /></figure><p>All in all, we can believe the other GAFAM should be able to produce similar apps in the near future.</p><p>The core of the battle is as always <strong>the data</strong> to enable the training of the models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aa6d0da54ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>