<?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 Chai AI on Medium]]></title>
        <description><![CDATA[Stories by Chai AI on Medium]]></description>
        <link>https://medium.com/@chai-research?source=rss-f1cd6d559529------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HgC8Bxv43U5KXfuiFbo3gw.png</url>
            <title>Stories by Chai AI on Medium</title>
            <link>https://medium.com/@chai-research?source=rss-f1cd6d559529------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:06:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chai-research/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[Chai Guanaco: Lazy imports for fast Python web service cold-starts]]></title>
            <link>https://chai-research.medium.com/chai-guanaco-lazy-imports-for-fast-python-web-service-cold-starts-8cccb2dc7b2b?source=rss-f1cd6d559529------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cccb2dc7b2b</guid>
            <dc:creator><![CDATA[Chai AI]]></dc:creator>
            <pubDate>Wed, 16 Aug 2023 17:26:06 GMT</pubDate>
            <atom:updated>2023-08-16T17:26:06.004Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The following continues the series of blog posts on Guanaco, our internal service responsible for the submission, processing and serving of large language models (LLMs) to our app. Read the previous entry </em><a href="https://medium.com/@chai-research/chai-guanaco-deploying-llms-to-end-users-at-scale-c2e9c1462179"><em>here</em></a><em>!</em></p><h3>The problem</h3><p>Guanaco consists of several containerised Python web-services exposing a unified API to the outside world. Part of this API is responsible for processing user messages to their bots. Naturally, this service receives a large amount of concurrent requests and must therefore be load-balanced.</p><p>We achieve this by hosting Guanaco on the Cloud Run service offered by Google Cloud Platform. This cloud service runs our containers in a horizontally-scaled fashion (in fact, on a Kubernetes cluster), spinning up new containers of the same service on-demand in order to deal with fluctuations in traffic.</p><p>Recently, as we became more confident in the service, we started routing more traffic through Guanaco. We quickly noticed that the tail latencies of the service were degrading. After a closer look, we noticed that the Guanaco container was taking as much as 30 seconds to spin up! This is of course no good when trying to respond quickly to user messages. In particular, we expect that 70% of messages are served within 5 seconds, and 99% of messages in under 10 seconds (for messages that reach our larger more intensive models).</p><h3>Diagnosing the cause</h3><p>The first step in dealing with this problem always lies in reproducing it locally. This was actually more subtle than it sounds, as when I initially tried to do this, the Docker container took less than a second to launch on my machine 🤔</p><p>I started to play with the CPU and memory parameters passed to the container and found that with specs closer to that which Cloud Run serves, I was able to reproduce the long cold-start time.</p><pre>docker run --cpus=0.2 -m 1000m -it --rm -t guanaco-repo /bin/bash -c &quot;./start_guanaco.sh&quot;</pre><p>With this in hand I next set out to profile the start-up of the container. I had a hunch that there were probably some dodgy imports which were responsible for this. So I started the server up with the environment variable PYTHONPROFILEIMPORTTIME=1</p><p>This variable instructs Python to profile each and every single import when running a given script. Doing this revealed that up to 16 seconds were being spent loading imports from external dependencies!</p><p>This was not great as far as the chat API was concerned, as some of these imports were not even relevant to the code responsible for processing chats. They were only being used to process requests to other non-chat related endpoints. So these imports were delaying the fulfilment of bot messages, despite not being relevant for them.</p><h3>The solution</h3><p>In order to solve this, we decided to convert these imports to <strong>lazy imports</strong>. To be more precise, Python evaluates all global imports at runtime, recursively cascading through the import tree until all necessary packages have been imported. Lazy imports, on the other hand, are evaluated just-in-time.</p><p>As a first approach, one could fact import <em>anywhere</em> in Python, even inside functions. This in and of itself would solve the problem but, while it is considered Pythonic by manh, I did not find it to be a satisfying and clean solution. In addition, it is not DRY, requiring possibly multiple imports of the same package across multiple different functions.</p><p>I really longed for a solution that allowed me to maintain imports in the usual global scope, but just have them be lazily evaluated.</p><p>Thankfully, the package <a href="https://pypi.org/project/lazy-import/">lazy-import</a> does exactly that. With the following code placed in the repo’s __init__.py , for example, any import of the kubernetes package is evaluated only when the package is first invoked:</p><pre>import lazy_import<br>lazy_import.load_module(&quot;kubernetes&quot;)</pre><p>And that’s all that was required! After identifying the worst offending imports and lazy importing them in this way, I saw the average container start time on Cloud Run drop to roughly five seconds.</p><p>This drastically improved our tail latencies: no longer is the chatbot message queue building up waiting for containers to start. Rather, containers now spin up very fast and the various imports for a given container delayed until the other endpoint actually requiring them is invoked.</p><p>N.B. If desired, one could go even further here and automatically lazy_load all your package requirements by iterating over the entries of the usual requirements.txt and passing them to lazy_import.load_module.</p><p><em>Alex is a backend engineer at Chai. He has been writing software and contributing to various open-source projects for the better part of 15 years. He holds Masters and PhD degrees in Pure Mathematics from Cambridge and King’s College London respectively.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cccb2dc7b2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chai Guanaco: Deploying LLMs to end-users at scale]]></title>
            <link>https://chai-research.medium.com/chai-guanaco-deploying-llms-to-end-users-at-scale-c2e9c1462179?source=rss-f1cd6d559529------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2e9c1462179</guid>
            <dc:creator><![CDATA[Chai AI]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 19:38:47 GMT</pubDate>
            <atom:updated>2023-08-08T19:38:47.938Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploying language models is a fiddly business. It is one thing to spin up a server with a beefy GPU and start making single inference requests; but how do you scale this concept to hundreds of millions of inference requests a day? Is it possible to do this seamlessly and swiftly, and also to start receiving immediate human feedback from diverse audiences? In this series of blog posts we will offer a technical deep-dive into how our engineering team tackled these problems and, ultimately, how it paved the way for the world’s first user-evaluated LLM competition: Guanaco.</p><p><strong>Setting the scene</strong></p><p>To set the scene, let me first give you a high level introduction to our infrastructure here at Chai. Our frontend, the Chai app, is available on iOS and the Google Play Store, and currently serves roughly one million daily active users. Powering this behind the scenes, we host a myriad of containerised Python microservices on Google Cloud Platform. These RESTful microservices are all each responsible for the various different features found on the app.</p><p>Arguably the most important service we host is our bot response service: the program that is ultimately responsible for parsing user messages to bots, and forwarding them to our models for inferences. These models are hosted on an impressive 700-GPU-strong Kubernetes cluster hosted by the good folks at CoreWeave.</p><p>Managing and maintaining such a cluster is a full-time job in-and-of itself (and we’re hiring!). Designing a system which can quickly and automatically launch new models to the cluster, and make them immediately available, requires a thoughtful approach.</p><p><strong>The high-level approach</strong></p><p>When we first set out on this idea, we started by setting our constraints which included:</p><ul><li>Models should be deployable, without manual intervention, by anyone familiar with Python.</li><li>Model developers should start receiving their first user-feedbacks within roughly five minutes of submission.</li><li>The user experience must be seamless: choosing to switch to a Guanaco model should incur no latency penalties or other such poor UX.</li><li>The service must be maintainable by a team of no more than three engineers (after all, we’re a company of less than ten people!)</li></ul><p>It became clear very quickly that to achieve this, especially with our engineering head-count, we had to apply a principled approach. Ultimately, for us, this means a heavy and judicious use of test-driven development (TDD). Coming from a quantitative-trading background this felt like a very natural approach as, in that domain, poor test coverage in any one area of the code could incur extremely heavy financial losses.</p><p>We thus began with an overarching end-to-end test, which starts with the developer submitting her model, and ends with an assertion that within 5 minutes she has received her first feedback. With this failing test in hand, we then started to flesh out the submission and deployment system one failing unit test at a time.</p><p>While not a proper web-development project per se, we also drew heavy inspiration from familiar web-development principles such as the Model-View-Controller framework (MVC) and Object Relational Mapping (ORM). I personally feel that using these guiding principles has helped to ensure that we build a trustworthy system that is both scalable and easily maintainable.</p><p><strong>Nitty-gritty details</strong></p><p>Diving now into the more technical details, let me describe to you the journey of a language model (LLM) through the Guanaco service. An LLM will start-off its life as a fine-tune of some foundational model (usually Meta’s Llama), hosted on the popular model-storage platform HuggingFace.</p><p>Via our pip package, chai-guanaco, a developer can submit his model via one easy command, which prompts the Guanaco service to launch a submission job.</p><p>This job records some metadata to a database, but then very quickly begins the model preprocessing stage. This involves downloading the LLM from HuggingFace, running some sanity-checks, and then serialising it with the very cool package tensorizer, written by engineers at Coreweave. This serialised model is then uploaded to CoreWeave’s regional cache, which is a specialised Amazon S3 service built to ensure incredibly fast access to models from their various datacenters.</p><p>Once this stage is complete, which takes no longer than two to three minutes, we then publish a new inference service manifest to our Kubernetes cluster, instructing it to launch our model inference server code and serve the submitted model.</p><p>Our inference server code is based heavily off the excellent open-source package vLLM. Together with some in-house optimisations and integrations with our S3 cache, this inference service is usually ready to start serving requests in under two minutes.</p><p>In principle, the model is now ready to serve. However, to ensure the best experience for our users, we run various stress-checks against it, verifying that the model’s inference latencies fall within an acceptable range for the end-user.</p><p>Once this is complete, the model is published to the outside world, its status updated to “deployed” and the app’s backend code kicks in.</p><p>Whenever a user decides to start a new conversation in our so-called “beta-mode” (after consenting to share their conversation), our bot response services queries the Guanaco service to understand which models are in need of feedback. It chooses a model (usually those which have been submitted most recently) for the user to chat with.</p><p>After a certain amount of messages, or when backing out of the conversation, the user is prompted to give a thumbs-up rating and some plaintext feedback. This feedback is then routed to our feedback microservice which categories all the feedback the individual models have collected. Once this finds its home in the database, our model developers can easily view it, along with the anonymised conversation, via the chai-guanaco pip package.</p><p><em>Alex is a backend engineer at Chai. He has been writing software and contributing to various open-source projects for the better part of 15 years. He holds Masters and PhD degrees in Pure Mathematics from Cambridge and King’s College London respectively.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2e9c1462179" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chai-GPT. RLHF Part I: Reward Modelling]]></title>
            <link>https://chai-research.medium.com/chai-rlhf-part-i-reward-modelling-8934871d28e9?source=rss-f1cd6d559529------2</link>
            <guid isPermaLink="false">https://medium.com/p/8934871d28e9</guid>
            <dc:creator><![CDATA[Chai AI]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 23:25:20 GMT</pubDate>
            <atom:updated>2023-08-08T21:08:59.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXooQB6mwAyqRIeFpadkxQ.png" /></figure><p>Full results published in: <a href="https://arxiv.org/pdf/2303.06135.pdf">https://arxiv.org/pdf/2303.06135.pdf</a></p><p>Our own large language models (LLMs) are the foundation of <a href="https://onelink.to/kqzhy9">chai</a>. A platform for chat AI. Improving our LLMs directly translates to better user experiences, engagement and retention of our entire platform.</p><p>In this series of blog posts, we will offer a technical deep-dive into exactly how Chai implements Reinforcement Learning with Human Feedback (RLHF) pipeline, directly improving user retention by over 30%.</p><p><strong>RLHF Overview</strong></p><p>Reinforcement learning from human feedback (RLHF) was initially introduced in <a href="https://arxiv.org/pdf/2203.02155.pdf">this paper</a> in 2022 by OpenAI and has gained popularity with the recent release of ChatGPT. RLHG involves training multiple models at different stages, which typically include pre-training a language model, training a reward model, and fine-tuning the language model with reinforcement learning. This process is depicted in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INVcZKi5uX1WaPzplVr_vQ.png" /><figcaption>source: <a href="https://arxiv.org/pdf/2203.02155.pdf">https://arxiv.org/pdf/2203.02155.pdf</a></figcaption></figure><p><strong>Chai’s Internal Reward Modelling via Pseudo Labels</strong></p><p>People come to Chai for engaging conversations, storytelling, and roleplay, which is quite different from OpenAI’s ChatGPT. To train a reward model using supervised learning, one requires labelled data. Manual annotations are not only costly, but in this case, they are also inaccurate and biased. It’s more challenging to determine whether a response is engaging compared to determining its accuracy or helpfulness.</p><p>We therefore propose pseudo labels that can be conveniently extracted from user interactions, where the labels directly mark whether a given response is engaging or not.</p><p>As there most likely is no <em>single metric</em> which defines how engaging a response is, we invert the problem and look into <em>what makes a response bad</em>. Specifically:</p><ul><li>End of conversation: Did the model send a message which resulted in the end of a conversation?</li><li>Retry: Did the user regenerate the message from the model after they’ve seen it?</li><li>Edit: Did the user edit the response? (This typically means the user is very frustrated as they have re-tried the message multiple times)</li><li>Star rating (this is not a negative signal): How much did the user like the message they’ve seen</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XM25RiA-ohc1VPUCM0aSxw.png" /></figure><p>With over 70 million model responses served per day, we found around 20% of the responses were re-tried, 3% of the messages were edited, 1% of the messages were rated by the user, and each conversation roughly has 11 model responses. This means, each day, we produce:</p><ul><li>14 million retry signals</li><li>2.1 million edit signals</li><li>700K star ratings</li><li>6 million end-of-conversation signals</li></ul><p>During data collection, we simply sample these signals across different dates and different model types served. This resulted in a dataset with 170 million rows. Each row contains model input/output along with the signal (binary for retry/edit/end-of-conversation).</p><p><strong>Model training</strong></p><p>There are several ways to train a reward model, given we have multiple signals, one can consider two different approaches:</p><ol><li>Multiple reward ensemble: where we train one reward model for each signal, these outputs are then aggregated (i.e. simple sum) in order to obtain the final reward value.</li><li>Reward with signal ensemble: where we have a single model, but trained on some joint targets of these signals.</li></ol><p>We have experimented with both methods and discovered multiple reward ensemble yields no significantly better result at the cost of complexity during production. Therefore we chose the second approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x5Mm_PBSKq27ng-wPVLAMA.png" /><figcaption>Chai Reward Model Architectures / Targets</figcaption></figure><p>The reward model architecture we have chosen is <a href="https://huggingface.co/gpt2">GPT2</a> and <a href="https://huggingface.co/docs/transformers/model_doc/roberta">RoBERTa</a>, with the number of parameters between 82M and 355M. As text classification is inherently less complex than text generation, we saw no benefit in using extra-large models such as GPT-J 6B for such a task.</p><p><strong>Best-of-N sampling</strong></p><p>After the reward model is trained, we can simply utilize rejection (best of N sampling) in production, i.e. for each model input, we generate N responses. The model input is concatenated with the responses and they are run through the reward model. Finally, we select the response with the highest reward score. In part II of the blog post, we will show case how we utilize reinforcement learning to achieve the best of N performance via a single model pass-through.</p><p><strong>Results</strong></p><p>Our north star metric is user retention, defined by the percentage of new users who joined on day 0, and send at least 1 message on day 30. As this metric is <em>expensive </em>to obtain (as it may hurt user experience if a bad model is deployed and tested), we have an approximate metric called <em>mean conversation length (MCL), </em>which averages over the total number of model responses within each conversation per test group.</p><p><strong>Dataset size VS. MCL</strong></p><p>In this experiment, we vary the amount of data used during model training. From ~10K examples all the way to ~60M examples. We directly observe the scaling law (i.e. the log-linear relationship between model performance and dataset size). We also observe by tuning the hyper-parameters of the base model, we obtain a delta performance improvement in model performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sGoubv9usoJr7a3GenN6g.png" /><figcaption>Mean conversation length (MCL) improvement over dataset size</figcaption></figure><p><strong>Exogenous parameters VS. MCL</strong></p><p>There are a couple of key exogenous parameters that can be tuned. These are a bit different from hyper parameters as they are not model-specific. We observe by tuning the context window length, there is very marginal improvement in performance. So is tuning K (defining end of conversation, i.e. remaining responses before the termination of a conversation).</p><p>There is a log-linear relationship between performance and the number of samples drawn during rejection sampling. Unfortunately, we could not feasibly test best-of-32 and above as they induce too much latency on the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XW7qwV5Fz14n-cvAnatBQ.png" /></figure><p><strong>User retention testing</strong></p><p>Finally, by selecting the best hyper parameters, we observe that a joint target of retry and end of conversation achieves the best performance. Yielding over 30% improvement against the baseline!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kpp21f1_3IeF4aiRu1n-mg.png" /></figure><p><strong>Conclusion</strong></p><p>In this work, we focus on developing chatAIs that are highly engaging and entertaining for users. We demonstrate through extensive A/B tests across large user groups that training reward models with human feedback followed by response selection, leads to chatAIs with longer average user interactions and higher user retention. We propose intuitive evaluation metrics, namely the mean conversation length and user retention, and investigate a range of pseudo labels that can be used to identify captivating responses that can be used to train a reward model that can score generated responses. Using our best reward model for response selection, we show that the user retention of a GPT-J 6B language model increases by over 30%, highlighting the effectiveness of using natural human-chatbot interactions for developing highly engaging chatAIs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8934871d28e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>