New Blog: Bringing (Gen) AI from Laptop to Production with MLRun

Open Source MLOps and LLMOps Orchestration with MLRun: Quick Start Tutorial

Open Source MLOps and LLMOps Orchestration with MLRun: Quick Start Tutorial

MLRun is an open-source MLOps and gen AI orchestration framework designed to manage and automate the machine learning lifecycle. This includes everything from data ingestion and preprocessing to model training, deployment and monitoring, as well as de-risking. MLRun provides a unified framework for data scientists and developers to transform their ML code into scalable, production-ready applications.

In this blog post, we’ll show you how to get started with MLRun: creating a dataset, training the model, serving and deploying. You can also follow along by watching the video this blog post is based on or through the docs.

When starting your first MLRun project, don’t forget to star us on GitHub.

Now let’s get started.

Creating Your First MLRun Project

An MLRun project helps organize and manage the various components and stages of an ML or gen AI workflow in an automated and streamlined manner. It integrates components like datasets, code, models and configurations into a single container. By doing so, it supports collaboration, ensures version control, enhances reproducibility and allows for logging and monitoring.

  1. Install and import MLRun. More details on how to do it.
  2. Create a project with project = mlrun.get_or_create_project(name=”quick-tutorial”, user_project=True).

This will create the project object, which will be used to add and execute functions.

  1. Now for the dataset. This only requires a simple script with one Python function that grabs a dataset from scikit-learn and returns it as a pandas dataframe.

%%writefile data-prep.py

 

import pandas as pd

from sklearn.datasets import load_breast_cancer

 

def breast_cancer_generator():

    “””

    A function which generates the breast cancer dataset

    “””

    breast_cancer = load_breast_cancer()

    breast_cancer_dataset = pd.DataFrame(

        data=breast_cancer.data, columns=breast_cancer.feature_names

    )

    breast_cancer_labels = pd.DataFrame(data=breast_cancer.target, columns=[“label”])

    breast_cancer_dataset = pd.concat(

        [breast_cancer_dataset, breast_cancer_labels], axis=1

    )

 

    return breast_cancer_dataset, “label”

This is regular Python. MLRun will automatically log the returning data set and a label column name. 4. Create an MLRun function using project.set_function, together with the name of the Python file and parameters specifying requirements. These could include running the function as a job with a certain Docker image.

data_gen_fn = project.set_function(

    “data-prep.py”,

    name=”data-prep”,

    kind=”job”,

    image=”mlrun/mlrun”,

    handler=”breast_cancer_generator”,

)

project.save()  # save the project with the latest config

 

  1. Save the project.
  2. Run the function with project.run_function together with the required parameters. For example, for running in a local environment, use (local=True), otherwise it runs at scale in Kubernetes. Notice the `returns` parameter where we specify what MLRun should log from the function’s returning objects.

gen_data_run = project.run_function(

    “data-prep”, 

    local=True,

    returns=[“dataset”, “label_column”],

)

  1. Open the MLRun UI.
  2. View artifacts like the logged data sets, the label column, metadata and more.

Training the Model

Now let’s see how to train a model using the dataset that we just created. Instead of creating a brand new MLRun function, we can import one from the MLRun function hub.

  1. Go to the function hub.

Here’s what it looks like:

 

You will find a number of useful and powerful functions out-of-the-box. We’ll use the Auto trainer function.

  1. Import it by pointing to the marketplace and specifying the function name:

# Import the function

trainer = mlrun.import_function(“hub://auto_trainer”)

In this case, one of the parameters is the data set from our previous run.

trainer_run = project.run_function(

    trainer,

    inputs={“dataset”: data_prep_run.outputs[“dataset”]},

    params={

        “model_class”: “sklearn.ensemble.RandomForestClassifier”,

        “train_test_split_size”: 0.2,

        “label_columns”: data_prep_run.results[“label_column”],

        “model_name”: “breast_cancer_classifier”,

    },

    handler=”train”,

)

 

The default is local=false, which means it will run behind the scenes on Kubernetes.

You will be able to see the pod and the print out statements.

  1. Open the MLRun UI, which will display more details and artifacts. For example, the parameters passed in the evaluation metrics, the model itself and more.

Serving the Model

Now we can serve the trained model.

  1. Type mlrun.new_function and select the kind as serving.

serving_fn = mlrun.new_function(

    “breast_cancer_classsifier_servingserving”,

    image=”mlrun/mlrun”,

    kind=”serving”,

    requirements=[“scikit-learn~=1.3.0”],

)

 

  1. Add your model to the serving function using serving_fun.add_model and the path to the model.
  • The path to the model is the output of the training job.
  • The class name specifies the model’s serving class where the API is.. There are built-in classes in MLRun, like the SciKit-Learn model server, in this example.

serving_fn.add_model(

    “breast_cancer_classifier_endpoint”,

    class_name=”mlrun.frameworks.SKLearnModelServer”,

    model_path=trainer_run.outputs[“model”],,

)

 

In this example, we are using sklearn. But you can choose your preferred framework from this list:

Or customize your own. You can read more about this in the docs.

The example below shows a simple, singular model. There are also more advanced models that include steps for data enrichment, pre-processing, post-processing, data transformations, aggregations and more.

Read more about real-time serving here.

  1. Test the serving function using a mock server that simulates the model deployment. This allows making sure everything is behaving as expected without having to deploy.

# Create a mock (simulator of the real-time function)

server = serving_fn.to_mock_server()

Use the mock server `test` method (server.test) to test the model server.

The last part of the code is the model server, which you can send data inputs to and acts exactly like a model server.

Deploying the Model

Finally, it’s time to deploy to production with a single line of code.

  1. Use the `deploy` method:

serving_fn.deploy()

This will take the code, all the parameters, the pre- and post-processing, etc., package them up in a container deployed on Kubernetes and expose them to an endpoint. The endpoint contains your transformation, pre- and post-processing, business logic, etc. This is all deployed at once, while supporting rolling upgrades, scale, etc.

  1. Now, send data and see if you get a response as expected. Use the serving function `invoke` method (serving_fn.invoke) to send data from the notebook.

That’s it! You now know how to use MLRun to manage and deploy ML models. As you can see, MLRun is more than just training and deploying models to an endpoint. It is an open source machine learning platform that helps build a production-ready application that includes everything from data transformations to your business logic to the model deployments to a lot more.

Start using MLRun today.

Get more tutorials here.

Recent Blog Posts
MLRun v1.8 Release: with Smarter Model Monitoring, Alerts and Tracking
MLRun v1.8 adds features to make LLM and ML evaluation and monitoring more accessible, practical and...
Gilad Shaham
June 16, 2024
MLRun + NVIDIA NeMo: Building Observable AI Data Flywheels in Production
NVIDIA NeMo and Iguazio streamline training, evaluation, fine-tuning and monitoring of AI models at...
Baila - Iguazio
June 16, 2024
Fine-Tuning in MLRun: How to Get Started
How to fine tune an existing LLM quickly and easily with MLRun, with two practical hands-on examples...
Nick Schenone
June 16, 2024

Tutorial: Build a Smart Call Center Analysis Gen AI App with MLRun, Gradio and SQLAlchemy

Tutorial: Build a Smart Call Center Analysis Gen AI App with MLRun, Gradio and SQLAlchemy

Developing a gen AI app requires multiple engineering resources, but with MLRun the process can be simplified and automated. In this blog post, we show a tutorial of building an application for a smart call center application. This includes a pipeline for generating data for calls and another pipeline for call analysis. For those of you interested in the business aspect, we added information in the beginning about how AI is impacting industries.

You can follow the tutorial along with the respective Notebook and clone the Git. Don’t forget to star us on Github when you do! You can also watch the tutorial video.

How AI is Impacting the Economy

AI is changing our economy and ways of work. According to McKinsey, AI’s most substantial impact is in three main areas:

  • Productivity – Improving how businesses are run, from customer interactions to coding to content creation.
  • Product Transformation – Changing how products meet customer needs. This includes conversational interfaces and co-pilots, as well as hyper-personalization, i.e customer-specific content at a granular level.

Redistributing profit pools – AIaaS (AI-as-a-Service) is added to the value chain, resulting in new solutions and entire value chains being replaced.

AI Pitfalls to Avoid

When building a gen AI app and operationalizing LLMs, it’s important to perform the following actions:

  1. Define a value roadmapWithout a clear value roadmap, projects can easily drift from their intended goals. This roadmap aligns the AI initiative with business objectives, ensuring that the development efforts lead to tangible benefits.
  2. Avoid technological and operational debtAvoiding this debt ensures the long-term sustainability and maintainability of the AI system.
  3. Take into consideration the human experienceIgnoring the human experience can lead to an AI solution that users find difficult or unpleasant to use, impeding adoption and productivity.
  4. Use a scalable and resilient gen AI architecture to ensure you reach production – Otherwise, the architecture might fail under increased loads or during unexpected disruptions.
  5. Implement processes to ensure AI maturity and governanceWithout proper processes, the AI system can become unreliable, biased, or non-compliant with regulations. Governance ensures that the AI operates within acceptable ethical and legal boundaries.
  6. Define quantifiable KPIsClear KPIs create accountability and focus, ensuring that the project stays on track.

Now let’s dive into the hands-on tutorial.

Tutorial: Building a Gen AI Application for Call Center Analysis

The following tutorial shows how to build an LLM call center analysis application. We’ll show how you can use gen AI to analyze customer and agent calls so your audio files can be used to extract insights.

This will be done with MLRun in a single workflow. MLRun will:

  • Automate the workflows
  • Auto-scale resources
  • Automatically distribute inference jobs to workers
  • Automatically log and parse the values of the workflow steps

As a reminder, you can:

Installation

  1. First, you will need to install MLRun, Gradio and SQLAlchemy and add tokens. The project is created in the Notebook.

Data Generation Pipeline

  1. Now it’s time to generate call data. You can skip this if you already have your own audio files for analysis. We also have saved generated data in the Git repo you can use, enabling you to run the demo without an OpenAI key.

This comprises six steps, some of which are based on MLRun’s Function Hub:

The resulting workflow will look like this:

As you can see, no code is required. More details on each step and when to use them, in the documentation.

  1. Run the workflow by calling the project’s method project.run. You can also configure the workflow with arguments.

Data Analysis Pipeline

  1. Now it’s time for the data analysis pipeline. The steps in this pipeline are:
  • Inserting calls
  • Diarization
  • Transcription
  • PII recognition
  • Analysis
  • Post-processing

And it looks like this:

 

Similarly, no coding is required here either.

  1. Run the workflow and view the results.

Here’s how some of the steps are executed:

  • Analysis – Generating a table with the call summary, its main topic, customer tone, upselling attempts and more:

6. You can also use your database and the calls for developing new applications, like prompting your LLM to find a specific call in your call database in a RAG based chat app.To hear what a real call sounds like, watch the video of this tutorial.

Advanced MLRun Capabilities

In addition to simplifying the building and running of the pipelines, MLRun also allows auto logging, auto distribution and auto scaling resources.

Try MLRun for yourself.

Recent Blog Posts
MLRun v1.8 Release: with Smarter Model Monitoring, Alerts and Tracking
MLRun v1.8 adds features to make LLM and ML evaluation and monitoring more accessible, practical and...
Gilad Shaham
June 13, 2024
MLRun + NVIDIA NeMo: Building Observable AI Data Flywheels in Production
NVIDIA NeMo and Iguazio streamline training, evaluation, fine-tuning and monitoring of AI models at...
Baila - Iguazio
June 13, 2024
Fine-Tuning in MLRun: How to Get Started
How to fine tune an existing LLM quickly and easily with MLRun, with two practical hands-on examples...
Nick Schenone
June 13, 2024