<?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 Jasper Van den Bossche on Medium]]></title>
        <description><![CDATA[Stories by Jasper Van den Bossche on Medium]]></description>
        <link>https://medium.com/@jasper.van.den.bossche?source=rss-bd85a1880b2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Jasper Van den Bossche on Medium</title>
            <link>https://medium.com/@jasper.van.den.bossche?source=rss-bd85a1880b2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 05:32:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jasper.van.den.bossche/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[Unlocking Custom Large Language Models Using Bedrock Fine-Tuning]]></title>
            <link>https://medium.com/ml6team/unlocking-custom-large-language-models-using-bedrock-fine-tuning-e13a19320805?source=rss-bd85a1880b2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e13a19320805</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[bedrock]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[aws-bedrock]]></category>
            <dc:creator><![CDATA[Jasper Van den Bossche]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 12:50:35 GMT</pubDate>
            <atom:updated>2024-10-29T12:50:35.941Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G1_ZU7V4mrTcyePqAYtqhw.png" /></figure><p>One of the projects we are working on involves generating code for a custom dialect of a programming language using a large language model (LLM). With a dataset of instructions and their corresponding implementations, we aim to fine-tune a model to automate this process. Given the rapid advancements in AI, fine-tuning LLMs can significantly enhance their performance for specific tasks, offering tailored solutions that generic models might not provide.</p><p>In our pursuit to fine-tune this model, we turned to AWS Bedrock. AWS Bedrock offers a fully managed, user-friendly environment for training and deploying custom models, making it an attractive choice for our experimentation and development needs. Its promise of streamlined integration and robust infrastructure seemed ideal for our use case. In this blog post, we’ll delve into the journey of fine-tuning an LLM with AWS Bedrock. We’ll explore the platform’s standout features that facilitated our project and discuss the challenges we faced along the way.</p><h3><strong>Browsing the Catalogue: Choosing a Model and Configuring the Setup</strong></h3><p>When fine-tuning a Large Language Model (LLM) for a specific task, the first crucial decision is selecting the right model. During our exploration of AWS Bedrock’s documentation, we discovered that the platform currently supports only a limited selection of <a href="https://docs.aws.amazon.com/bedrock/latest/userguide/custom-model-supported.html">four LLMs</a> for fine-tuning. Despite this limitation, there are variants within these models, such as the 13B and 70B versions of Llama2, and the lightweight and normal versions of Cohere’s Command model. You’ll also need to request access to the model, which is standard practice in Bedrock. We chose to start our adventure with Cohere’s Command Light model, a smaller to model to minimize the cost and latency where we hoped that fine-tuning would be powerful enough to meet our goals in terms of quality.</p><h3>Availability</h3><p>Another aspect to consider is the regional availability of custom models. At the time writing, AWS Bedrock only offers these custom models in three US regions. This restriction can pose challenges, especially for organizations that must comply with data residency regulations, such as those within the EU or other regions with specific data handling requirements. We are quite certain AWS is working on rolling out the service in other regions, but for now keep in mind that the service is only available in US regions.</p><h3>Preparing the Training Dataset</h3><p>Now that we have decided on a model, it is time to start our fine-tuning mission. The first step in the process is to create a dataset in a predefined format. Specifically, you need a JSONL file where each record contains a prompt and a completion key that both map to a string.</p><ul><li><strong>Prompt:</strong> Contains the question or task that the LLM needs to answer or solve.</li><li><strong>Completion:</strong> Contains the expected answer or solution from the LLM.</li></ul><p>In supervised learning terms, the prompts are the “features”, and the completions are the “labels”.</p><p>To give you an idea of what a record in our dataset looks like, here’s an example. Note that we have used Python instead of our proprietary programming language dialect to protect our client’s confidential information:</p><pre>{<br> &quot;prompt&quot;: &quot;You are given the following task that needs to be solved using the Python programming language:\\n\\nWrite a function that extracts all links that can be found in an HTML snippet. The input of the function is a string that contains HTML, the output is a list of URLs in string format. Make sure your code is easy to understand and well-documented.&quot;,<br> &quot;completion&quot;: &quot;Here&#39;s a possible solution to the task:\\n\\n```python\\nfrom bs4 import BeautifulSoup\\nimport re\\n\\ndef extract_links(html):\\n    # Create a BeautifulSoup object from the HTML\\n    soup = BeautifulSoup(html, &#39;html.parser&#39;)\\n    # Find all the &lt;a&gt; tags in the HTML\\n    links = soup.find_all(&#39;a&#39;)\\n    # Extract the href attribute from each &lt;a&gt; tag\\n    urls = [link.get(&#39;href&#39;) for link in links]\\n    # Filter out any URLs that don&#39;t start with http or https\\n    urls = [url for url in urls if url and re.match(&#39;^https?://&#39;, url)]\\n    return urls\\n```\\n\\nThis function works by first creating a BeautifulSoup object from the input HTML string. It then uses the `find_all` method of the BeautifulSoup object to find all the `&lt;a&gt;` tags in the HTML. It then extracts the `href` attribute from each `&lt;a&gt;` tag using the `get` method, and stores the results in a list. Finally, it filters out any URLs that don&#39;t start with `http` or `https` using a regular expression, and returns the resulting list of URLs.&quot;<br>}</pre><p>We’ll leave it up to you to choose your favourite data engineering tooling to build an ETL pipeline to create a dataset, or simply write a script to process and prepare your own dataset. Once you have your dataset ready, you need to store the JSONL file on an S3 bucket. With that, you’re ready to move on to the fine-tuning process on AWS Bedrock.</p><h3>Running a Training Job</h3><p>Now we arrive at the most exciting part of the Bedrock fine-tuning journey: fine-tuning a model on our own dataset. You can start a training job from the AWS Management Console UI or by using AWS client libraries in your favorite programming language. We’ll opt for the latter and implement a Python script, which offers several advantages:</p><ul><li><strong>Automation:</strong> You can automate the training process, making it easier to run multiple experiments.</li><li><strong>Repeatability:</strong> Scripts ensure that the training setup is consistent every time you run it.</li><li><strong>Integration:</strong> You can integrate the training process with other parts of your MLOps setup.</li></ul><p>Our fine-tuning script looks as follows:</p><pre>import os<br>import argparse<br>import logging<br>from datetime import datetime<br>​<br>import boto3<br>​<br># Set up logging<br>logging.basicConfig(level=logging.INFO)<br>​<br>AWS_PROFILE = os.environ.get(&#39;AWS_PROFILE&#39;)<br>CUSTOM_MODEL_NAME = os.environ.get(&#39;CUSTOM_MODEL_NAME&#39;)<br>BASE_MODEL_IDENTIFIER = os.environ.get(&#39;BASE_MODEL_IDENTIFIER&#39;)<br>TRAINING_DATA_S3_URI = os.environ.get(&#39;TRAINING_DATA_S3_URI&#39;)<br>OUTPUT_DATA_S3_URI = os.environ.get(&#39;TRAINING_DATA_S3_URI&#39;)<br>​<br>if __name__ == &quot;__main__&quot;:<br>   # NOTE we use SSO on AWS for authentication<br>   # The authentication might differ a bit depending on your setup<br>   # Check the official AWS documention for more information<br>​<br>   # Create a session using the specified AWS profile<br>   session = boto3.Session(profile_name=AWS_PROFILE)<br>​<br>   # Create a client for the Bedrock service<br>   bedrock = session.client(service_name=&#39;bedrock&#39;)<br>​<br>   # Get the account ID<br>   account_id = session.client(&#39;sts&#39;).get_caller_identity()[&#39;Account&#39;]<br>​<br>   # Generate a unique job name using the current date and time<br>   datetime_string = datetime.now().strftime(&quot;%Y%m%d%H%M%S&quot;)<br>​<br>   try:<br>       # Launch the fine-tuning job<br>       response_ft = bedrock.create_model_customization_job(<br>           jobName=f&quot;{datetime_string}-fine-tune-job&quot;,<br>           customizationType=&quot;FINE_TUNING&quot;,<br>           roleArn=f&quot;arn:aws:iam::{account_id}:role/BedrockFineTuning&quot;,<br>           hyperParameters={<br>               &quot;epochCount&quot;: &quot;5&quot;,<br>               &quot;batchSize&quot;: &quot;8&quot;,<br>               &quot;learningRate&quot;: &quot;.001&quot;,<br>           },<br>           trainingDataConfig={&quot;s3Uri&quot;: TRAINING_DATA_S3_URI},<br>           outputDataConfig={&quot;s3Uri&quot;: OUTPUT_DATA_S3_URI},<br>           customModelName=CUSTOM_MODEL_NAME,<br>           baseModelIdentifier=BASE_MODEL_IDENTIFIER<br>       )<br>​<br>       # Log the job ARN<br>       job_arn = response_ft.get(&#39;jobArn&#39;)<br>       logging.info(f&quot;Launched fine-tuning job with ARN: {job_arn}&quot;)<br>   except Exception as e:<br>       # Log any errors that occur<br>       logging.error(f&quot;Error launching fine-tuning job: {e}&quot;)</pre><p>The script authenticates with AWS using the specified AWS profile, creates a client for the Bedrock service, generates a unique job name, and launches a fine-tuning job using the Bedrock client. The fine-tuning job is configured to automatically load the specified dataset from an S3 bucket and write the outputs to a specified location on an S3 bucket. The IAM role required by the script needs permission to read and write to the specified S3 buckets. The script also includes error handling and logging to help with debugging and monitoring.</p><p>Run the script, and a fine-tuning job will be created on Bedrock. We recommend having something else to do in the meantime, as the job can take quite some time to finish. In our case, the training job took roughly 35 minutes. You can check the Bedrock UI for the status of the job. Once the job successfully finishes, the outputs will be stored in the specified bucket, and you are ready to deploy your custom model.</p><h3>Training Job Outputs</h3><p>Once a training job is finished, you will find two subdirectories in the output directory you specified in the training job: training_artifactsand validation_artifacts. Within each of these directories, you will find a metrics file:</p><ul><li>step_wise_training_metrics.csv: Contains the training loss for each step during training. Each row represents a single step in the training process, and the ‘training_loss’ column contains the loss value for that step. A decreasing training loss indicates that the model is learning and fitting the training data well.</li><li>validation_metrics.csv: Contains the validation loss for each step during training. Each row represents a single step in the training process, and the ‘validation_loss’ column contains the loss value for that step. The validation loss measures how well the model performs on unseen data, providing an estimate of its generalization ability. Ideally, the validation loss should decrease and stabilize, indicating good model performance on new data.</li></ul><p>You can easily plot these files to gain insights into whether your training job was successful and perform hyperparameter tuning to optimize your fine-tuning task. Once you are happy with the results of the training job, you can move on to the next steps: deploying and testing the fine-tuned model. Below is a simple script to plot the results:</p><pre>import os<br>​<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>​<br>training_metrics_file = os.environ.get(&#39;TRAINING_METRICS_FILE&#39;)<br>validation_metrics_file = os.environ.get(&#39;VALIDATION_METRICS_FILE&#39;)<br>​<br># Load the training data<br>training_data = pd.read_csv(training_metrics_file)<br>​<br># Load the validation data<br>validation_data = pd.read_csv(validation_metrics_file)<br>​<br># Create a line plot for the training loss<br>plt.plot(training_data[&#39;step_number&#39;], training_data[&#39;training_loss&#39;], label=&#39;Training Loss&#39;)<br>​<br># Create a line plot for the validation loss<br>plt.plot(validation_data[&#39;step_number&#39;], validation_data[&#39;validation_loss&#39;], label=&#39;Validation Loss&#39;, linestyle=&#39;--&#39;)<br>​<br># Add labels and title<br>plt.xlabel(&#39;Step Number&#39;)<br>plt.ylabel(&#39;Loss&#39;)<br>plt.title(&#39;Training and Validation Loss over Steps&#39;)<br>​<br># Add a legend<br>plt.legend()<br>​<br># Show the plot<br>plt.show()</pre><h3>Understanding Costs of Custom Models</h3><p>Once your training job is complete, your new custom model will appear in the custom models tab. Before you can test or use your newly fine-tuned model, it’s important to understand the costs associated with deploying it.</p><h4>Provisioned Throughput</h4><p>In the context of model serving, provisioned throughput refers to the pre-allocated capacity to handle a specific inference throughput. This ensures that the serving infrastructure can manage the expected load without latency issues, guaranteeing predictable performance for real-time inference. However, it may incur higher costs if the provisioned capacity is not fully utilized.</p><p>The rates for custom models are the same as their base models. You can either purchase provisioned throughput with a commitment or without a commitment. Purchasing without a commitment means that you will be billed hourly, while purchasing with a commitment means that you’ll purchase compute for 1–6 months. Check the<a href="https://aws.amazon.com/bedrock/pricing/"> pricing table</a> for a clear overview of the prices per model.</p><h4>Cost Considerations</h4><p>You might think that only offering provisioned throughput is an easy money grab by AWS. However, keep in mind that a custom model can only be used by you. AWS cannot quickly swap out the weights of a base model they offer through an API for a single request from you. That would be dramatic for the performance of their offering, so they need to spin up infrastructure that runs your custom model. Hence, offering custom models through provisioned throughput does make sense.</p><p>This, of course, comes with the implication that Bedrock fine-tuning may not be cost-effective for applications with very low throughput, as you will essentially pay a lot of money to host infrastructure that isn’t optimally used. Therefore, we would recommend you take a look at Sagemaker’s offerings. Philipp Schmid, Technical Lead at Hugging Face, has an excellent<a href="https://www.philschmid.de/sagemaker-train-evalaute-llms-2024"> blogpost</a> on fine-tuning on Sagemaker.</p><h3>Deploying Our Custom Model</h3><p>Once you have purchased provisioned throughput for your custom model, your model will be automatically deployed. You can check the Bedrock UI for status updates. Once deployed, you can invoke your custom model by sending an HTTP request to the API or by using a client library, such as Python. Remember to monitor your model’s usage and manage your provisioned throughput accordingly. If you are purchasing provisioned throughput without a commitment, make sure to shut down your instances when you are not using your models to avoid unexpectedly high cloud bills.</p><h4>Let’s Do Some Hands on Testing</h4><p>After some hyper parameter tuning and a couple of training runs we saw some promising results in our metrics, which means it’s time for some real world testing. After all, numbers tell you a lot, but testing how good an LLM actually works for your use case means that you’ll need some human evaluation. After purchasing provisioned throughput, our model is deployed and becomes available to interact with. To help us in our testing efforts we created a small streamlit UI:</p><pre>import json<br>import os<br>​<br>import boto3<br>import streamlit as st<br>​<br># Title of the app<br>st.title(&quot;Code Generator&quot;)<br>​<br># Input text area for the user to paste their code snippet<br>task = st.text_area(&quot;Enter your task below:&quot;, key=&quot;task&quot;)<br>​<br>aws_profile = os.environ.get(&quot;AWS_PROFILE&quot;)<br>provisioned_model_arn = os.environ.get(&quot;MODEL_ARN&quot;)<br>session = boto3.Session(profile_name=aws_profile)<br>boto3_bedrock = session.client(&quot;bedrock-runtime&quot;)<br>​<br># Button to send the code snippet to the server<br>if st.button(&quot;Generate code&quot;):<br>   accept = &quot;application/json&quot;<br>   contentType = &quot;application/json&quot;<br>   body = json.dumps({<br>       &quot;prompt&quot;: task,<br>       &quot;temperature&quot;: 0.1,<br>   })<br>   try:<br>       response = boto3_bedrock.invoke_model(<br>           body=body,<br>           modelId=provisioned_model_arn,<br>           accept=accept,<br>           contentType=contentType<br>       )<br>       response_body = json.loads(response.get(&quot;body&quot;).read().decode(&quot;utf-8&quot;))<br>       generated_code = response_body.get(&quot;generations&quot;)[0].get(&quot;text&quot;)<br>       st.code(generated_code)<br>   except Exception as exception:<br>       st.exception(exception)</pre><p>The app contains a text area where we can write our prompt, in our case we will ask it to generate code to solve a given problem. Once you click the submit button, this prompt is then sent to our custom model using the Python Bedrock client. The client itself is straightforward to use, you provide a request body which contains the prompt and optionally some model parameters, the id of your model in the form of the ARN string. Once the model returns its output, it is parsed and displayed in a code field for evaluation.</p><h3>Conclusion</h3><p>In this blog post, we explored the process of fine-tuning Large Language Models (LLMs) on AWS Bedrock. We were initially drawn to Bedrock’s low barrier to entry, which allows you to build custom models with minimal setup. By preparing a dataset in a predefined format and storing it on an S3 bucket, you can launch a fine-tuning job that uses your dataset to fine-tune a preconfigured model. Upon completion, you receive a detailed report with training and validation metrics stored on a configured S3 bucket.</p><p>Once you are satisfied with the metrics, you can purchase provisioned throughput to deploy your model and start using it. However, it’s important to note that the requirement for provisioned throughput makes Bedrock fine-tuning less suitable for smaller use cases. For such scenarios, Amazon Sagemaker might be a more cost-effective option.</p><p>Despite these considerations, AWS Bedrock shows great promise as part of AWS’s generative AI offerings. The core fundamentals are well-documented and implemented, making it a robust choice for larger-scale applications. We look forward to seeing new models being added to the service and its availability expanding to more regions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e13a19320805" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ml6team/unlocking-custom-large-language-models-using-bedrock-fine-tuning-e13a19320805">Unlocking Custom Large Language Models Using Bedrock Fine-Tuning</a> was originally published in <a href="https://medium.com/ml6team">ML6team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Need a GenAI Gateway]]></title>
            <link>https://medium.com/ml6team/why-you-need-a-genai-gateway-8c4dc35dac9b?source=rss-bd85a1880b2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c4dc35dac9b</guid>
            <category><![CDATA[ai-platform]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[gateway]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Jasper Van den Bossche]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 08:37:47 GMT</pubDate>
            <atom:updated>2024-10-07T08:37:47.810Z</atom:updated>
            <content:encoded><![CDATA[<p>Generative AI is ubiquitous these days, and organizations are rapidly integrating GenAI into their business processes. However, building GenAI applications comes with its own set of specific challenges. The models are often large, meaning inference costs for running these models can quickly get out of hand, and model selection often requires balancing performance against costs and latency. Other common challenges include the misuse of generative models or data leakage. While implementing measures such as rate limiting, monitoring, and guardrailing in your GenAI applications can help overcome these problems, doing so for every individual project brings significant overhead for your engineering teams. It also becomes easy to lose track of global usage of generative AI within your organization and leads to many cases of reinventing the wheel as teams solve the same problems over and over again.</p><p>An alternative approach that’s quickly becoming more popular is the creation of a <strong>centralized platform to manage access to GenAI models, track usage, implement security measures, and more</strong>. Such an AI platform consists of infrastructure and technical building blocks that can be used by other teams in the organization, as well as a team that is responsible for maintaining this platform and ensuring it serves the needs of the teams that use it. The goal is to enable teams across the organization to build GenAI projects, while centralizing the required governance. In this article, we will focus mostly on the technical side of the platform and specifically one of the central components, a GenAI Gateway.</p><p>The main idea behind an GenAI Gateway is to provide an interface that allows other teams to make use of AI models in a way that lowers the barrier to entry, deduplicates engineering effort, centralizes governance and observability for AI projects across your organization. Through this centralized interface, it becomes possible to manage quotas, costs, infrastructure, third-party API access, and other aspects as a platform capability across the organization in a unified way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/0*t_zquTauO6-g7DcE" /></figure><p>The concept of a GenAI gateway is central to the platform idea. Inspired by API gateways commonly used in microservice architectures, a GenAI gateway serves as a software layer between your applications and your generative models. This provides an opportunity to connect governance and observability tooling to the model requests, as well as optimizations such as caching. It also allows the abstraction of the certain technical details of model calls, allowing users to switch between heterogeneous models and serving setups with little effort.</p><p>From an architectural perspective, the GenAI Gateway is located in between the platform consumers and the hosted models. It offers API functionality to request available models from the model registry, and make calls to these models, with all the requests passing through governance and observability layers (authentication and access management, quota management, logging). On the backend side, it interacts with the model registry and model serving infrastructure. More sophisticated implementations can offer other AI services such as managed vector database access.</p><h3>Do We Really Need a Gateway Specifically for LLMs?</h3><p>At first glance, one might assume that building an API gateway and connecting model providers’ APIs and self-hosted inference servers would be sufficient to solve our problems. While API gateways offer a lot of helpful functionality, there are specific features that set a GenAI gateway apart from a traditional API gateway. Just like the MLOps paradigm builds on DevOps principles to solve challenges specific to deploying ML applications, a GenAI gateway extends the API Gateway concept to offer solutions to challenges specifically encountered in GenAI applications.</p><p><strong>A Flywheel for AI Acceleration in the Organization</strong></p><p>By close collaboration between the teams serving the use cases and the platform team developing the gateway, it becomes possible to create service interfaces that can be written once and reused across teams. Once the gateway is set up for a particular model (or model provider), a new team with a similar need should be able to seamlessly integrate the GenAI gateway in their product tech stack, without having to spend time to figure out custom deployments, provider licensing, monitoring or other technical aspects that are handled the gateway. New functionalities can and should be added in lock-step with growing demands from the teams, focusing on the feature work that represents the greatest output multiplier in terms of other use cases benefiting from them.</p><p><strong>Seamless Model Swapping</strong></p><p>GenAI is a quickly evolving field with providers rapidly releasing new models, which means that the model you deploy today is likely to be outperformed by a newer model in just a matter of weeks or months. Alternatively, a smaller or more cost-effective model might be released, offering the potential to reduce costs and latency. If this model is from a different provider, switching costs might be prohibitive on the scale of a single project. Therefore, it is crucial to be able to swap out models via a central interface, without having to update each application that consumes them.</p><p>A centralized GenAI gateway addresses this need. Instead of modifying the inference call in each of your applications, you only need to update the GenAI gateway once. The gateway then handles the necessary routing and transformation of the API call on the backend and sends it to the appropriate provider. This centralized approach simplifies the process of keeping your applications up-to-date with the latest and most efficient models, ensuring that you can quickly adapt to advancements in generative AI technology.</p><p><strong>Managing the High Costs of Generative AI</strong></p><p>Generative models, particularly large language models (LLMs), are notoriously resource-intensive. They require powerful GPUs or other accelerators to maintain reasonable inference latency and throughput. This substantial computational power comes at a significant cost, making it essential to implement rate-limiting measures or restrict access to certain models altogether. However, estimating the costs for LLM usage is not as straightforward as one might think.</p><p>To account for this variability, model providers typically charge based on the number of input and output tokens consumed. This pricing model reflects the underlying computational complexity and makes it crucial to monitor and log token usage to gain insights into how the models are utilized. Implementing cost guardrails alongside monitoring can help manage and optimize your expenditure effectively, ensuring that you stay within budget while leveraging the power of generative models.</p><p>In the case of self-hosted models, centralizing the deployment infrastructure allows for more optimal utilization and scaling strategies of model servers, next to better cost management.</p><h4>With Great Power Comes Great Responsibility</h4><p>Large Language Models (LLMs) are extremely powerful tools, but they can also be easily misused. Vulnerabilities such as prompt injection and sensitive information disclosure can pose significant security risks to your organization.</p><p>In a prompt injection attack, an attacker attempts to manipulate the LLM to return outputs it shouldn’t be able to by tweaking prompts to circumvent built-in measures. This type of attack can lead to severe reputation damage in public-facing GenAI applications that lack proper safeguards.</p><p>Another major threat is the handling of data access by LLMs. While LLMs are incredibly powerful on their own, their full potential is often unleashed when connected to your data. The technique, known as retrieval-augmented generation, involves a retriever first searching for relevant documents within your data lake (often pre processed and stored in vector databases to allow for semantic search of relevant documents). If this data access is not properly configured, a user might be able to misuse the LLM to access data they are not authorized to. This can be particularly dangerous when the application is public-facing.</p><p>Furthermore, it is often desirable to screen for other undesirable inputs or outputs, such as toxicity, model hallucination, or other inappropriate content.</p><p>Avoiding misuse and ensuring the secure use of generative AI is a key part of a successful rollout of generative AI within the organization. Generative AI comes with its own set of security challenges that must be handled appropriately. Addressing these topics in a centralized way makes sense since these concerns cut across use cases.</p><h4>Playground</h4><p>Having a centralized platform also provides an opportunity to offer users an <em>AI Playground</em> on top of the gateway<strong>. </strong>This is an application with a Web UI where users can easily access AI models hosted on the gateway. This can be helpful for low-barrier use case exploration, and for providing a secure internal alternative to using external LLM tools such as ChatGPT. Connecting the playground to some internal data sources makes both these use cases even more compelling.</p><h4>Fallback Mechanisms</h4><p>The high demand for generative AI and the difficulty in scaling up compute resources can lead to situations where model providers are unable to successfully generate responses. To overcome these reliability issues, it is essential to implement proper failover mechanisms.</p><p>Example fallback mechanisms include retrying the same model, attempting the request in another region, or sending the request to another model provider. This can be integrated with governance to ensure appropriate controls are maintained on user access and data compliance.</p><h4>IAM and Secrets</h4><p>Just like an API gateway, a GenAI gateway is an excellent mechanism to centralize authentication and authorization for incoming traffic. However, when working with model providers, you will also need to authenticate with them, mostly through the use of an API key.</p><p>Handling sensitive information such as API keys requires the use of a secret manager to safely store and load these values. By building this functionality into the GenAI gateway, individual product teams don’t need to set up and maintain licenses to model providers individually. Managing this centrally increases security and makes it easier to control costs.</p><h3>A GenAI Gateway Tailored to Your Needs</h3><p>All organizations have different needs for their GenAI solutions, so there’s no one-size-fits-all GenAI gateway. An implementation of a GenAI gateway can range from a simple and basic architecture to a feature-rich, complex architecture.</p><p>As an alternative to implementing a GenAI gateway yourself, you can also go off-the-shelf. Many of the features we describe in this section are available as part of GenAI gateway products on the market, such as<a href="https://github.com/EinStack/glide"> Glide</a>, <a href="https://www.getjavelin.io/">Javelin</a>, <a href="https://orq.ai/">Orq</a> or <a href="https://konghq.com/products/kong-ai-gateway">Kong GenAI Gateway</a>, which provide out-of-the-box solutions for GenAI gateways. Choosing between these two options requires analyzing the trade-offs between each, and seeing what best fits your organization’s current situation in terms of AI vision, roadmap, current and foreseen use case load, and available resources.</p><p>The main advantage of using such solutions is that you don’t need to invest time in building one yourself. Maintenance costs will also be significantly lower. However, the major downside is that you are fully dependent on the features they offer. Building a custom GenAI gateway allows you to tailor the gateway to your specific needs, and it lets you keep control over all the data and infrastructure on your own platform. Unless you opt for a self-hosted solution, off-the-shelf gateways require you to share potentially sensitive data through the providers’ API for processing and storage. It might also become difficult later to switch away from third party software once you’ve built a lot of functionality on top of it (pipelines, scripts,…). And since these tools and pricing models are still relatively new, significant changes might make switching desirable or inevitable in the future.</p><p>Developing a custom solution does require some investment in development and maintenance, however it also means you maintain full control and can tailor to your organizations’ needs in terms of models, or other supporting components. Importantly, “building it yourself” does not require building everything from scratch. A lot of the required tooling provided by cloud providers can be adapted to work together in the gateway architecture.</p><p>If you are developing a customized solution, it is often best to develop the gateway in an iterative manner, carefully considering what would bring the most value across the teams that would be consumers of the gateway’s services, and validating these assumptions before starting the implementation. Also consider what implications each feature or abstraction has on maintenance costs for your platform team (e.g. when model providers break backward compatibility in an API update).</p><h4>A Super Basic GenAI Gateway</h4><p>The most minimal implementation of a GenAI gateway would be a component that can route requests to different models across different model providers or to different self-hosted models, as well as a model registry component offering information on supported models. Such a GenAI gateway can be incredibly useful in the early stages of building GenAI applications. The main benefit of having a GenAI gateway compared to not having one is that it provides a centralized way to access a range of models, making it easier to experiment with different models and update them as needed. For example, when Meta released LLaMA-3, which likely outperforms LLaMA-2, swapping LLaMA-3 for LLaMA-2 doesn’t require changes in all of your applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*rLuzjfd81Q51Iww6" /></figure><h4>Authentication and Authorization</h4><p>As mentioned before, allowing unrestricted access to LLM calls is quite risky. Therefore, adding a policy store to the GenAI gateway is a great idea. Policies can be used as an authorization component to define restrictions on access to certain models by specific users, set rate limits, or limit the number of input and output tokens. Policies can also enforce certain regulations, such as processing data in a specific region.</p><p>A natural companion to the policy store is an identity and access management (IAM) component, ensuring that the GenAI gateway is aware of who is making an API call. This component should handle all authentication logic. Together with the policy store, you can set up fine-grained access control to your models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*3wxX8R2OnuyX1n--" /></figure><h4>Keeping an Eye on the Price</h4><p>Observability and monitoring are both important practices within a production environment, but in GenAI applications, they deserve special attention. As LLm calls are generally expensive, with non- deterministic costs, as the number of output tokens varies. Monitoring can be used to gain insights into how LLMs are used and if this is in line with expectations or best practices. Not only the number of calls to LLMs is a major factor in the total costs, but also the size of the inputs and outputs.</p><p>Our architecture so far supports pretty much everything we need in terms of security and cost management. What’s left to add to our architecture are some more niche features like caching. Caching in GenAI can be similar to caching in a web server, but with some unique tweaks. Semantic caching is a technique to determine whether we have previously processed a request where the prompt was semantically similar to the current incoming request. For example, “How do I update my password?” and “How can I change my password?” have the same answer, even though the questions are worded differently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*jMUJtQQwMhMtKvUt" /></figure><h4>Taking Control of What Is Going In and Out of the Model</h4><p>There are two types of guardrails: input and output guardrails. As the name suggests, input guardrails are used to ensure that inputs for the LLM are verified, while output guardrails are used to verify the outputs generated by the LLM. Examples of input guardrails include measures to block malicious requests and prevent users from generating inappropriate content. If you are using third-party APIs, you might want to remove personal identifiable information. Output guardrails can be used to verify output formats, such as validating that the LLM returned a valid JSON in a predefined format, or to verify the quality of the generated response. The main reasons for adding guardrails are to avoid abuse and maintain high-quality generated outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*wxz-6D05Zgzq7oeD" /></figure><h4>Other Features</h4><p>The AI playground mentioned above can be added to encourage easy experimentation. This can be seen as a separate project, owned by the platform team, acting as a consumer for your gateway services, and it can be realized by using off-the-shelf components for the frontend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*RkxZI2hxFk2uJYAY" /></figure><p>An additional component that can be added to the gateway is custom logic to pre- or post-process the inputs and outputs. Responses can be enriched with metadata or put into a certain format to fit your organization’s goals. These could be turned on or off via API flags</p><h4>Scenarios When a GenAI Gateway Is Not the Right Solution</h4><p>A prime example of where a GenAI gateway might not be a suitable solution is in processing pipeline with a low-latency and/or high-throughput requirement where one or more steps involve calls to a generative model. A GenAI gateway acts as a middleman, which inherently introduces additional latency. When self-serving, you have better control over optimizing throughput and latency, for example, through batch requests and keeping model data in GPU memory. For such custom projects a self-managed solution reusing components or best practices from the platform might be the best solution.</p><p>However, using generative models without the gateway means losing the benefit of centralized traffic management, making it more difficult to gain organization-wide insights. It’s up to the solution architect and other stakeholders to make the trade-off between having the gateway features such as centralized monitoring, access control, and rate limiting versus better-tuned performance.</p><p>A new model usage pattern can also be developed within the use case team, and integrated in the gateway at a later stage once the case for its reuse across the organization becomes more clear.</p><h3>Conclusion</h3><p>In this article we covered the concept of a GenAI gateway, a concept inspired by an API gateway to centralize generative AI traffic in a single place, as part of a platform approach to AI across the organization. A GenAI gateway offers a solution to GenAI specific challenges such as secure usage models via guardrails, monitoring and observability of model usage and authorized usage models. You can tailor the gateway to your needs, to make optimal use of generative AI within your organization.</p><p><em>This blog post was co-authored with Robbe Sneyders and Thomas Janssens. We would also like to give a special shout-out to Arne Pannemans and Matthias Durivet.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c4dc35dac9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ml6team/why-you-need-a-genai-gateway-8c4dc35dac9b">Why You Need a GenAI Gateway</a> was originally published in <a href="https://medium.com/ml6team">ML6team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Need for Speed: JAX]]></title>
            <link>https://medium.com/ml6team/need-for-speed-jax-1d203d434718?source=rss-bd85a1880b2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d203d434718</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[jax]]></category>
            <dc:creator><![CDATA[Jasper Van den Bossche]]></dc:creator>
            <pubDate>Wed, 02 Mar 2022 15:05:17 GMT</pubDate>
            <atom:updated>2022-09-09T13:22:15.018Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Training your neural network ten times faster using Jax on a TPU</strong></p><p>All the cool kids seem to be raving about JAX these days. Deepmind is using it extensively for their <a href="https://deepmind.com/blog/article/using-jax-to-accelerate-our-research">research</a> and even building their own ecosystem on top of it. Boris Dayma and his team built <a href="https://github.com/borisdayma/dalle-mini">DALL·E Mini</a> in no time using JAX and TPUs, definitely worth checking out on Hugging Face where you already find over 5000 models written in JAX. But what exactly is JAX and why is it so special? According to their website JAX offers automatic differentiation, vectorization and just-in-time compilation to both GPUs and TPUs via composable transformations. Sounds complicated? Don’t worry, in this blogpost we will take you on a tour and show you how JAX works, how it’s different from Tensorflow/Pytorch and why we think it is a super interesting framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uJsn28h2-9uWx0jY" /></figure><h3>What is JAX?</h3><p>JAX is a high-performance numerical computing and machine learning framework by Google Research that runs super fast on GPUs and TPUs, without having to worry about low-level details. The goal of JAX was to build a framework that combines high-performance with Python’s expressiveness and ease of use, so that researchers could experiment with new models and techniques without the need of highly optimised low-level C/C++ implementations. It achieves this goal by using Google’s XLA (Accelerated Linear Algebra) compiler to generate efficient machine code rather than using precompiled kernels. One of the cool things about JAX is that it is accelerator agnostic, meaning that the same Python code can run efficiently on both GPUs and TPUs.</p><p>JAX works via composable function transformations, this means that JAX takes a function and produces a new function that is interpreted differently and that multiple transformations can be chained together. Automatic differentiation for instance is a transformation that generates the derivative of a function, while automatic vectorization takes a function that operates on a single data point and transforms it into a function that operates on a batch of data points. Through these transformations JAX allows the programmer to stay in the high-level Python world and let the compiler do the hard work by generating the highly efficient code needed to train complex models. We will go over these transformations and apply them in an example where we build a simple multilayer perceptron.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bFRUw5sLfP0ssmCN" /><figcaption>A schematic overview of composable functions.</figcaption></figure><h3>What makes it different from Tensorflow and Pytorch?</h3><p>JAX is a compiler-oriented framework, which means that a compiler is responsible for transforming the Python functions into efficient machine code. Tensorflow and Pytorch on the other hand have precompiled GPU and TPU kernels for each operation. During the execution of a TensorFlow program, each operation is dispatched individually. While the operations themselves are very well optimised, fusing them together requires a lot of memory operations, causing a bottleneck in the performance. The XLA compiler can generate code for the entire function. It can use all of that information to fuse together operations and save a ton of memory operations and thus generate overall faster code.</p><p>JAX is also more lightweight than Tensorflow and Pytorch, because there is no need to implement each operation, function or model separately. Instead JAX implements the NumPy API with simpler and more low-level operations that can be used as building blocks and fused together into complex models and functions by the compiler.</p><h3>The compiler, much more powerful than you might think</h3><p>The compiler-oriented design is a lot more powerful than you might think at first. With the compiler, there is no longer a need to implement low-level accelerator code. It allows researchers to vastly improve their productivity and opens doors to experiment with new model architectures. Researchers are even able to experiment with GPUs and TPUs without the need to rewrite their code. But how does that work?</p><p>JAX doesn’t directly compile to machine code, but rather to an intermediate representation that is independent from the high-level Python code and the machine code. The compiler is split up in a frontend that compiles Python functions to the IR and a backend that compiles the IR to platform specific machine code. This design isn’t new, an example of a compiler that also follows this design is LLVM. There are frontends for both C and Rust that translate high-level code to the LLVM IR. The backend can then generate machine code for a variety of supported machine types, no matter whether the original code was written in C or Rust.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5JPmp1Anvy_SKIRL" /><figcaption>JAX transforms high level Python code to an intermediate representation that is then compiled by XLA to a program that runs on your machine type.</figcaption></figure><p>This is huge, because thanks to this flexible design one could build a new accelerator, write an XLA backend for it and your JAX code that previously ran on GPUs/TPUs can be executed on the new accelerator. On the other hand, you could also build a framework in another programming language that compiles to the JAX IR and you can make use of GPUs and TPUs thanks to XLA.</p><p>If this compiler based approach works so much better than precompiled kernels, why didn’t Tensorflow and Pytorch make use of it from the start? The answer is pretty simple, it is really hard to design a good numerical compiler. With its automatic differentiation, vectorization and jit-compilation, JAX has some really powerful tools under its belt. However JAX isn’t the silver bullet either, all of these goodies come at a small price, you need to learn a few new tricks and concepts related to functional programming.</p><h3>A note on functional programming</h3><p>JAX can’t transform just any Python function, it can only transform pure functions. A pure function can be defined as a function that only depends on its inputs, meaning that for a given input x it will always return the same output y and that it doesn’t produce any side effects such as IO operations or mutation of global variables. Python’s dynamism means that the behaviour of a function changes based on the types of its inputs and JAX wants to exploit this dynamism by transforming functions at runtime. At the start of a transformation JAX checks what the function does for a set of given inputs and transforms the function based on that information. Under the hood JAX traces the function, just like the Python interpreter. By only allowing pure functions, transforming functions just in time becomes a lot easier and faster.</p><p>Imagine that the tracer has to deal with side effects such as IO, that means that unexpected behaviour can occur such as a user that entered invalid data, which makes it a lot harder to generate efficient code, especially when accelerators are in the game. Global variables can change between two function calls and thus completely change the behaviour of the function they’re used in, making a transformed function invalid. If you are interested in compilers and the nitty gritty details of how JAX’s tracing works, we recommend you to check out the<a href="https://jax.readthedocs.io/en/latest/autodidax.html"> documentation</a> for more details of its inner workings.</p><p>The only unfortunate thing about JAX is that it can’t verify whether a function is a pure function. It is up to the programmer to make sure that he writes pure functions, otherwise JAX will transform the function with some unexpected behaviour.</p><h3>Representing stateful objects using Pytrees</h3><p>Working with pure functions also has an impact on how data structures are used. In other frameworks machine learning models are often represented in a stateful way, however, this clashes with the functional programming paradigm because this is mutation of a global state. To overcome this problem JAX introduces pytrees, <em>tree-like structures built out of container-like Python objects. C</em>ontainer-like classes can be registered in the pytree registry, which by default contains lists, tuples, and dicts. Pytrees can contain other pytrees and classes not registered in the pytree registry are considered leafs. Leafs can be considered as immutable inputs for a pure function. For each class in the pytree registry, there is a function that converts a pytree to a tuple with its children and optional metadata as well as a function that converts children and metadata back to a container-like type. These functions can be used to update the model or any other stateful objects you use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7gJFzhRj1r8_b5HB" /></figure><h3>Let’s transform some code!</h3><p>Before we dive into our MLP example, we will show the most important transformations in JAX.</p><h4>Automatic Differentiation</h4><p>The first transformation is automatic differentiation, where we take a Python function as an input and return a function that represents the gradient of that function. The neat thing about JAX’s autodiff is that it can differentiate Python functions that make use and Python containers, conditionals, loops etc. In the following example we create a function that represents the gradient of the `tanh` function. Because JAX transformations are composable, we can use <em>n</em> nested calls of the grad function to transform to calculate the <em>n</em>th derivative.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b98edace892a36cd4d931cf093639bd/href">https://medium.com/media/3b98edace892a36cd4d931cf093639bd/href</a></iframe><p>JAX’s Automatic differentiation is a powerful and extensive tool, if you want to learn more about how it works we recommend you to read<a href="https://jax.readthedocs.io/en/latest/notebooks/autodiff_cookbook.html"> The JAX Autodiff Cookbook</a>.</p><h4>Automatic Vectorization</h4><p>When training a model, you typically propagate a batch of training samples through your model. When implementing a model would you thus have to think of your prediction function as one that takes in a batch of samples and returns a prediction for each sample. This however can significantly increase the difficulty of the implementation as well as reduce the readability of the function compared to a function that would operate on a single sample. In comes the second transformation: automatic vectorization. We write our function as if we were processing only a single sample, then vmap will transform it into a vectorized version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gxSNYewE51lmNP4f" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/277e3b847e5ff22148cb672945238416/href">https://medium.com/media/277e3b847e5ff22148cb672945238416/href</a></iframe><p>In the beginning vmap can be a bit tricky especially when working with higher dimensions, but it is a really powerful transformation. We recommend you to check out some examples in the documentation to fully understand its potential.</p><h4>Just-In-Time Compilation</h4><p>The third function transformation is just-in-time compilation. The goal of this transformation is to improve the performance, parallelise the code and run it on an accelerator. JAX doesn’t compile directly to machine code but rather to an intermediate representation. That intermediate representation is independent from the Python code and the machine code of the accelerator. The XLA compiler will then take the intermediate representation and compile it to efficient machine code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a302c6701bfdaaa8a29bc6978cf9f05e/href">https://medium.com/media/a302c6701bfdaaa8a29bc6978cf9f05e/href</a></iframe><p>It is not always easy to decide when and what code you should compile, in order to make optimal use of the compiler, we recommend you to check out the<a href="https://jax.readthedocs.io/en/latest/notebooks/thinking_in_jax.html#to-jit-or-not-to-jit"> documentation</a>. Later in this blog we’ll go a bit deeper in the design of the compiler and why this makes JAX such a powerful framework.</p><h3>Training an MLP in 5 minutes using a TPU</h3><p>Now that we learned about the most important transformations, we are ready to put that knowledge into practice. We will implement an MLP from scratch to classify MNIST images and train it super fast on a TPU. Our neural network will have an input layer of 728 input variables, followed by two hidden layers with 512 and 256 neurons respectively and an output layer with a node for each class.</p><h4>Model initialisation</h4><p>The first thing we will need to do is create a structure that represents our model. As input of our initialisation function we have a list with the number of nodes in each layer of our neural network. We have an input layer that is equal to the number of pixels of an image, followed by two hidden layers with 512 and 256 neurons respectively and an output layer that is equal to the number of classes. We use JAX numpy arrays to initialise the model on the accelerator, avoiding to manually copy that data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/186ed4d7b11db792d4dba54bb05a4e7c/href">https://medium.com/media/186ed4d7b11db792d4dba54bb05a4e7c/href</a></iframe><p>Note that generating random numbers is slightly different from numpy. We want to be able to generate random numbers on parallel accelerators and we need a random number generator that works well with the functional programming paradigm. Numpy’s algorithm to generate random numbers isn’t very suited for these purposes. Check out the JAX<a href="https://github.com/google/jax/blob/main/design_notes/prng.md"> design notes</a> and<a href="https://jax.readthedocs.io/en/latest/jax-101/05-random-numbers.html"> documentation</a> for more information.</p><h4>Prediction</h4><p>Our next step is to write a prediction function that will assign labels to a batch of images. We will use automatic vectorization to transform a function that takes in a single image as input and outputs a label into a function that predicts labels for a batch of inputs. Writing a prediction function is not super hard, we flow through the hidden layers of the network and apply weights and biases via a matrix multiplication and vector addition and apply the RELU activation function. At the end we calculate the output label using the RealSoftMax function. Once we have our function to label a single image we can transform it using vmap so it can process a batch of inputs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b44446d7680b0ed9f8ee73e9824adb7/href">https://medium.com/media/4b44446d7680b0ed9f8ee73e9824adb7/href</a></iframe><h4>Loss Function</h4><p>The loss function takes a batch of images and calculates the mean absolute error. We call our batched predictions and calculate the label for each image, compare this against the one-hot encoded ground truth labels and calculate the mean number of errors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc21aa25556aa4cc27a92b63a2347750/href">https://medium.com/media/bc21aa25556aa4cc27a92b63a2347750/href</a></iframe><h4>Update function</h4><p>Now that we have our prediction and loss function, we will implement an update function to iteratively update our model in each training step. Our update function takes in a batch of images and its ground truth labels together with the current model and a learning rate. We calculate both the value of the loss and the value of its gradient. We update the model using the learning rate and the loss gradients. As we want to compile this function, we have to convert the updated model to a pytree. We also return the value of the loss for monitoring the accuracy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a1aee2272658998d50d832c10eb954e/href">https://medium.com/media/7a1aee2272658998d50d832c10eb954e/href</a></iframe><p>Now that we have the update function, we are going to compile so it can run on a TPU and greatly improve its performance. The nested functions called in the update function will also be compiled and optimised. The reason why we only apply the compile transformation on update and not on each function separately is that we want to give the compiler as much information to work with, so it can optimize the code as much as possible.</p><h4>Training Our Model</h4><p>We can define an accuracy function (and optionally other metrics) and create a training loop using our update function and initial model as input. We are now ready to train our model using a TPU or GPU.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3331d9b4ea68f0c7a0fdd0ce48623ddd/href">https://medium.com/media/3331d9b4ea68f0c7a0fdd0ce48623ddd/href</a></iframe><h3>Conclusion</h3><p>Phew, we have learned a lot today. First we started describing JAX as a framework with composable function transformations. The four core transformations are automatic vectorisation, automatic parallelisation over multiple accelerators, automatic differentiation of python functions and JIT-compiling functions to run them on accelerators. We went deeper in on the inner workings of JAX and learned how it is able to create such efficient functions that work both on GPUs and TPUs by compiling to an IR that is then transformed to XLA calls. This approach allows researchers to experiment with new machine learning techniques without having to worry about a low level, highly optimised version of their code. We hope software engineers are excited as well so that new libraries can be built on top of JAX and potential accelerators can be quickly adopted.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d203d434718" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ml6team/need-for-speed-jax-1d203d434718">Need for Speed: JAX</a> was originally published in <a href="https://medium.com/ml6team">ML6team</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>