<?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 littlereddotdata on Medium]]></title>
        <description><![CDATA[Stories by littlereddotdata on Medium]]></description>
        <link>https://medium.com/@fukumaruuu?source=rss-672c3458ffbe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aVYlj3EEJUsbI0Gr1iVV1g.jpeg</url>
            <title>Stories by littlereddotdata on Medium</title>
            <link>https://medium.com/@fukumaruuu?source=rss-672c3458ffbe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:42:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fukumaruuu/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[“We quickly realised that almost all of the successes hinged on the performance of a small number…]]></title>
            <link>https://fukumaruuu.medium.com/we-quickly-realised-that-almost-all-of-the-successes-hinged-on-the-performance-of-a-small-number-4f6cf2150634?source=rss-672c3458ffbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f6cf2150634</guid>
            <category><![CDATA[technical-leadership]]></category>
            <dc:creator><![CDATA[littlereddotdata]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 23:26:41 GMT</pubDate>
            <atom:updated>2025-04-18T23:26:41.617Z</atom:updated>
            <content:encoded><![CDATA[<p>“<em>We quickly realised that almost all of the successes hinged on the performance of a small number of outstanding technical workers. What distinguished them .. was a rare combination of technical expertise and leadership skills. Today, we would say that they were high in innovation, but with sufficient motivational and organizational skills to make ideas effective.”</em></p><p>Here’s a list of technical leadership books that I’ve read recently</p><h3>Jerry Weinberg: Becoming a Technical Leader</h3><p>I see Jerry Weinberg as a predecessor of the technical writers of our generation (Camille Fournier, Tanya Reilly, Will Larson and the like). He is from a former generation of programmers, the ones who would work with IBM mainframes and debug programs by analyzing piles of computer paper print-outs. Programming is still just as collaborative a discipline today as it was then, and Jerry’s book is still relevant.</p><p><strong>Main ideas</strong></p><ul><li>Technical leadership is different from the leadership talked about in business school or general management books.</li><li>Because they work in complex domains, technical leaders must first investigate a problem fully by drilling into it’s root causes, specifications and expected outputs</li><li>Technical leaders must then be able to motivate and organize others to reach the same understanding.</li><li>Lastly, technical leaders must then manage the flow and quality of ideas produced to address problems in this technical domain.</li><li>Technical domains involve innovation and creativity, so ensuring a team’s wellbeing, and creating an environment where everyone feels empowered, is crucial.</li></ul><p>The main thinking framework of the book has made clear (finally!) lots of my fuzzy thoughts about extending impact beyond myself. For example, how do leadership principles apply when you need to align multiple technical projects with each other? This is most definitely not a problem that can be solved just with status reports and kanban boards and the usual suite of project management tools. Teams need to build and maintain a shared project context, and someone (the official or unofficial) technical leaders on the team need to have effective mechanisms for driving this.</p><p><strong>Highlights and Lowlights</strong></p><p>The message of each book chapter is explained in the form of anecdotes that can meander! There are none of the short and snappy stories seen in today’s business books. This is good and bad. It was entertaining to read a whole chapter about Weinberg musing on how to motivate teams, using his cat catching a mouse as an analogy. For some people though, they might just wish that he got to the point.</p><p>Towards the end, the book’s chapters start to echo principles that other leadership books usually cover. Principles like first understanding oneself and listening and observing before speaking are usually seen today as must-haves for empathetic leadership. There’s not too many new insights from these chapters.</p><p>I’ve read fluffy hot-takes about balancing “hardware and heartware”, and about programming ultimately being a fundamentally human endeavour. This was the first book though that really explored the “how” of applying these ideas to technical disciplines. A good exercise left to the reader would be to list examples of applying this framework to real-life situations.</p><h3>Will Larson: An Elegant Puzzle</h3><p>Will Larson actually mentions Jerry Weinberg’s Becoming a Technical Leader in this book, which is how I started reading Weinberg’s work in the first place.</p><p><strong>Main idea</strong></p><ul><li>We can apply a systems thinking approach to how engineering managers manage teams and organizations. Even though this approach won’t be completely reflective of an individual’s specific situation, they are a starting point that can be refined and can be a tool to formalize our understanding of how our teams and companies function.</li><li>Some examples of systems thinking include thinking of hiring in terms of managing stocks and flows, and designing teams based on an organisations growth stage.</li><li>Engineering management is at its core an ethical profession, and solving the “puzzle” of bringing together individuals and teams is a way for managers to fulfill their obligations in a way that does right by people and company.</li></ul><p><strong>Highlights and lowlights</strong></p><p>As a biologist who studied a ton of ecology, I loved Larson’s systems thinking approach! Reading about the four states of a team (falling behind, treading water, repaying debt and innovating) was just like reading about how different species succeed each other in stages as a mangrove ecosystem matures. Of course, describing a dynamic system such as a team from a systems lens wouldn’t be complete without talking about the effects the stabilizing and destabilizing forces have on this system, such as breaking up or consolidating teams, which the book does as well.</p><p>Thus far, I’ve only been able to draw lessons from specific experiences that I’ve had as one person. But a systems perspective has helped me to generalise my thinking beyond my own immediate experiences.</p><p>I have read reviews where this approach felt too abstract for some people though, so your mileage may vary.</p><p>Substantial parts of the book talk about the mechanics of hiring and ensuring team diversity. There’s also a section about creating policies and how to enforce them. For individual contributors who can’t use these formal mechanisms of influence, these chapters may not be immediately applicable. In fact, this is precisely why Larson also wrote another book specifically for individual contributors (covered below).</p><p>Above all, this book made me marvel at how lucky individual contributors are in tech companies. One gets a manager who can focus mostly on ensuring the team is running well, that it’s members are performing, and that they are developing and thinking about broader career goals. This is most definitely not the case outside of present-day tech companies. In other places, managers might also be doing an IC’s job themselves, and management comes as an afterthought or has to be juggled with a manager’s own IC responsibilities. I remember how game-changing it was the first time when I had a manager consistently monitor my weekly workload and say no on my behalf. It’s not something to take for granted.</p><h3>Will Larson: Staff Engineer: Leadership beyond the Management Path</h3><p>If The Elegant Puzzle was written as a reference for engineering managers, Staff Engineer was written as a guide for individual contributors who want to progress into a Staff Engineer role. While the book does concretely talk about tactics to get the job, the main questions the book tries to answer are the (notoriously) hard questions of how Staff Engineers define their roles and impact, and how they influence outcomes without the formal mechanisms of authority that engineering managers have.</p><p><strong>Main ideas:</strong></p><ul><li>Being a Staff Engineer is fundamentally different from functioning at the level below it (usually a Senior Engineer).</li><li>The step change “ends up being the focus on people: reconciling competing priorities, clearing up miscommunication, aligning folks on the same page” (Stephen Wan when interviewed in the book).</li><li>Like it or not, most of the work in getting the job is making sure you have the right executive visibility. This means working on high priority projects, having executives know who you are (usually through these high priority projects) and having a good reputation (doing high priority projects well). Honestly, having these factors come together can be a function of timing and luck rather than skill alone.</li></ul><p><strong>Highlights</strong></p><ul><li>Including comprehensive interviews of staff engineers who work at a range of companies and teams. This diversity really brought out how varied a Staff Engineer role can be. Companies each have different needs and ways of working; a staff engineer who is a “solver” jumping in to resolve urgent problems may be valued at a company that prioritizes execution speed, but the same archetype may not be as useful another company that looks for consensus builders instead.</li><li>Despite the fuzziness of this job, the book succeeds in drawing out common traits that are needed to be good at this job.</li></ul><p><strong>Lowlights</strong></p><ul><li>Personally, highly-functioning ICs also exist in engineering-adjacent roles such as Field Engineering and Professional Services. There are lots of books written about how to sell and how to be a consultant, but I’ve yet to come across books that address the unique intersection of being a technical sales engineer / technical consultant who is also responsible for having an impact beyond just themselves.</li></ul><p>In comparison to books written about how to be a successful Senior Engineer or Engineering Manager, there aren’t many books written about being a technical leader as a non-manager. The other canonical book is The Staff Engineer’s Path by Tanya Reilly. Both books complement each other well. Tanya’s book is written as a manual for people just promoted as Staff Engineers, while Will’s book is for people interested in getting the role. Hopefully there will be more individual contributor-focused books published in the future.</p><h3>Claire Hughes Johnson: Scaling People</h3><p>This is not a book directly about technical leadership. Claire Hughes Johnson was responsible for scaling teams at Stripe and Google but not in a technical or engineering role. However, many of her book’s lessons do carry over to the technical domain, hence I’ve included the book here. It’s also a book I’ve found super comprehensive and tactical. In fact, The Economist called it “unapologetically practical”.</p><p><strong>Main ideas</strong>:</p><ul><li>Like building the foundations of a house, building companies and teams comes down to putting in structure and consistency in the form of clear goals, regular cadences, reviews, established ways of working.</li><li>Claire uses the analogy of having rules in a game of football. If someone threw a ball at a bunch of beginners and told them to “go play”, the result would be a chaotic disaster. Put down rules and expectations though, and people can have fun and challenge themselves and hone their skills. A similar structure can be applied to companies too.</li><li>Apart from setting in place this “operating system”, it’s also important to make the implicit explicit, to “say the thing you think you cannot say”. For would-be technical leaders looking for pointers, this is the hidden gem in the book.</li></ul><p><strong>Highlights</strong></p><ul><li>Chapter 1 that included the “gem” mentioned above was invaluable for me. It’s all about building trust. A very important topic and, refreshingly, one that Claire breaks down into four concrete action items — building self awareness, being explicit, being clear about how management and leadership are different, and coming back constantly to established operating principles. Trust is so important but so rarely something we can work on directly! These four points would be something to come back to again and again.</li></ul><p>There aren’t really lowlights to this book. It’s written mainly with company building in mind. Most of the book concerns aspects such as hiring, structuring teams and setting a company’s mission and values that may be of important to executives, but not necessarily to people who want to improve their technical leadership skills. Still, the parts about creating stability, structure and trust are definitely great takeaways.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f6cf2150634" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Metrics that matter in production for LLMs: a simple framework]]></title>
            <link>https://fukumaruuu.medium.com/metrics-that-matter-in-production-for-llms-a-simple-framework-fc644ca4f32a?source=rss-672c3458ffbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc644ca4f32a</guid>
            <category><![CDATA[gen-ai-tools]]></category>
            <category><![CDATA[llmops]]></category>
            <dc:creator><![CDATA[littlereddotdata]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 08:58:16 GMT</pubDate>
            <atom:updated>2024-09-17T09:02:02.240Z</atom:updated>
            <content:encoded><![CDATA[<h3>The difference between a prototype and an actual application</h3><p>It only takes a developer an afternoon of pecking away at a laptop to create an LLM chatbot that answers questions over a set of documents. But it can take months for this prototype to be ready for end-users with the safety filters, latency guarantees and privacy guardrails that users need. Moving from “prototype to production” (or implementing LLMOps) can be painfully slow. And the process can be slow not because the process itself is time-consuming, but because it takes teams a long time to understand and plan for the all the different components involved. This post outlines a framework that can help team members align and prioritize on the LLMOps metrics and processes that really matter.</p><h3>How different is LLMOps from MLOps?</h3><ul><li><strong>LLM systems are usually compound systems</strong>, meaning that they include different moving parts that need to be managed together. While traditional ML systems might involve a pre-processing and post-processing step that can be included into a single model call, LLM systems might involve multiple chains with nested logic, or an agent framework that uses different tools depending on a user’s request</li><li><strong>LLM outputs are open-ended.</strong> Traditional machine learning applications might involve tagging a post with appropriate topics (multi-label classification) or forecasting future prices of a product (regression). In contrast, LLM models, by dealing mainly in natural language inputs and outputs, might give different answers to the same question that nonetheless have similar meanings. This means that ground truths are usually not the only “right” answer.</li><li><strong>LLM evaluations are usually subjective.</strong> While summarisation, entity extraction and translation use cases can make use of traditional numeric metrics such as ROUGE scores, precision, recall and BLEU scores, other, more modern LLM applications such as generating SQL from natural language questions do not lend themselves to numeric scores. For example, there can be more than one way of writing a SQL statement that gives the same dataframe output. In these cases, we may need to handle this subjectivity by getting a human evaluator in our development loop, and / or using an LLM judge.</li></ul><h3>A framework categorizing metrics that matter for LLMOps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PlB4j1N9UEamDD4uJDesA.png" /></figure><h3>Model quality metrics</h3><p>Not all metrics are created equally. When developing an LLM application, Our first priority is optimising for quality. Without achieving a standard of quality that our users can accept, we cannot begin to optimise for other metrics such as latency and safety.</p><p>How we define quality depends on the type of application we are building. For RAG applications, we would be interested in metrics such as the precision and recall of our document retrieval step and how grounded our LLM’s responses are in the context that is retrieved. For summarization use cases, we may define a custom quality scale from 1–5 and use an LLM judge to rate the quality of our summarizations. Since an LLM’s outputs are usually open-ended, it becomes imperative that we have an evaluation set with our expected inputs, outputs and (if necessary) relevant documents to benchmark against. Also, although LLM judges are useful for scaling our evaluations to many examples, human feedback is still crucial for judging quality.</p><h3>Operational metrics (eg. latency and throughput)</h3><p>Once we have a quality application, then we can begin to optimize for operational metrics such as latency and throughput. Optimizing for latency may involve reducing the number of steps our model needs to take to reach a response, or cutting down on specific steps that bottleneck the pipeline (such as a lengthy database call). During prototyping, we typically do not focus on latency bottlenecks related to request load or network latency, as this will be something we address as part of the production process.</p><h3>Safety metrics</h3><p>Safety though important, also comes after quality. If we are referring to safety in terms of a model’s responses, then we may implement a topic filter or content moderation filter either as a pre-processing or post-processing step in our pipeline. A filter acting as a pre-processor might filter out irrelevant or toxic questions from users; a filter included as part of a post-processing step might also filter out undesire-able responses, but from the model instead of the user.</p><p>In these cases, we may assign a toxicity score or another metrics (perhaps professionalism) to our inputs and outputs, and flag instances where this score exceeds a certain threshold.</p><p>Safety may not only refer to questions and generated responses. We will also want to ensure that our data is safe — this means that a model may not be allowed to use Personally Identifiable Information (PII) when generating a response, or that only certain users have access to a model. For this aspect of safety, we would rely on data access controls through a governance tool. We may also want to proactively quarantine sensitive data when it appears upstream in our pipeline so downstream systems are not affected.</p><h3>Usage and cost metrics</h3><p>While the previously mentioned metrics are usually the responsibility of a team’s data scientists, usage and cost metrics are unique because they are typically not managed by a platform engineer or governance team instead. Here, what matters are that costs are attributable to a certain business unit, and that usage does not exceed certain limits set by an organization. It’s an unpleasant surprise when a bill comes from higher than expected usage costs. To prevent this, platform administrators and governance teams may implement rate limits or cost alerting by business team to manage resources prudently.</p><h3>How to iterate on metrics</h3><h4>Available tools</h4><p>With an open-source machine learning framework such as MLflow, evaluation can be managed with the MLflow Evaluate library. With MLflow Evaluate, we can define custom metrics such as a bespoke toxicity score, set-up custom LLM judges, and also present our results side-by-side to a human evaluator from the MLflow UI. If we are using Databricks’ Mosaic AI Agent Framework or another front-end tool such as Gradio, we can also create a UI for domain experts to provide feedback on the quality of our system’s responses.</p><p>For identifying latency bottlenecks in our pipeline and for troubleshooting areas that need quality improvement, MLflow also offers MLflow Tracing. MLflow Tracing presents a visual breakdown of Langchain and LlamaIndex pipelines with a simple mlflow.langchain.autolog() or mlflow.llamaindex.autolog() one liner. For more bespoke applications that may use the more flexible mlflow.pyfunc flavor, we can also define custom spans and traces to be logged.</p><h4>Flexibility is key</h4><p>During the prototyping or POC stages of a project, it is the Data Scientist who will usually be iterating on metrics related to model quality and LLM application latency. At this stage, flexibility is key. Different models give different responses to similar questions; a data scientist will need to select the model that provides the best quality answers, for a reasonable latency and cost. To achieve this, all available tooling should be used, from traces, to scalable LLM judges, to human feedback.</p><p>Underpinning all of this work is the governance layer. The governance layer ensures data is protected, and that API usage and costs are kept under control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRUTbS0Xhmn0WGRcN9mWqQ.png" /><figcaption>Sample development setup using Databricks Mosaic AI Agent Framework and Databricks Mosaic AI Evaluation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*lsCE4zW2R5zX-lBt1rQisw.png" /></figure><h3>Extending this framework to LLMOps</h3><h4>What LLMOps means</h4><p>When we talk about “LLMOps”, it is usually in the context of how we want to “move from POC to production”. More concretely, what we usually mean is that we want a define set of steps to migrate an application from our “development” environment to our “production” environment.</p><p>This migration matters because development environments do not have the service level-agreements, robust testing and governance guardrails in place that keep an application up and running without 404 errors, security vulnerabilities and latencies that are unacceptable to an end user. A development environment is flexible and useful for iterating quickly to reach our required quality bar. But once we reach this bar, we then need to plan for how to make our application robust enough that it means “production standards”.</p><p>In practice, turning a prototype into something of “production standard” might involve:</p><ul><li>translating one-off notebook evaluation code into repeatable workflows that can run on schedule</li><li>implementing a data pipeline to log incoming requests and responses, with their corresponding traces</li><li>implementing a monitoring feature on logged requests and responses, and defining appropriate thresholds for important metrics such as latency</li><li>having a process for upgrading and / or replacing older models with newer, more performance ones (this could involve A/B testing two models with a traffic split between models).</li></ul><p>If possible, we can also translate human feedback into automated checks as much as possible. For example, if human feedback was used to evaluate whether a model gave responses that was off-topic, then we may automate this human evaluation step with a traditional topic model that is faster to run than creating another LLM step.</p><p>This is a sample process of what might happen in production, using the Databricks Mosaic AI tech stack as an example. Our initial evaluations developed by the data scientist is still used, but this time defined as a repeatable workflow that evaluates our models responses to inputs on a set schedule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-DI_PSc_y1_mcrQdcHOOWw.png" /><figcaption>Sample production setup using the Databricks platform</figcaption></figure><h4>The role of the ML Engineer in LLMOps</h4><p>The machine learning engineer is usually tasked with defining the assets that we outlined in the previous section (automated workflows, pipelines, logging tables). To make the process repeatable, these assets might be create with Infrastructure-as-code tools such as Terraform. They may have also have their configurations defined within YAML files and saved to version control so change management becomes easy via pull and merge requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*eVFkhcXah6OZwoFFcNPzvg.png" /></figure><h3>Creating a flywheel</h3><p>With our system handling user requests in a production environment, we are now in a position to create a “flywheel” that can lead to continuous system improvements. As user requests come in, we log the requests to a table, run evaluations on the model response quality and output our evaluation metrics to a dashboard. Over time, we gather more and more instances of edge cases, unexpected questions and also feedback on the overall user experience of our application.</p><p>User inputs can form the basis of an ever-expanding evaluation set to evaluate our system against. Unexpected inputs and edge cases can allow us to add tests to our pre-deployment check to increase our system’s robustness. User feedback allows us to redesign and rethink our interfaces so they are more user friendly.</p><h3>Conclusion</h3><p>LLMOps is a tough topic mainly because it contains many moving parts. LLMOps covers many types of metrics, from quality metrics, operational metrics, to safety and also governance metrics. Additionally, orchestrating LLMOps well involves not only technology and tools, but people and processes as well. Having a framework to categorize the different metrics and stages of this process is a first step to making sense of this complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc644ca4f32a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Thinking like an LLM for a day]]></title>
            <link>https://fukumaruuu.medium.com/thinking-like-an-llm-for-a-day-cbbb8b7b3e71?source=rss-672c3458ffbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbbb8b7b3e71</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm-agent]]></category>
            <dc:creator><![CDATA[littlereddotdata]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 01:41:35 GMT</pubDate>
            <atom:updated>2024-09-01T01:41:35.617Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGQlGmEy6og4vRRrYG9o1Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@wilhazec?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">William Felipe Seccon</a> on <a href="https://unsplash.com/photos/woman-in-white-dress-figurine-R2y1K8Fcb-8?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><pre>agent = create_react_agent(model, tools, prompt)<br>agent_executor = AgentExecutor(agent=agent, tools=tools)</pre><p>Begin!</p><blockquote><strong><em>Observation:</em></strong><em> I need breakfast. There is no more yoghurt in the fridge. </em><strong><em>Thought:</em></strong><em> I need to get more yoghurt. I will invoke the </em><em>create_shopping_list tool to add yoghurt to the shopping list.</em></blockquote><blockquote><strong><em>Action:</em></strong><em> Add yoghurt to shopping list. </em><em>{&quot;item&quot;: &quot;yoghurt&quot;} <br></em><strong><em>Observation:</em></strong><em> I am still hungry. The fridge is completely empty. <br></em><strong><em>Thought:</em></strong><em> I will invoke the </em><em>check_freezer tool to check what’s in the freezer. </em><strong><em>Action:</em></strong><em> Check freezer. </em><em>{&quot;duration_of_starting_mindlessly&quot;: 10 seconds} </em><strong><em>Observation:</em></strong><em> There is only Chunky Monkey ice-cream in the freezer. <br></em><strong><em>Final Answer:</em></strong><em> It’s ice-cream for breakfast! 🍨</em></blockquote><p>Question: someone was rude to me. How should I respond?</p><blockquote><strong><em>Thought:</em></strong><em> I need to invoke the </em><em>past_memories tool to see how I have dealt with similar situations in the past. <br></em><strong><em>Action:</em></strong><em> calling memory database </em><em>{&quot;tag&quot;: &quot;rude encounter&quot;} <br></em><strong><em>Observation:</em></strong><em> I can see in the past I ruminated over the encounter for the entire day, finally going to sleep and waking up in the middle of the night still bothered. <br></em><strong><em>Thought:</em></strong><em> As an LLM I have no capacity for rumination or repetitive thoughts. I also have no body and cannot feel where emotions are making my chest contract. There are no tools available for handling this situation. I should abort the react loop and let the incident slide. <br></em><strong><em>Final Answer:</em></strong><em> Stop circular react loop and let things slide.</em></blockquote><p>Question: I’m going hiking. What’s the weather like and how should I prepare?</p><blockquote><strong><em>Thought:</em></strong><em> I need to invoke the </em><em>check_weather API tool <br></em><strong><em>Action:</em></strong><em> checking weather </em><em>{&quot;city&quot;: my_city&quot;} <br></em><strong><em>Observation:</em></strong><em> According to the weather API, it will rain this afternoon. </em><strong><em>Thought:</em></strong><em> I should bring an umbrella. <br></em><strong><em>Observation:</em></strong><em> As an LLM, I have no skin. I do not know the pleasure of soft raindrops falling through the tree canopy leaves onto my head. I also don’t know that being muddy feels more gross than being wet. <br></em><strong><em>Final Answer:</em></strong><em> I should bring wellies. Maybe I don’t need an umbrella after all?</em></blockquote><p>Question: How can I unpack a tuple in Python:</p><blockquote><strong><em>Thought:</em></strong><em> Finally a question for an LLM! <br></em><strong><em>Final Answer:</em></strong></blockquote><pre>my_tuple = (1, 2, 3)<br>x, y, z = my_tuple</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbbb8b7b3e71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ideas for thinking about LLM quality]]></title>
            <link>https://fukumaruuu.medium.com/ideas-for-thinking-about-llm-quality-cce593898a56?source=rss-672c3458ffbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/cce593898a56</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm-applications]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[littlereddotdata]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 06:16:08 GMT</pubDate>
            <atom:updated>2024-08-26T06:16:08.845Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*XVZIv9ilDXcv052i3ywU9g.png" /><figcaption><a href="https://icons8.com/illustrations/illustration/memphis-communicating-with-a-chatbot-by-phone">https://icons8.com/illustrations/illustration/memphis-communicating-with-a-chatbot-by-phone</a></figcaption></figure><p><em>“Your question is not related to any of the datasets in my database. I am happy to help with questions related to sales and product, however. Feel free to ask me about those!”</em></p><p>This was a recent response I got from an LLM. I was stunned for a moment. I had come to expect long strings of text streaming onto the screen a few seconds after I asked a question. But after a while, I realised that this guardrail was probably a good idea. Outputs should be controlled and scoped properly.</p><p>And indeed, as more teams move from POC to production, quality guarantees are a must-have.</p><p>The Vanishing Gradients podcast recently covered this topic with a series of episodes featuring well-known practitioners and academics such as Hamel Husain and Shreya Shankar (full links to all the resources at the end of this post). The episode with Shreya Shankar in particular was very informative. After listening to the podcast, I decided to take a closer looks at the two papers discussed.</p><p><a href="https://vanishinggradients.fireside.fm/32">https://vanishinggradients.fireside.fm/32</a></p><p>This post offers a summary and some takeaways for those interested in LLM quality!</p><ul><li><a href="https://arxiv.org/pdf/2401.03038">spade: Synthesizing Data Quality Assertions for Large Language Model Pipelines</a></li><li><a href="https://www.notion.so/Ideas-for-thinking-about-LLM-quality-1-46aa59e0139e47799ecabfbca4413ac3?pvs=21">Who Validates the Validators? Aligning LLM-Assisted Evaluation of LLM Outputs with Human Preference</a></li></ul><h3>Paper Summaries</h3><p>SPADE starts with the premise that, during the prompt engineering process, developers take a prompt and then add additional instructions to it based on what they care about. For example, adding the instruction, “always address the user politely” may mean that professionalism is important. Therefore, there should be a test that measures the professionalism of every LLM response.</p><p>Using this insight, the paper proposes an algorithmic process for automatically creating quality assertions based on how prompts are elaborated on, corrected and changed (something the authors call “prompt deltas”).</p><p>The SPADE paper focuses on the technical underpinnings of automating quality checks for LLM applications. A later paper, Who Validates the Validators, takes an HCI perspective on the problem by discussing how users interact with an application to iteratively improve generated assertions.</p><p>This paper observes the process that study participants go through to iteratively select and refine tests using a tool the paper’s authors developed (rather than relying completely on an automated process like the SPADE paper). Through these observations, the paper then gives some insights into how developer tools should be design to ensure application quality.</p><h3>Takeaways</h3><p><strong>Taking an empirical approach</strong></p><p>What I found most valuable from these papers was their empirical approach to quality assertions. The authors didn’t just formulate an algorithm or build a tool based on what they thought would be important to users. Rather, they made observations of existing prompts and user behaviour, and then design their tools accordingly.</p><p><strong>Categorizing prompt deltas</strong></p><p>In fact, it was super helpful to see the SPADE paper categorizing the difference instructions that people include in their prompts. In short, amongst the prompts analysed, ~35% of the changes were “structural”, while ~65% of the changes were “content-based”. Structural changes refer to relatively minor changes that do not change a task definition (for example returning a response in JSON format, or requesting newlines between statements. Content-based changes refer to changes that alter the task definition, for example outlining the sequence of steps an LLM should take (do A, then do B) or giving instructions such as “maintain a professional tone”. Knowing overall how prompts are structured across applications and developers can eventually help with better prompt design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*UAP7GCVIqeTqi2EOVw-wCA.png" /><figcaption>source: <a href="https://arxiv.org/pdf/2401.03038">spade: Synthesizing Data Quality Assertions for Large Language Model Pipelines</a></figcaption></figure><p><strong>The iterative process of prompt refinement</strong></p><p>Another insight from the paper Who Validates the Validators paper is the observation that <em>“users need criteria to grade outputs, but grading outputs helps users define criteria”.</em></p><p>The analogy I can think of is the writing — you need a plan to write an article, but the process of writing an article in itself helps you to refine your plan. Criteria then, start off as something like rough sketches that are progressively filled out and colored in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kleu5mwJGUWYp63nrLZKXQ.png" /><figcaption>source: <a href="https://www.notion.so/Ideas-for-thinking-about-LLM-quality-1-46aa59e0139e47799ecabfbca4413ac3?pvs=21">Who Validates the Validators? Aligning LLM-Assisted Evaluation of LLM Outputs with Human Preference</a></figcaption></figure><p><strong>Human judgement with automation works better than just automation alone</strong></p><p>It would save developers a lot of time if the entire quality assertion process could be fully automated (just like how much developer time would be saved if software tests could write themselves). But unfortunately full automation still falls short of a hybrid human + automated approach. For instance, for a particular pipeline, the study authors observed that a hybrid approach produced an assertion set less than half the size of the fully automated one, and increased coverage from 49% to 73%.</p><p><strong>Does this smell like data labelling?</strong></p><p>The whole interactive process of allowing developers to iteratively optimise is quite reminiscent of UIs for data labelling. But instead of correctly outputs directly, we are correcting the functions and criteria that check outputs. It’s like if Great Expectations had a user interface that intelligently surfaced rules for you to optimise.</p><h3>Conclusion</h3><p>By themselves, these papers don’t give recommendations for what to do to improve an LLM system (for example, ways of improving the prompt, or how to judge the context provided by a retrieval step). But they are a great</p><h3>Resources</h3><p><a href="https://arxiv.org/pdf/2401.03038">spade: Synthesizing Data Quality Assertions for Large Language Model Pipelines</a></p><p><a href="https://www.notion.so/Ideas-for-thinking-about-LLM-quality-1-46aa59e0139e47799ecabfbca4413ac3?pvs=21">Who Validates the Validators? Aligning LLM-Assisted Evaluation of LLM Outputs with Human Preference</a></p><p><a href="https://www.youtube.com/watch?v=eGVDKegRdgM">https://www.youtube.com/watch?v=eGVDKegRdgM</a></p><p><a href="https://www.sh-reya.com/blog/ai-engineering-flywheel/">https://www.sh-reya.com/blog/ai-engineering-flywheel/</a></p><p><a href="https://www.oreilly.com/radar/what-we-learned-from-a-year-of-building-with-llms-part-i/">https://www.oreilly.com/radar/what-we-learned-from-a-year-of-building-with-llms-part-i/</a></p><p><a href="https://www.oreilly.com/radar/what-we-learned-from-a-year-of-building-with-llms-part-ii/">https://www.oreilly.com/radar/what-we-learned-from-a-year-of-building-with-llms-part-ii/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cce593898a56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Non-technical books for technical people]]></title>
            <link>https://fukumaruuu.medium.com/non-technical-books-for-technical-people-8bcf8faf95b5?source=rss-672c3458ffbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bcf8faf95b5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-market]]></category>
            <dc:creator><![CDATA[littlereddotdata]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 00:09:29 GMT</pubDate>
            <atom:updated>2024-08-18T00:25:24.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbkReJtg6B0ScD1sntdZ7A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tjdragotta?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">TJ Dragotta</a> on <a href="https://unsplash.com/photos/mens-playing-instruments-on-road-FWLHZcKSZas?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>No, this is not a productivity post!</p><p>It’s a short list of books that can widen your perspective as a tech worker. They won’t directly teach you how to communicate better with your manager, or how to design a scalable distributed system. But, read over some tea on a weekend, they could make you see your work differently.</p><h3>Atlas of AI by Kate Crawford</h3><p>As tech workers, we spend our days peering at computer screens. We stare at code and analyze neat squares of data. We have ergonomic chairs and air-conditioned offices! But, as Kate outlines in this book, the AI industry is not only algorithms and programs whirring on machines.</p><p><em>“AI is neither artificial not intelligent. Rather, artificial intelligence is both embodied and material, made from natural resources, fuel, human labour, infrastructure, logistics, histories and classifications”</em></p><p>Kate forces us to look up from our screens and consider the AI industry as an extractive one, one that extracts, literally, minerals from the earth to build computing machines, human knowledge as data to train models, and messy human preferences to build classification models that represent a stripped-down version of how humans experience music, books and social connection.</p><p>We are taken on a tour of the lithium mining pits in Nevada being stripped to provide rare metals to build computers, the “long-corridors of energy-devouring data centers, skull archives, image databases and the fluorescent-lit hangars of delivery warehouses”. For someone who’s interaction with a data center is pressing “Start” on a cloud instance to run a machine learning model, the book is an eye-opener.</p><p>Given the breadth of this book, the “atlas” in the book’s title becomes a image that organises the books information. Each book chapter is meant to connect to the others to form a map of the AI industry. These accounts cover the “extractive mining that leaves an imprint of the planet, the mass capture of data, and the profoundly unequal and exploitative labor practices that sustain it”. It’s a wide-ranging set of settings, and it forces the reader to consider more closely the “physical infrastructure, social values and power dynamics” that influence the AI industry.</p><p>When this book was published in 2021, some practices in the tech industry, such as using classification algorithms for social justice or using employing low-wage workers for data labelling tasks, were still not as widely discussed or as regulated as they are today. We’ve made progress between 2021 and now. But although we are now more aware of these realities, the industry is still young, and this books offers a great way to think about the challenges ahead.</p><h3>The Real Work by Adam Gopnik</h3><p>A tech worker is always paddling against an incoming tidal wave of information. Every week there is a new Large Language Model released. Every week a new technique to improve Retrieval-Augmented Generation is published. Keeping up with the news to stay relevant is half our jobs. Then, the other half of the job is getting better at what we already know. Coding, a main way we express our ideas to a computer, is a craft that needs to be honed deliberately. We are always faced with the question of how to improve and maintain mastery.</p><p>And mastery is precisely what Adam Gopnik writes about in The Real Work, though not in the way that you might think. How to cultivate mastery is already extensively covered in books like Timothy Gallwey’s “The Inner Game” series. What Gopnik does, in contrast, is take us through examples of every day mastery that are commonly overlooked, and to draw out the poetry in the mundane.</p><p>My favourites are his accounts of his mother and his wife baking bread, of his attempts to learn to dance with his daughter, and his experiences learning to drive.</p><p>None of these activities are very remarkable. Most people can do these things every day without much thought. Certainly someone who kneads a good sourdough is not at the level of someone winning an Olympic medal or writing a seminal research paper. But this is entirely Gopnik’s point — there is “accomplishment” (getting a good grade on a music exam), and there is “mastery”, which is feeling like what was devilishly hard to do before, like make a sound on a flute, suddenly feels easy. The first relies on external measures of achievement, and the second involves a more internally-focused way of transcending one’s former limitations.</p><p>Gopnik does not offer any instructions or self-help tips in this book. But he does approach mastery as something poetic, fulfilling and uniquely human. Mastery is not only a “sign of skill”. When appreciating mastery, we also “search for the signs of a unique human presence: it’s why we love vibrato in a voice, legato in piano performance, why we catalog the tics and mannerisms of a baseball player at the bat”. Mastery is not only a means to recognition, achievement, and status. it’s also something worth pursuing for its own sake.</p><p>I’m going to keep these descriptions in mind the next time another article about “the 5 ways to progress to staff engineer” pops up.</p><p>For a summary, The Atlantic published a great article <a href="https://www.theatlantic.com/books/archive/2023/04/the-real-work-book-review-mastery/673701/">here</a>.</p><h3>The Lifecycle of Software Objects by Ted Chiang</h3><p>This is a short story more than a book, but it’s quite profound. In this book, the two main characters are employees at a computer that builds digital pets. The protagonist, Anna, develops a close relationship with one of the pets, Jax, and is faced with a dilemma when the company creating the pets, Blue Gamma, is shut down. The digital pets no longer have a home on the internet, and Anna and other digital pet owners have to make some tough decisions on whether and how to sustain these “beings”.</p><p>There are so many ethical threads to this story and no answers, which is precisely why it’s such a good read.</p><p>A summary of the short story can be found <a href="https://en.wikipedia.org/wiki/The_Lifecycle_of_Software_Objects">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bcf8faf95b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving my NBA stats SQL Agent Part 2]]></title>
            <link>https://fukumaruuu.medium.com/improving-my-nba-stats-sql-agent-part-2-5234c9e4b474?source=rss-672c3458ffbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/5234c9e4b474</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[llm-agent]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[littlereddotdata]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 00:49:06 GMT</pubDate>
            <atom:updated>2024-08-16T05:10:12.494Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*7xW3AEQFMn_6PmlO99QIHQ.png" /><figcaption><a href="https://icons8.com/illustrations/author/627444">https://icons8.com/illustrations/author/627444</a></figcaption></figure><h3>Introduction</h3><p><a href="https://medium.com/p/6aafe7acb01c">See Part 1 here</a></p><p><a href="https://github.com/jeannefukumaru/mlflow_traces_sql_agent/tree/v1">Code for Part 1 is here</a> and code for <a href="https://github.com/jeannefukumaru/mlflow_traces_sql_agent/tree/main">Part 2 is here</a></p><p>Previously, we use a simple SQLDatabase Agent in Langchain so we can ask use natural language against our NBA stats database instead of having to write SQL. We also set up evaluation using MLflow Traces to give a baseline measurement of this agent’s performance.</p><p>Our work is not done though! Building Text to SQL agent means paying attention to many components, especially if we want a quality agent. So in part 2, we will go through some changes we made to our original implementation.</p><p>It’s also worth noting that making changes may not necessarily mean performance will improve. This is why we set up an evaluation process FIRST so that we can measure whether or not a change made actually leads to improvement.</p><h3>1. Use SparkSQL agent and toolkit instead of SQLDatabase agent and toolkit</h3><p>We originally used the SQLDatabaseToolkit with a SQLDatabase agent as a starting point. But looking more closely, we see that the SQLDatabase agent is built to cover a range of SQL dialects. But we are focused only on executing SparkSQL against our database.</p><p>So we can try using the SparkSQL agent and toolkit instead to see whether focusing on SparkSQL will increase the accuracy and relevancy of the SQL our agent generates.</p><pre>spark_sql = SparkSQL(catalog=&quot;main&quot;, schema=&quot;nba_sql_agent&quot;)<br>llm = ChatDatabricks(endpoint=&quot;databricks-meta-llama-3-1-70b-instruct&quot;)<br>tools = SparkSQLToolkit(db=spark_sql, llm=llm)<br>agent = create_spark_sql_agent(llm=llm, toolkit=tools, verbose=True, agent_executor_kwargs={&quot;handle_parsing_errors&quot;:True})</pre><h3>2. Table metadata to include within the prompt</h3><p>When we look at the implementation of the SparkSQL agent and of SQLDatabase agents we see that the agents have tools to list available database tables and their metadata.</p><p>For example with SQLDatabaseToolkit().get_tools() we have:</p><pre>[QuerySQLDataBaseTool(),<br> InfoSQLDatabaseTool()<br> ListSQLDatabaseTool(),<br> QuerySQLCheckerTool()]</pre><p>From looking at our MLflow Traces, we see our agent can take extra time to iterate on a SQL query error because everytime it does error handling, it needs to: 1. decide to use the InfoSQLDatabaseTool() and the ListSQLDatabaseTool() and 2. use the tool and evaluate the output.</p><p>Since we only have one table in our database, we can include the table description, column description and few-shot examples directly in our prompt. By doing this, we can reduce the number of tool calls our Agent has to make and reduce our latency.</p><pre>table_desc = json.dumps({&quot;description&quot;: &quot;The &#39;nba_games&#39; table contains data about NBA games, including details about the teams, game statistics. It includes information such as the game date, matchup, and win-loss record. This data can be used for various purposes, including game analysis. It can also be used to identify trends and patterns in player performance and team performance over time.&quot;})</pre><pre>column_comments = json.dumps({&#39;season_id&#39;: &quot;Unique identifier for the NBA season.&quot;,<br> &#39;team_id_home&#39;: &quot;Identifier for the home team in the game.&quot;,<br> &#39;team_abbreviation_home&#39;: &quot;Abbreviated representation of the home team&#39;s name.&quot;,<br> &#39;team_name_home&#39;: &quot;Full name of the home team in the game.&quot;,<br> &#39;game_id&#39;: &quot;Unique identifier for the game.&quot;,<br> &#39;game_date&#39;: &quot;Date when the game was played.&quot;,<br> &#39;matchup_home&#39;: &quot;Opposing team&#39;s abbreviation for the home team.&quot;,})<br> <br> few_shot_examples = json.dumps([{&#39;Question&#39;: &#39;How many away games did the Boston Celtics win in 2023&#39;, <br>                                 &#39;Answer&#39;: &quot;&quot;&quot;SELECT count(season_id) as total_wins,year(game_date) as year <br>                                FROM nba_games <br>                                WHERE wl_away = &quot;W&quot; and team_name_away = &quot;Boston Celtics&quot; and year(game_date) = 2023 <br>                                GROUP BY year(game_date)&quot;&quot;&quot;}])</pre><h3>3. Format prompt using ChatPromptTemplate</h3><p>Now that our prompt is more complex, we can use the Langchain ChatPromptTemplate so we can organize the system prompt, user prompt and chat history separately</p><pre>from langchain_core.prompts.chat import SystemMessagePromptTemplate, HumanMessagePromptTemplate<br>from langchain.prompts import ChatPromptTemplate, PromptTemplate, MessagesPlaceholder</pre><pre>system_message_template = &quot;&quot;&quot;&quot;You are an expert in the American NBA. Your task is to answer user questions about games, teams and players. <br>    Think step-by-step what SQL query you need in order to answer the users question. Include the SQL query you finally used in your final output. <br>    This is a description of the table: {table_desc}<br>    This is an explanation of the column comments: {column_comments}<br>    Here are some examples of the user question and the corresponding SQL query: <br>    {few_shot_examples}&quot;&quot;&quot;<br>system_message = SystemMessagePromptTemplate(prompt=PromptTemplate(input_variables=[&quot;table_desc&quot;, &quot;column_comments&quot;, &quot;few_shot_examples&quot;], template=system_message_template))<br>chat_prompt_str = ChatPromptTemplate([system_message,<br> MessagesPlaceholder(variable_name=&#39;chat_history&#39;, optional=True),<br> HumanMessagePromptTemplate(prompt=PromptTemplate(input_variables=[&#39;input&#39;], template=&#39;{input}&#39;))])</pre><h3>4. Helper functions to help us parse our user questions for the LLM Agent</h3><p>Users may not ask questions in a way that directly translates into a valid SQL query. For example, sports fans might refer to Michael Jordan as “Air Jordan” or just “Jordan”. To help our Agent, we can translate these terms into the entities that are actually stored in our database (in this case the player’s full name). While it can seem feasible to use an LLM to parse colloquial player names into their full form, it’s also much faster and easier to start with a rule-based solution first.</p><pre># Parse player names if shortforms or nicknames are used<br>def parse_player_names(query):<br>    known_nicknames = [&quot;iceman&quot;, &quot;air jordan&quot;]<br>    nicknames_in_query = [n for n in known_nicknames if n in query]<br>    player_nickname_map = {&quot;iceman&quot;: &quot;George Gervin&quot;, &quot;air jordan&quot;: &quot;Michael Jordan&quot;}<br>    <br>    for n in nicknames_in_query:<br>        try:<br>            real_name = player_nickname_map[n]<br>            query = query.replace(n, real_name)<br>        except KeyError:<br>            pass</pre><p>Then, within our LLM chain, we can call this function on the user’s input as part of the Langchain Expression Language (LCEL)</p><pre>chain = (<br>    {<br>        &quot;input&quot;: itemgetter(&quot;messages&quot;)<br>        | RunnableLambda(parse_player_names),})</pre><h3>5. Customise the SparkSQLToolkit</h3><p>As we saw before, the toolkit that we pass to our Agent is really a class that encapsulates a list of tools. Instead of having a tool to list the tables and table information from our database, which takes time, we include this information directly in our prompt and leave out the original ListSparkSQLTool and InfoSparkSQLTool from the Toolkit.</p><pre>class SparkSQLToolkit(BaseToolkit):<br>  &quot;&quot;&quot;Toolkit for interacting with Spark SQL.<br>  Parameters:<br>      db: SparkSQL. The Spark SQL database.<br>      llm: BaseLanguageModel. The language model.<br>  &quot;&quot;&quot;<br>  db: SparkSQL = Field(exclude=True)<br>  llm: BaseLanguageModel = Field(exclude=True)<br>  <br>  class Config:<br>      arbitrary_types_allowed = True</pre><pre>  def get_tools(self) -&gt; List[BaseTool]:<br>    &quot;&quot;&quot;Get the tools in the toolkit.&quot;&quot;&quot;<br>    return [<br>        QuerySparkSQLTool(db=self.db),<br>        NewQueryCheckerTool(db=self.db, llm=self.llm),<br>    ]</pre><h3>6. Customise tool prompts</h3><p>Some tools used by our agent have prompts associated with them, for example, the QuerySparkSQLTool contains a prompt to check the validity of a sql query before it is executed. If we see persistent model errors because of certain syntax errors, we can update this prompt to be more relevant. Then, we can include this new prompt into the QueryCheckTool in the SparkSQLToolkit</p><pre># original prompt<br>&#39;Double check the Spark SQL query above for common mistakes, including:\\n&#39;<br> &#39;- Using NOT IN with NULL values\\n&#39;<br> &#39;- Using UNION when UNION ALL should have been used\\n&#39;<br> &#39;- Using BETWEEN for exclusive ranges\\n&#39;<br> &#39;- Data type mismatch in predicates\\n&#39;<br> &#39;- Properly quoting identifiers\\n&#39;<br> &#39;- Using the correct number of arguments for functions\\n&#39;<br> &#39;- Casting to the correct data type\\n&#39;<br> &#39;- Using the proper columns for joins\\n&#39;<br> &#39;\\n&#39;<br> &#39;If there are any of the above mistakes, rewrite the query. If there are no &#39;<br> &#39;mistakes, just reproduce the original query.&#39;</pre><pre>NEW_QUERY_CHECKER = &quot;&quot;&quot;<br>{query}<br>Double check the Spark SQL query above for common mistakes, including:<br>- Using NOT IN with NULL values<br>- Using UNION when UNION ALL should have been used<br>- Using BETWEEN for exclusive ranges<br>- Data type mismatch in predicates<br>- Properly quoting identifiers<br>- Using the correct number of arguments for functions<br>- Casting to the correct data type<br>- Using the proper columns for joins<br>- Make sure your string matching formatting is correct</pre><pre>class NewQueryCheckerTool(BaseSparkSQLTool, BaseTool):<br>    &quot;&quot;&quot;Use an LLM to check if a query is correct.<br>    Adapted from &lt;https://www.patterns.app/blog/2023/01/18/crunchbot-sql-analyst-gpt/&gt;&quot;&quot;&quot;<br>    template: str = NEW_QUERY_CHECKER<br>    llm: BaseLanguageModel<br>    llm_chain: Any = Field(init=False)<br>    name: str = &quot;query_checker_sql_db&quot;<br>    description: str = &quot;&quot;&quot;<br>    Use this tool to double check if your query is correct before executing it.<br>    Always use this tool before executing a query with query_sql_db!<br>    &quot;&quot;&quot;<br>    @root_validator(pre=True)<br>    def initialize_llm_chain(cls, values: Dict[str, Any]) -&gt; Dict[str, Any]:<br>        if &quot;llm_chain&quot; not in values:<br>            from langchain.chains.llm import LLMChain<br>            values[&quot;llm_chain&quot;] = LLMChain(<br>                llm=values.get(&quot;llm&quot;),  # type: ignore[arg-type]<br>                prompt=PromptTemplate(<br>                    template=NEW_QUERY_CHECKER, input_variables=[&quot;query&quot;]<br>                ),<br>            )<br>        if values[&quot;llm_chain&quot;].prompt.input_variables != [&quot;query&quot;]:<br>            raise ValueError(<br>                &quot;LLM chain for QueryCheckerTool need to use [&#39;query&#39;] as input_variables &quot;<br>                &quot;for the embedded prompt&quot;<br>            )<br>        return values<br>    def _run(<br>        self,<br>        query: str,<br>        run_manager: Optional[CallbackManagerForToolRun] = None,<br>    ) -&gt; str:<br>        &quot;&quot;&quot;Use the LLM to check the query.&quot;&quot;&quot;<br>        return self.llm_chain.predict(<br>            query=query, callbacks=run_manager.get_child() if run_manager else None<br>        )<br>    async def _arun(<br>        self,<br>        query: str,<br>        run_manager: Optional[AsyncCallbackManagerForToolRun] = None,<br>    ) -&gt; str:<br>        return await self.llm_chain.apredict(<br>            query=query, callbacks=run_manager.get_child() if run_manager else None<br>        )</pre><h3>Conclusion</h3><p>These are some ideas for customising and improving the results of a Text-to-SQL Agent. Tools and agents from libraries may benefit from customisation, and it’s helpful to be see how tools and agents really work so we can tune them as needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5234c9e4b474" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a ComposerModel? Why is it useful for training neural networks?]]></title>
            <link>https://fukumaruuu.medium.com/what-is-a-composermodel-why-is-it-useful-for-training-neural-networks-af99ab64489d?source=rss-672c3458ffbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/af99ab64489d</guid>
            <category><![CDATA[gen-ai-tools]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[littlereddotdata]]></dc:creator>
            <pubDate>Wed, 31 Jul 2024 08:37:04 GMT</pubDate>
            <atom:updated>2024-07-31T08:38:28.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*raIC3nHKHUbEnI6l0Lx47A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@govizlora?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Yuheng Ouyang</a> on <a href="https://unsplash.com/photos/an-old-computer-sitting-on-top-of-a-desk-okgMMgpliIk?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>When I first started using the OSS libraries <a href="https://github.com/mosaicml/composer">Composer</a> and <a href="https://github.com/mosaicml/llm-foundry">LLM Foundry</a> for training Large Language Models, I was surprised to see an abstraction I had not seen before — the ComposerModel . I had heard of Pytorch models, and HuggingFace models, but not of Composer models. In fact, the Composer library had several abstractions for interfacing between HuggingFace and Composer. Clearly there were differences between the two. But what exactly were they and why would they be important? I needed to find out.</p><p>Table of contents:</p><ul><li>Background: What is the Composer library?</li><li>Background: Why do we need Composer as a framework on top of Pytorch?</li><li>Where does the ComposerModel abstraction fit in this picture?</li><li>Interfacing between Composer and HuggingFace for Large Language models</li></ul><h3>Background: What is the Composer library?</h3><p>Composer is a Pytorch-based framework built for training neural-networks in the most efficient and flexible way possible. It does this by abstracting away the complex logic needed to manage distributed training over multiple GPUs (a must for modern-day neural network training), while still allowing developers to implement custom algorithms and callbacks as needed.</p><h3>Background: Why do we need Composer as a framework on top of Pytorch?</h3><p>Training neural networks involves managing many things, from the way data is loaded and processed, to how the model is architected, and how the model weights are updated with its optimizers and learning rate schedulers. Add in the need for also managing distributed training across multiple GPUs, and the code needed to orchestrate the training process can become confusing and unmanageable. Not to mention, state-of-the-art techniques are continually being developed, and we may want to augment an existing model architecture to use these modern techniques. Composer streamlines this whole process in a way that is not only easy, but flexible too.</p><h3>Flexibility</h3><p>Custom algorithms such as <a href="https://docs.mosaicml.com/projects/composer/en/stable/method_cards/selective_backprop.html">Selective Backprop</a> can speed up the model training process, while others can improve a model in other ways, such as <a href="https://docs.mosaicml.com/projects/composer/en/stable/method_cards/label_smoothing.html">helping it to generalise</a>. With Composer, these custom algorithms can be inserted into various points in the model training loop, such as the data preprocessing step and the model training step.</p><p>As an example, using the ColOut technique, we can choose to drop random rows and columns from image data before they are loaded into the model training loop (<a href="https://docs.mosaicml.com/projects/composer/en/stable/examples/custom_speedup_methods.html">example from docs</a>). This helps us speed up training because we reduce the size of the image passed to a model. It can also act as a form of data augmentation by increasing the variability of the data the model sees.</p><h3>Ease of use</h3><p>With models trending towards the 7B, 13B and 70B parameter range, we not only have to split datasets across multiple GPUs. We have to do the same with models as well. Sharding a model across multiple GPUs involves more than just distributing the model weights. We may also need to shard the model’s optimizer and activations, and manage the updates during training in a distributed manner as well. It’s never a good idea to manage this manually, and this is where Composer’s Trainer object can help - it handles the orchestration of the model training loop for us, leaving us to focus on higher-level decisions such as which learning rate scheduler to use.</p><h3>Where does the ComposerModel abstraction fit in this picture?</h3><p>A ComposerModel acts as an interface to the Composer Trainer class. It wraps up a neural network and allows the Trainer to then orchestrating the training loop.</p><p>Creating a ComposerModel at minimum means implementing the forward() and loss() methods from the ComposerModel <a href="https://github.com/mosaicml/composer/blob/dev/composer/models/base.py">base class</a>. But this is rarely enough, because we usually also want to measure how well our model is performing. For this, we also need to compute metrics, which is done via <a href="https://docs.mosaicml.com/projects/composer/en/stable/composer_model.html#metrics">implementing</a> the eval_forward() , get_metrics and update_metrics methods.</p><p>Example of implementing the forward() and loss() methods of the ComposerModel class from the <a href="https://docs.mosaicml.com/projects/composer/en/stable/composer_model.html">Composer docs</a>:</p><pre>import torchvision<br>import torch.nn.functional as F</pre><pre>from composer.models import ComposerModel</pre><pre>class ResNet18(ComposerModel):</pre><pre>    def __init__(self):<br>        super().__init__()<br>        self.model = torchvision.models.resnet18()</pre><pre>    def forward(self, batch): # batch is the output of the dataloader<br>        # specify how batches are passed through the model<br>        inputs, _ = batch<br>        return self.model(inputs)</pre><pre>    def loss(self, outputs, batch):<br>        # pass batches and `forward` outputs to the loss<br>        _, targets = batch<br>        return F.cross_entropy(outputs, targets)</pre><p>Example of implementing metrics with the ComposerModel class, from the <a href="https://docs.mosaicml.com/projects/composer/en/stable/composer_model.html#metrics">docs</a>:</p><pre>class ComposerClassifier(ComposerModel):</pre><pre>    def __init__(self):<br>        super().__init__()<br>        self.model = torchvision.models.resnet18()<br>        self.train_accuracy = torchmetrics.classification.MulticlassAccuracy(num_classes=1000, average=&#39;micro&#39;)<br>        self.val_accuracy = torchmetrics.classification.MulticlassAccuracy(num_classes=1000, average=&#39;micro&#39;)</pre><pre>    ...</pre><pre>    def eval_forward(self, batch, outputs):<br>        if outputs:<br>            return outputs<br>        inputs, _ = batch<br>        outputs = self.model(inputs)<br>        return outputs</pre><pre>    def update_metric(self, batch, outputs, metric):<br>        _, targets = batch<br>        metric.update(outputs, targets)</pre><pre>    def get_metrics(self, is_train=False):<br>        # defines which metrics to use in each phase of training<br>        return {&#39;MulticlassAccuracy&#39;: self.train_accuracy} if train else {&#39;MulticlassAccuracy&#39;: self.val_accuracy}</pre><p>Once the model is passed into the Trainer class, Trainerin turn, manages the model training loop in a way that allows us to:</p><ul><li>implement customised speed-up methods available from the Composer library. For example, dropping random rows and columns from image data before they are loaded into the model training loop (<a href="https://docs.mosaicml.com/projects/composer/en/stable/examples/custom_speedup_methods.html">example from docs</a>)</li><li><a href="https://docs.mosaicml.com/projects/composer/en/stable/trainer/using_the_trainer.html#distributed-training">implement distributed training</a> without handling torch.distributed logic by hand.</li></ul><h3>Interfacing between Composer and HuggingFace for Large Language Models</h3><p>We can see now why we need an model abstraction here. The training loop is tightly integrated with the model architecture and data (and any customisations we make to the model and data). So it makes sense to have two abstractions (ComposerModel and Trainer ) that work well together.</p><p>But for large language models focused on text, many OSS models are published on HuggingFace. After training our own model, we may also want to publish the model to HuggingFace. Hence, to interface between Composer and HuggingFace, we can</p><ul><li>Use <a href="https://github.com/mosaicml/llm-foundry/blob/78e91ef790039c57100bc83362cf01f95f07ea7c/llmfoundry/models/hf/hf_causal_lm.py#L4">hf_causal_lm</a> from LLM Foundry to wrap a HuggingFace model as a Composer object, and train the model using the standard Trainer workflow. If using Mosaic AI MCT, this is the corresponding mcli configuration field:</li></ul><pre>model:<br>    name: hf_causal_lm<br>    init_device: mixed<br>    pretrained_model_name_or_path: meta-llama/Llama-2-7b-hf<br>    pretrained: true<br>    # Note: you must have set the HF_TOKEN environment variable and have access to the llama2 models<br>    use_auth_token: true<br>    use_flash_attention_2: true</pre><ul><li>Save a Composer checkpoint in HuggingFace format using hf_checkpointer <a href="https://github.com/mosaicml/llm-foundry/blob/78e91ef790039c57100bc83362cf01f95f07ea7c/llmfoundry/callbacks/hf_checkpointer.py#L136">callbac</a>k in LLM Foundry</li></ul><pre>callbacks:<br>    hf_checkpointer: <br>      save_interval: # how often to save a checkpoint. <br>      save_folder: # which cloud storage folder to save the checkpoint<br>      # other arguments</pre><h3>Closing thoughts</h3><p>My introduction to the ComposerModel class was via Large Language Models. But it’s worth keeping in mind that Composer is a general purpose framework for neural networks in general. It can be used for training vision models, embedding models, and diffusion models. Also, training deep neural networks, especially large language models, can increase exponentially in difficulty with model size. This is where other parts of the Mosaic AI stack, such as Streaming Datasets and LLM Foundry come in. Training large models is not easy, and there are different tools for each part of the job.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af99ab64489d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How MLflow Traces allows me to improve my NBA stats SQL Agent]]></title>
            <link>https://fukumaruuu.medium.com/how-mlflow-traces-allows-me-to-improve-my-nba-stats-sql-agent-6aafe7acb01c?source=rss-672c3458ffbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aafe7acb01c</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[littlereddotdata]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 07:50:34 GMT</pubDate>
            <atom:updated>2024-07-31T05:00:21.804Z</atom:updated>
            <content:encoded><![CDATA[<p>💻 code for this article is <a href="https://github.com/jeannefukumaru/mlflow_traces_sql_agent/tree/main">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0lAQ67hLsd4BYYr9hhE9IQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@maxwinkler?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Max Winkler</a> on <a href="https://unsplash.com/photos/grayscale-basketball-players-UFIZodJgScQ?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>It’s quite common to use unstructured data to augment the contextual knowledge of a Large Language Model. But it’s less common to do the same with structured data. I got curious about this, and so built a SQL Agent to answer questions about NBA games based on <a href="https://www.kaggle.com/datasets/wyattowalsh/basketball">NBA game statistics.</a></p><p>Sports data analysis is actually a really rich field! Some sites I got inspiration from include <a href="https://sltsportonomix.substack.com/p/beyond-the-court-assessing-player">https://sltsportonomix.substack.com/p/beyond-the-court-assessing-player</a> which did a few really in-depth posts on how data can <a href="https://sltsportonomix.substack.com/p/behind-the-buzzer-decoding-the-dynamics">“decode the dynamics of comeback victories”</a> and provide new ways of <a href="https://sltsportonomix.substack.com/p/beyond-the-court-assessing-player">understanding a player’s team contribution</a>.</p><p>My use of the data is much simpler. I’m sure if I were a basketball enthusiast I would be able to ask many more interesting questions about the data. But we’ll leave that for another day.</p><h3>The Agent Itself</h3><p>I used Langchain to build the Agent and logged the Agent to MLflow for further analysis. The code for that is here, and there is more information on using MLflow with Langchain. But the focus here will be on the subsequent step of analysing the Agent’s performance.</p><h3>Evaluation Dataset</h3><p>We can’t analyse performance without an evaluation dataset, so here is one. Evaluation dataset follows the <a href="https://docs.databricks.com/en/generative-ai/agent-evaluation/evaluation-set.html#eval-set-schema">schema</a> expected by Mosaic AI Agent Evaluation. It’s a schema that’s really useful for structuring how we think about LLM evaluation. Specifically, that we not only need to have questions and answers, but also additional context to the answers. For unstructured data, this could be documents that we retrieve from a vector database. For structured data (our case) this could be the actual SQL query that we would have needed to answer a question about the data. For this particular use case, we also add an extra field — difficulty - to the schema so we can separate evaluation of easier and harder questions</p><pre>eval_data = [<br>    {<br>        &quot;request&quot;: &quot;How many away games did the Boston Celtics win in 2023&quot;,<br>        &quot;difficulty&quot;: &quot;easy&quot;,<br>        &quot;expected_response&quot;: &quot;Boston Celtics won 20 away games in 2023&quot;,<br>        &quot;expected_retrieved_context&quot;: [<br>            {<br>                &quot;doc_uri&quot;: &quot;&quot;&quot;SELECT count(season_id) as total_wins,year(game_date) as year <br>                                FROM nba_games <br>                                WHERE wl_away = &quot;W&quot; and team_name_away = &quot;Boston Celtics&quot; and year(game_date) = 2023 <br>                                GROUP BY year(game_date)&quot;&quot;&quot;<br>            },<br>        ],<br>    },]</pre><p>Starting the MLflow run for evaluation:</p><pre>with mlflow.start_run(run_id=mlflow_run_id):<br>    # Evaluate<br>    eval_results = mlflow.evaluate(<br>        data=eval_df,<br>        model=f&quot;runs:/{mlflow_run_id}/chain&quot;,  <br>        model_type=&quot;databricks-agent&quot;,<br>    )</pre><h3>Analyzing Traces</h3><p>MLflow Traces logs all the Langchain calls that the Langchain SQL Agent Executor makes to answer our question. We can parse these Traces, and extract the outputs of the ReActSingleOutputParser calls to see the sequence of steps our Agent has gone through to answer our question. To help with parsing, we define an <a href="https://github.com/jeannefukumaru/mlflow_traces_sql_agent/blob/main/nba_sql_agent/02_MLflow_Traces_Evaluation.py#L118">AgentAnalyzer()</a> <a href="https://github.com/jeannefukumaru/mlflow_traces_sql_agent/blob/main/nba_sql_agent/2024-07-16-LLM-judge-evaluation-simple-dataset.py#L113">class</a> that contains helper methods for our analysis. The final outputs can be saved into a Pandas Dataframe, from which we can see which tools the Agent selected as well as the Agent’s reasoning for selecting that tool.</p><h3>Is our Agent able to select tools appropriately?</h3><p>🔍 In this example, we can see that the SQL Agent seems to be using the tools available to it in a logical sequence. It checks for what tables are available with sql_db_list_tables , gets the table schema with sql_db_schema , then crafts a SQL query and checks and runs it.</p><h3>How many times does our Agent need to call a tool before getting an answer?</h3><p>Sometimes, when an Agent is unable to construct a valid SQL query or find the right table to call, it can end up in a loop where it continually queries the data until a time out happens. That doesn’t seem to be the case here though. From the correctness feedback given by the LLM-as-a-judge from MLflow Evaluate, we can see the steps taken by the LLM is pretty even across requests, and there aren’t really calls that take many steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*wnNxrfDxJaB41E59Ktr5DQ.png" /></figure><h3>Does the Agent’s final output make sense?</h3><p>Although in this case we only have 3 questions, if we were to keep changing chain parameters such as the LLM model and the prompt, constantly evaluating the LLM output would take a lot of time. So instead of manual evaluation, we can extract the <strong>response/llm_judged/correctness/rating</strong> and <strong>response/llm_judged/correctness/rationale</strong> evaluations from the LLM-as-a-judge evaluation to check the correctness of the Agent’s final output. Here, we see room for improvement. Although our previous analyses shows that the Agent is able to call the right tools to answer our question, the final output is still incorrect 2/3 times. This shows us we may need to provide more context to our model, either by using the prompt to elaborate on the columns the model should query or to provide the model with some query examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfUY-uJBlOuTHv4Az3Srzw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aafe7acb01c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extending context length windows for Large Language Models]]></title>
            <link>https://fukumaruuu.medium.com/extending-context-length-windows-for-large-language-models-25fee253f01c?source=rss-672c3458ffbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/25fee253f01c</guid>
            <category><![CDATA[natural-language-processi]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[littlereddotdata]]></dc:creator>
            <pubDate>Sun, 26 May 2024 04:14:23 GMT</pubDate>
            <atom:updated>2024-05-26T04:14:23.106Z</atom:updated>
            <content:encoded><![CDATA[<h3>Extending context length windows for Large Language Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*9Ts4jXUd2wVnVKrbtu9ElA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25fee253f01c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trustworthy AI frameworks in Asia — analysing China and Singapore’s published guidance for…]]></title>
            <link>https://fukumaruuu.medium.com/trustworthy-ai-frameworks-in-asia-analysing-china-and-singapores-published-guidance-for-3a276b632abb?source=rss-672c3458ffbe------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a276b632abb</guid>
            <category><![CDATA[data-governance]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[fairness-and-bias]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <dc:creator><![CDATA[littlereddotdata]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 08:12:55 GMT</pubDate>
            <atom:updated>2024-01-20T08:14:34.487Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trustworthy AI frameworks in Asia — analysing China and Singapore’s published guidance for Generative AI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2HnoINnGlZoVHa1lbXwI_g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pianodr023?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Michael Hart</a> on <a href="https://unsplash.com/photos/cars-near-building-t6Hd6ONYGrk?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p><em>This article represents a personal opinion only.</em></p><p><em>Many Generative AI governance frameworks have been published, with impliciations for a technology practitioners day-to-day work. This article distills the common areas of focus between these frameworks, and comments on what this means for the people, processes and technologies within the technology industry.</em></p><h3>An overview of the field globally</h3><p>In October 2023, US president Joe Biden signed an <a href="https://www.whitehouse.gov/briefing-room/presidential-actions/2023/10/30/executive-order-on-the-safe-secure-and-trustworthy-development-and-use-of-artificial-intelligence/">executive order</a> that outlined 8 principles and priorities for “the safe, secure, trustworthy development of Artificial Intelligence”. Similarly, the UK also released a <a href="https://www.gov.uk/government/publications/ai-regulation-a-pro-innovation-approach">whitepaper</a> proposing how the government should regulate Artificial Intelligence (AI).</p><p>Closer to home, Singapore also released a “<a href="https://aiverifyfoundation.sg/downloads/Proposed_MGF_Gen_AI_2024.pdf">Proposed Model Governance Framework for Generative AI</a>”, while China published their own <a href="https://digichina.stanford.edu/work/translation-measures-for-the-management-of-generative-artificial-intelligence-services-draft-for-comment-april-2023/">“Measures for the Management of Generative AI services”.</a></p><p>It’s only natural that many frameworks, from different countries, are being published rapidly. AI is a transformative technology that governments feel compelled to control and regulate. Indeed, the authors of all the frameworks acknowledge Generative AI’s “potential for both promise and peril”.</p><p>In their papers, the authors recognise the immense potential of AI to discover new medicines, improve public services and remove manual toil from workers. At the same time, they also acknowledge how Generative AI, trained as it is on data that unavoidably reflects societal biases, can also perpetuate existing inequalities and entrench misinformation.</p><p>As the author of The Pragmatic Engineer, Gergery Orosz phrases it, “in doubt that regulation would arrive for such an innovative, disruptive field as AI. The only question is how quickly it would happen”.</p><h3>What this means for practitioners</h3><p>As technologists, how we work and how we build tools for our users will be affected by these guidelines. Already, procurement departments who publish Request For Information questionnaires when onboarding a new platform or tool are asking about how an AI service can meet the fairness, anti-bias and data privacy requirements these frameworks ask for. Because of the increased need for data classification and lineage, data engineers will need to build in validation, tagging and monitoring into their pipelines more than ever.</p><p>To help you understand these incoming changes, this article distills the common areas of focus between these frameworks, with a special emphasis on the guidelines published by Singapore and China. We’ll see that there are many areas common to both frameworks. They all mention the importance of respecting an individual’s data rights, call on the need for more transparent and rigorously tested models, and draw out the need to build user awareness of how Generative AI will affect them.</p><p>Mostly though, these guidelines are, by themselves, too general to be effective. Most likely, it is an organization’s responsible parties, like Data Governance officers, who will have to translate these guidelines into specific practices around how a company manages its data and develops its models. This is something we will explore in future posts. We will examine how a company might implement these guidelines, from the data layer all the way to the application layer.</p><h3>Here are some key takeaways:</h3><p><strong>Emphasis on preserving the rights on an individual</strong></p><ul><li>Right to data privacy and fair model outputs</li></ul><p>Mentioned in both frameworks are how data, whether used to train a model or to get a model’s prediction, should be used in accordance with existing data privacy practices. A model’s output should also, as far as possible, not should not discriminate against certain classes of users.</p><p>In practice, this puts focus on data governance tools that typically manage data access controls, specify data privacy features and provide audit logging. Data governance is a large field in itself; suffice to say that Generative AI governance will only make the field more important.</p><p><strong>Stress on the need for more rigorously evaluated and transparent models</strong></p><p>Both frameworks emphasised the need for more control over the output of Generative AI models (through evaluation and testing) and more visibility into a models provenance (through tracking the model’s training data and model’s risks and limitations). In a way, this second point is related to the one on an individual’s data rights: only through rigorous evaluation and visibility can one guarantee that user rights are respected.</p><ul><li>Rigorous evaluation</li></ul><p>From an engineering point of view, there is a definite imbalance in this area. The tools for creating evaluation <strong>pipelines</strong> are more mature than the actual <strong>tests</strong> for evaluating a model’s robustness (for example how factual a model is or aligned it is to a society’s moral values). Existing CI/CD pipelines can integrate model evaluations by calling APIs such as <a href="https://mlflow.org/docs/latest/llms/llm-evaluate/index.html">MLflow LLM Evaluate API</a>. Before deployment, existing tools such as <a href="https://learn.microsoft.com/en-us/azure/devops/pipelines/process/approvals?view=azure-devops&amp;tabs=check-pass">Azure DevOps</a> allow for manual approvals in order for a CI/CD pipeline to succeed.</p><p>There are, however, few agreed-upon tests that measure a model’s factualness, tone, and, most importantly for users, relevancy. There are some frameworks, for example <a href="https://github.com/explodinggradients/ragas">RAGAS</a> and <a href="https://fine-grained-hallucination.github.io/">FAVA</a>, and of course the good old standby — having a human-in-the-loop- but a commonly-agreed upon metric does not exist.</p><p>In fact, this may even be the status quo for a long time. Generative AI can product different phrasings of the same answer, or answer a question equally factfully using different sources. In these subjective cases, definitive evaluation is hard.</p><p>Here, the amount of effort put into evaluating a model will come down to how “material” a model is, or the extent to which a model’s outputs affects a user. A model who determines financial products to recommend to a user will have a higher materiality than a model that converts a user’s profile picture into an avatar. Hence, the recommender model will need more scrutiny.</p><ul><li>Transparency</li></ul><p>Within this context, transparency refers to disclosing clearly how the model was made and what data was used to make it. The Singapore Model Goverance Framework gives a useful analogy here — “food labels”. For a certain food product, such as mayonnaise, food labels contain a list of the ingredients that make up a food product. A food label may also contain information on where the product was made and packaged and who its distributor is. Similarly, a Generative AI model should have information on the data used to train it, the model’s intended use, and its risks and limitations (<a href="https://aiverifyfoundation.sg/downloads/Proposed_MGF_Gen_AI_2024.pdf">source</a>). Consumers can then be more informed about the models that power the tools they use, from email to calendars to cars.</p><p>In practice, transparency is cannot be separated from good lineage tracking. Lineage tracking, in itself, can be broken down into two components. It can refer to tracking a model’s training data and inputs at inference time. It can also mean having visibility into the sub-components of a model. Implementing the former means having good dataset tagging practices, informative metadata and clear dataset descriptions. For the latter, tracing the flow of information through each of the model’s sub-components becomes important.</p><p>There are various ways model tracing might happen, but here is one example — to understand why a model is giving less than factual answers, a developer might comparing the relative accuracy of the retrieval step (where a model searches through documents for relevant information) versus the generation step (where a model uses relevant documents to generate a user response).</p><p>Tracing is something that has been extensively studied in other software engineering disciplines such as API observability. Some of the lessons from this disciplines, such as implementing trace graphs, have already made their way into open-source Large Language Model tracing tools such as <a href="https://langfuse.com/docs/langchain/python">Langfuse</a>, to promising results.</p><p>Adding good metadata to dataset, however, can be harder to tackle. Adding metadata like table descriptions has traditionally relied on manual effort, meaning that many tables in an organisation can go undocumented. A promising approach is to use Large Language models to automatically generate table descriptions, as <a href="https://www.databricks.com/blog/creating-bespoke-llm-ai-generated-documentation">Databricks has done</a>.</p><p><strong>Addresses the need for building user awareness</strong></p><ul><li><em>flag content created by Generative AI</em></li></ul><p>User awareness is another theme emphasised by both Generative AI governance frameworks. Both frameworks encourage the use of “watermarks” to delineate content that is generated by AI, and more broadly to inform consumers on the authenticity of the content they see digitally.</p><p>Flagging content as “AI-generated” goes some way towards addressing problems of misinformation. However, user awareness is a broader field than just preventing information misuse. It also includes other considerations, considerations such as helping users to more savvy about the technology they use. For example, users should made aware that recommendations they are seeing can lead to “filter bubbles”, where content they bookmark leads them to be recommended similar content. Users should also know that can control whether their timelines are algorithm-driven or simply timeline driven.</p><p>In this area, the biggest wins here will come from thoughtful user design. Useful frameworks have already been published for this, for instance <a href="https://pair.withgoogle.com/guidebook/patterns">Google’s People + AI Guidebook</a>. Design patterns, case studies and workshops will make a difference here.</p><h3>Conclusion</h3><p>Much of what these governance frameworks emphasise might seem self-evident. Principles like data privacy, detailed provenance and user awareness are features that every application should have. Yet in a regulatory landscape that’s still fragmented and susceptible to the third-party interests, reiterating these inviolable principles can be a form of reassurance. It’s also a reminder that because Generative AI technology affects how we make decisions and how we live, human values remain at its centre.</p><p><a href="https://aiverifyfoundation.sg/downloads/Proposed_MGF_Gen_AI_2024.pdf">Proposed Model Governance Framework for Generative AI</a></p><p><a href="https://digichina.stanford.edu/work/translation-measures-for-the-management-of-generative-artificial-intelligence-services-draft-for-comment-april-2023/">Measures for the Management of Generative AI services</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a276b632abb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>