<?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[yelassad - Medium]]></title>
        <description><![CDATA[Enjoy our publications where we share passion, experiments, and learnings from AI, Dev, and MLOps. In sharing, we trust. - Medium]]></description>
        <link>https://medium.com/yelassad?source=rss----b694c5719f35---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>yelassad - Medium</title>
            <link>https://medium.com/yelassad?source=rss----b694c5719f35---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:06:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/yelassad" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MLOps the Hard Way (A Gray Matter Enlightening Kit) — Helm]]></title>
            <link>https://medium.com/yelassad/mlops-the-hard-way-a-gray-matter-enlightening-kit-helm-4f695cf435e7?source=rss----b694c5719f35---4</link>
            <guid isPermaLink="false">https://medium.com/p/4f695cf435e7</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[helm]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Yassine Elassad]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 06:47:11 GMT</pubDate>
            <atom:updated>2023-11-20T07:39:13.701Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>MLOps the Hard Way (A Gray Matter Enlightening Kit)</strong></h3><blockquote><strong>MLOps the Hard Way</strong> is a series of very short articles that will cover multiple topics, tools, and strategies in dealing with challenges associated with the development, delivery, and operations of Machine Learning-based applications in the cloud.</blockquote><h3>Get your Helm ready</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CDVEf66reWRPs_2Qb23k3g.jpeg" /></figure><p>When working with <a href="https://helm.sh/">Helm</a>, most developers do not dive into the details of the chart being used unless it’s not working as expected.</p><p>The general workflow is something similar to this:</p><p>1) Identify the chart’s values.yaml documentations.<br>2) Identify what configuration items the chart have and which one you want to override/customize.<br>3) Create your own Helm values file mychartname.yml.<br>4) Add and update your desired chart to the local repository cache.<br>5) Apply/Install the desired chart with your desired values into your <a href="https://kubernetes.io/">Kubernetes</a> environment optionally in the desired namespace.</p><pre># helm repo add [NAME] [URL] [flags]<br>helm repo add mychartname https://chartrepository.apache.org <br>helm repo update mychartname <br>helm upgrade --install --create-namespace --values mychartname.yml --namespace mychartname-namespace  &lt;myreleasename&gt; mychartname</pre><p>When you use the “helm add” command to add a chart, the chart code is now stored on your local machine within the local repository cache directory. Depending on your operating system and configuration, this directory is your cache location:</p><pre>| Operating System | Cache Path                | Configuration Path             | Data Path               |<br>|------------------|---------------------------|--------------------------------|-------------------------|<br>| Linux            | $HOME/.cache/helm         | $HOME/.config/helm             | $HOME/.local/share/helm |<br>| macOS            | $HOME/Library/Caches/helm | $HOME/Library/Preferences/helm | $HOME/Library/helm      |<br>| Windows          | %TEMP%\helm               | %APPDATA%\helm                 | %APPDATA%\helm          |</pre><p>If everything goes well, you already know where the charts are located, and there is no need to check their code. However, since things rarely go smoothly, you may find yourself reading and analyzing the chart’s code in the local repository cache. <strong>Even worse, sometimes you might catch your self modifying a chart code within the cache diretory</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*sFpCJ1o9O0bhukccvTOwCQ.jpeg" /></figure><p>To be on the safe side while trying to demystify the magic of a Helm chart, consider the following:</p><pre># helm repo add [NAME] [URL] [flags]<br>helm repo add mychartname https://chartrepository.apache.org <br>helm repo update mychartname <br>mkdir mychartname <br>cd mychartname <br># Please use your dedicated cache repository path as it is OS dependent<br>helm template $HOME/Library/Caches/helm/repository/chartname-&lt;chart-version&gt;.tgz --output-dir .<br># as you would now see helm template Render chart templates locally and display/--outüut-dir stores the output.</pre><p>This way, you can use a copy of the chart code to conduct the analysis you wish and even make modifications if needed, without affecting the default vendor’s code.</p><pre># Got your helmet on? Great! Join the team – we&#39;re hiring!<br>print(&#39;career@lionswerk.de&#39;)<br># Got Questions? Let&#39;s chat! Reach out to us for any queries or clarifications.<br>print(&#39;https://lionswerk.slack.com/&#39;)<br># Need Help with your project? <br># Get a 15-minute Free Consultancy to kickstart your journey.<br>print(&#39;projects@lionswerk.de&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f695cf435e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/yelassad/mlops-the-hard-way-a-gray-matter-enlightening-kit-helm-4f695cf435e7">MLOps the Hard Way (A Gray Matter Enlightening Kit) — Helm</a> was originally published in <a href="https://medium.com/yelassad">yelassad</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating Local MLflow Experiments to a Centralized MLflow Instance]]></title>
            <link>https://medium.com/yelassad/migrating-local-mlflow-experiments-to-a-centralized-mlflow-instance-827be9e064f9?source=rss----b694c5719f35---4</link>
            <guid isPermaLink="false">https://medium.com/p/827be9e064f9</guid>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[mlflow-tracking]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[minio]]></category>
            <dc:creator><![CDATA[Zakariae Mkassi]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 20:23:58 GMT</pubDate>
            <atom:updated>2023-11-05T20:23:26.646Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rui9BFJJUXF5d6dYXsCd9w.png" /></figure><p><strong>A Step-by-Step Guide</strong></p><blockquote><strong>Introduction:</strong></blockquote><p><em>In the realm of machine learning experimentation, managing local MLflow projects efficiently and integrating them into a centralized MLflow instance is a pivotal step towards enhancing collaboration and scalability. The concept of centralization allows teams to access, track, and collaborate on experiments seamlessly, irrespective of where they were originally conducted. In this comprehensive guide, we will walk you through the step-by-step process of migrating your local MLflow experiments to a centralized MLflow instance, creating a robust infrastructure for your machine learning projects. Let’s embark on this journey to streamline your machine learning experiments and optimize your workflow.</em></p><p><strong><em>Requirements</em></strong><em>:</em></p><ol><li><strong><em>MLflow Central Instance:</em></strong><em> A centralized MLflow instance, where you want to consolidate and manage your experiments. This instance should be up and running, providing a central platform for tracking and storing MLflow experiments.</em></li><li><strong><em>PostgreSQL Database:</em></strong><em> A PostgreSQL database with a pre-defined schema to store MLflow experiment metadata, parameters, and metrics. Ensure that you have the necessary database credentials and connection details to interact with PostgreSQL.</em></li><li><strong><em>Minio Bucket:</em></strong><em> A Minio bucket, which serves as a centralized storage location for your MLflow artifacts. Minio is an open-source S3-compatible object storage system that should be configured and accessible for artifact storage. Ensure that you have access keys, secret keys, and the endpoint URL for Minio.</em></li></ol><p><em>These three components will form the foundation for centralizing your local MLflow experiments and creating a more organized and collaborative environment for your machine learning projects.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9LZVON1JSmVyyGuhNteow.png" /></figure><blockquote><strong><em>Uploading Local MLflow Artifacts to Minio: A Practical Guide</em></strong></blockquote><p><em>In this section, we will discuss how to upload your local MLflow artifacts to a Minio bucket, enabling centralized storage and easy accessibility for your machine learning model artifacts. This step is crucial for creating a streamlined and collaborative environment for your projects.</em></p><p><em>Code Walkthrough:</em></p><p><em>We’ve prepared a Python code snippet that demonstrates the process of uploading your local MLflow artifacts to a Minio bucket. Here’s a step-by-step explanation of the code:</em></p><pre>import os<br>import glob<br>import boto3<br><br>def upload_model_to_s3(local_folder_path, s3_bucket_name, aws_access_key_id, aws_secret_access_key, region_name, s3_folder_path):<br>    # Set up a session with the specified AWS access keys and region<br>    session = boto3.Session(<br>        aws_access_key_id=aws_access_key_id,<br>        aws_secret_access_key=aws_secret_access_key,<br>        region_name=region_name<br>    )<br><br>    # Initialize an S3 resource and connect to the Minio endpoint<br>    s3 = session.resource(&#39;s3&#39;, endpoint_url=&#39;http://&lt;IP-ADRESS&gt;:9000&#39;,<br>                          aws_access_key_id=aws_access_key_id,<br>                          aws_secret_access_key=aws_secret_access_key,<br>                          region_name=region_name)<br><br>    # Select the target S3 bucket<br>    bucket = s3.Bucket(s3_bucket_name)<br><br>    # Traverse the local folder and upload artifacts to S3<br>    for subdir, dirs, files in os.walk(local_folder_path):<br>        for file in files:<br>            full_path = os.path.join(subdir, file)<br>            with open(full_path, &#39;rb&#39;) as data:<br>                key = os.path.join(s3_folder_path, full_path[len(local_folder_path):])<br>                bucket.put_object(Key=key, Body=data)</pre><p><em>To execute this code, you’ll need to ensure you have the necessary AWS access keys, the Minio endpoint URL, and a local folder path containing your MLflow artifacts.</em></p><pre>local_folder_paths = &#39;PATH_TO_YOUR_MODEL_ARTIFACTS&#39;<br>s3_bucket_name = &#39;BUCKET_NAME&#39;<br>s3_folder_path =&#39;0/&#39;<br>aws_access_key_id = &#39;YOUR_AWS_ACCESS_KEY_ID&#39;<br>aws_secret_access_key = &#39;YOUR_AWS_SECRET_ACCESS_KEY&#39;<br>region_name= &#39;REGION_NAME&#39;<br><br>upload_folder_to_s3(local_folder_paths, s3_bucket_name, aws_access_key_id, aws_secret_access_key, region_name, s3_folder_path)</pre><p><em>With this code, you can automate the process of uploading your local MLflow artifacts to Minio, facilitating centralization and improving accessibility for your machine learning model artifacts.</em></p><blockquote><strong>Connecting to the Database:</strong></blockquote><p><em>Before we proceed with inserting run metadata, it’s essential to establish a connection to the PostgreSQL database. Here’s how you can set up a connection in your code:</em></p><pre>import psycopg2<br><br>class MLFlowDatabase:<br>    def __init__(self,run_path ,database=&quot;MLFLOW_DB&quot;, user=&quot;MLFLOW_USER&quot;, password=&quot;PASSWORD&quot;, host=&quot;DB_HOST&quot;, port=&quot;5432&quot;):<br>        # Establish a connection to the PostgreSQL database<br>        try:<br>            self.conn = psycopg2.connect(<br>                database=database,<br>                user=user,<br>                password=password,<br>                host=host,<br>                port=port<br>            )<br>            self.cur = self.conn.cursor()<br>            self.run_path = run_path<br>            self.run_uuid = None<br>        except Exception as e:<br>            print(&quot;Error occurred while connecting to the database:&quot;, e)<br><br>    def __del__(self):<br>        print(&#39;Disconnecting from the database...&#39;)<br>        # Close the database connection upon object deletion<br>        if self.conn:<br>            self.conn.close()<br><br>   # def insert_run_metadata(self)...<br>   # def insert_tags_to_db(self)...<br>   # def insert_params_to_db(self)...<br>   # def insert_metrics_to_db(self)...</pre><p><em>You can create an instance of the </em><em>MLFlowDatabase class and use it to connect to your PostgreSQL database. This connection is essential for all subsequent database operations, including inserting run metadata.</em></p><blockquote><strong>Inserting Run Metadata:</strong></blockquote><p><em>In this section, we will guide you through the process of inserting essential run metadata into your PostgreSQL database. This step is crucial for tracking and managing your machine learning experiments effectively:</em></p><pre>def insert_run_metadata(self):<br>    filepath = self.run_path + &#39;meta.yaml&#39;<br><br>    # Read the metadata file<br>    with open(filepath, &#39;r&#39;) as f:<br>        metadata = yaml.safe_load(f)<br><br>    # Extract relevant metadata values<br>    run_uuid = metadata[&#39;run_uuid&#39;]<br>    self.run_uuid = run_uuid<br>    name = metadata[&#39;run_name&#39;]<br>    source_type = &#39;UNKNOWN&#39;<br>    source_name = metadata[&#39;source_name&#39;]<br>    entry_point_name = metadata[&#39;entry_point_name&#39;]<br>    user_id = metadata[&#39;user_id&#39;]<br>    status = metadata[&#39;status&#39;]<br>    start_time = metadata[&#39;start_time&#39;]<br>    end_time = metadata[&#39;end_time&#39;]<br>    source_version = metadata[&#39;source_version&#39;]<br>    lifecycle_stage = metadata[&#39;lifecycle_stage&#39;]<br>    artifact_uri = &#39;mlflow-artifacts:/0/&#39; + run_uuid + &#39;/artifacts&#39;<br>    experiment_id = metadata[&#39;experiment_id&#39;]<br><br>    if status == 3:<br>        status = &#39;FINISHED&#39;<br>    elif status == 4:<br>        status = &#39;FAILED&#39;<br><br>    # Create an SQL query to insert run metadata<br>    query = f&quot;INSERT INTO \&quot;public\&quot;.\&quot;runs\&quot; (\&quot;run_uuid\&quot;,\&quot;name\&quot;,\&quot;source_type\&quot;,\&quot;source_name\&quot;,\&quot;entry_point_name\&quot;,\&quot;user_id\&quot;,\&quot;status\&quot;,\&quot;start_time\&quot;,\&quot;end_time\&quot;,\&quot;source_version\&quot;,\&quot;lifecycle_stage\&quot;,\&quot;artifact_uri\&quot;,\&quot;experiment_id\&quot;,\&quot;deleted_time\&quot;) VALUES (&#39;{self.run_uuid}&#39;,&#39;{name}&#39;,&#39;{source_type}&#39;,&#39;{source_name}&#39;,&#39;{entry_point_name}&#39;,&#39;{user_id}&#39;,&#39;{status}&#39;,{start_time},{end_time},&#39;{source_version}&#39;,&#39;{lifecycle_stage}&#39;,&#39;{artifact_uri}&#39;,{experiment_id},null);&quot;<br><br>    try:<br>        self.cur.execute(query=query)<br>    except psycopg2.IntegrityError as e:<br>        error_message = e.pgerror<br>        if &quot;Key (key, run_uuid)=&quot; in error_message:<br>            print(&quot;ID already exists.&quot;)<br>        else:<br>            print(&quot;Error occurred while inserting runs:&quot;, e)<br>    except Exception as e:<br>        print(&quot;Error occurred while inserting runs:&quot;, e)<br><br>    self.conn.commit()</pre><p><em>Explanation:</em></p><ul><li><em>This code reads the metadata file from your MLflow experiment, which contains crucial information about the run.</em></li><li><em>It extracts key metadata values like run UUID, run name, source type, source name, entry point name, and more.</em></li><li><em>The code then creates an SQL query to insert this metadata into the PostgreSQL database.</em></li><li><em>If any errors occur during the insertion process, the code provides appropriate error handling and messages.</em></li></ul><p><em>Usage:</em></p><p><em>You can execute this code by creating an instance of the </em><em>MLFlowDatabase class and calling the </em><em>insert_run_metadata method. This will insert the run metadata into your PostgreSQL database.</em></p><p><em>In the next section, we will continue with “Inserting Tags,” so stay tuned for the next step in our journey to centralize your MLflow experiments.</em></p><blockquote><strong>Inserting tags:</strong></blockquote><p><em>In this section, we will dive into the process of inserting tags associated with your machine learning runs into your PostgreSQL database. Tags provide valuable context and metadata about your experiments, making it easier to categorize and search for specific runs.</em></p><pre>def insert_tags_to_db(self):<br>    tags_dir = self.run_path + &#39;tags/&#39;<br><br>    tags = []<br><br>    for filename in os.listdir(tags_dir):<br>        filepath = os.path.join(tags_dir, filename)<br>        with open(filepath, &#39;r&#39;) as f:<br>            key = os.path.split(filename)[1]<br>            value = f.read().strip()<br>            result = (key, value)<br>            tags.append(result)  <br><br>    for tag in tags:<br>        key = tag[0]<br>        value = tag[1]<br>        query = &quot;INSERT INTO tags (key, value, run_uuid) VALUES (%s, %s, %s);&quot;<br>        try:<br>            self.cur.execute(query, (key, value, self.run_uuid))<br>        except psycopg2.IntegrityError as e:<br>            error_message = e.pgerror<br>            if &quot;Key (key, run_uuid)=&quot; in error_message:<br>                print(&quot;ID already exists.&quot;)<br>            else:<br>                print(&quot;Error occurred while inserting tags:&quot;, e)<br>        except Exception as e:<br>            print(&quot;Error occurred while inserting tags:&quot;, e)<br>    self.conn.commit()</pre><p><em>Explanation:</em></p><ul><li><em>This code processes the tags directory associated with your MLflow run. Tags are often used to provide additional information or categorization for your experiments.</em></li><li><em>It iterates through each tag file in the specified directory, extracting the tag name (key) and its value.</em></li><li><em>For each tag, the code generates an SQL query to insert the tag information into the PostgreSQL database.</em></li><li><em>Proper error handling is in place to address potential exceptions or integrity errors during the insertion process.</em></li></ul><p><em>Usage:</em></p><p><em>To utilize this code, create an instance of the </em><em>MLFlowDatabase class and call the </em><em>insert_tags_to_db method. This will insert the tags associated with your MLflow runs into your PostgreSQL database, allowing you to access and search for runs based on their associated tags.</em></p><p><em>In the upcoming section, we will discuss “Inserting Parameters,” another critical aspect of centralizing your MLflow experiments. Stay with us as we proceed on our journey to streamline your machine learning workflow.</em></p><blockquote><strong>Inserting Parameters:</strong></blockquote><p><em>In this section, we will explore how to insert parameters associated with your machine learning runs into your PostgreSQL database. Parameters are vital to track the configurations and hyperparameters used during an experiment, providing essential details for reproducing results and understanding your model’s performance.</em></p><pre>def insert_params_to_db(self):<br>    params_dir = self.run_path + &#39;params/&#39;<br>    params = []<br><br>    for filename in os.listdir(params_dir):<br>        filepath = os.path.join(params_dir, filename)<br>        with open(filepath, &#39;r&#39;) as f:<br>            key = os.path.split(filename)[1]<br>            value = f.read().strip()<br>            result = (key, value)<br>            params.append(result)<br><br>    for param in params:<br>        key = param[0]<br>        value = param[1]<br>        query = &quot;INSERT INTO params (key, value, run_uuid) VALUES (%s, %s, %s);&quot;<br>        try:<br>            self.cur.execute(query, (key, value, self.run_uuid))<br>        except psycopg2.IntegrityError as e:<br>            error_message = e.pgerror<br>            if &quot;Key (key, run_uuid)=&quot; in error_message:<br>                print(&quot;ID already exists.&quot;)<br>            else:<br>                print(&quot;Error occurred while inserting params:&quot;, e)<br>        except Exception as e:<br>            print(&quot;Error occurred while inserting params:&quot;, e)<br>    self.conn.commit()</pre><p><em>Explanation:</em></p><ul><li><em>This code handles the parameters associated with your MLflow run. Parameters often include hyperparameters, model configurations, and other settings used in your experiments.</em></li><li><em>It scans the specified directory for parameter files and extracts the parameter name (key) and its corresponding value.</em></li><li><em>For each parameter, the code generates an SQL query to insert the parameter information into the PostgreSQL database.</em></li><li><em>Proper error handling is in place to address potential exceptions or integrity errors during the insertion process.</em></li></ul><p><em>Usage:</em></p><p><em>To put this code to use, create an instance of the </em><em>MLFlowDatabase class and call the </em><em>insert_params_to_db method. This will insert the parameters linked to your MLflow runs into your PostgreSQL database, enabling you to document and review the specific configurations of each experiment.</em></p><p><em>In the next section, we will discuss “Inserting Metrics,” a crucial aspect of recording and analyzing the performance of your machine learning models. Join us as we continue our journey towards efficient machine learning project management.</em></p><blockquote><strong>Inserting Metrics:</strong></blockquote><p><em>In this section, we will guide you through the process of inserting metrics associated with your machine learning runs into your PostgreSQL database. Metrics play a crucial role in understanding the performance of your models and experiments, allowing you to track key indicators and make data-driven decisions.</em></p><pre>def insert_metrics_to_db(self):<br>    metrics_dir = self run_path + &#39;metrics/&#39;<br>    metrics = []<br><br>    for filename in os.listdir(metrics_dir):<br>        filepath = os.path.join(metrics_dir, filename)<br>        with open(filepath, &#39;r&#39;) as f:<br>            key = os.path.split(filename)[1]<br>            f_read = f.read().strip().split(&#39; &#39;)<br>            value = f_read[1]<br>            timestamp = f_read[0]<br>            step = f_read[2]<br>            is_nan = &#39;&#39;<br>            if value != 0:<br>                is_nan = &#39;false&#39;<br>            result = (key, value, timestamp, step, is_nan)<br>            metrics.append(result)<br><br>    for metric in metrics:<br>        key = metric[0]<br>        value = metric[1]<br>        timestamp = metric[2]<br>        step = metric[3]<br>        is_nan = metric[4]<br>        query_metrics = &quot;INSERT INTO metrics (key, value, timestamp, run_uuid, step, is_nan) VALUES (%s, %s, %s, %s, %s, %s);&quot;<br>        query_latest_metrics = &quot;INSERT INTO latest_metrics (key, value, timestamp, run_uuid, step, is_nan) VALUES (%s, %s, %s, %s, %s, %s);&quot;<br><br>        try:<br>            self.cur.execute(query_metrics, (key, value, timestamp, self.run_uuid, step, is_nan))<br>            self.cur.execute(query_latest_metrics, (key, value, timestamp, self.run_uuid, step, is_nan))<br>        except psycopg2.IntegrityError as e:<br>            error_message = e.pgerror<br>            if &quot;Key (key, run_uuid)=&quot; in error_message:<br>                print(&quot;ID already exists.&quot;)<br>            else:<br>                print(&quot;Error occurred while inserting metrics and latest_metrics:&quot;, e)<br>        except Exception as e:<br>            print(&quot;Error occurred while inserting metrics and latest_metrics:&quot;, e)<br><br>    self.conn.commit()</pre><p><em>Explanation:</em></p><ul><li><em>This code focuses on handling the metrics collected during your MLflow runs. Metrics typically include performance statistics, such as accuracy, loss, or any custom-defined metrics for your machine learning models.</em></li><li><em>It scans the metrics directory associated with your MLflow run, extracting information such as metric name, value, timestamp, step, and whether the value is NaN (not-a-number).</em></li><li><em>For each metric, the code generates two SQL queries: one to insert the metric into the </em><em>metrics table and another to insert it into the </em><em>latest_metrics table. The latter is used for quick access to the most recent metrics.</em></li><li><em>Proper error handling is in place to address potential exceptions or integrity errors during the insertion process.</em></li></ul><p><em>Usage:</em></p><p><em>To implement this code, create an instance of the </em><em>MLFlowDatabase class and call the </em><em>insert_metrics_to_db method. This will insert the metrics recorded during your MLflow runs into your PostgreSQL database, providing a comprehensive view of your experiment&#39;s performance over time.</em></p><p><em>With the completion of this section, you’ve learned how to centralize not only the metadata, tags, and parameters but also the crucial metrics of your machine learning experiments. In the next segment, we will discuss how to integrate your local MLflow artifacts into a centralized storage solution, such as Minio. Stay tuned for our continued journey to streamline your machine learning workflow.</em></p><blockquote><strong>Automating the Migration Process:</strong></blockquote><p><em>To streamline the migration process and facilitate the transition of multiple runs from your local MLflow experiments to a centralized instance, you can use the provided Python script. This script automates the entire migration process, making it more efficient and less error-prone.</em></p><p><em>Here’s how it works:</em></p><pre>run_paths = glob.glob(&#39;/PATH/TO/ML_RUNS/mlruns/0/*/&#39;)<br><br>for run_path in run_paths:<br>    mlflow_conn = MLFlowDatabase(run_path=run_path)<br><br>    mlflow_conn.insert_run_metadata()<br>    mlflow_conn.insert_tags_to_db()<br>    mlflow_conn.insert_params_to_db()<br>    mlflow_conn.insert_metrics_to_db()</pre><ol><li><em>List Run Paths: The script starts by listing all the run paths for your local MLflow experiments using the </em><em>glob module. These run paths represent the different experiments you have conducted locally.</em></li><li><em>Iterate Over Runs: It then iterates through each run path, creating an instance of the </em><em>MLFlowDatabase class for each run. This class encapsulates the logic for inserting run metadata, tags, parameters, and metrics into the centralized PostgreSQL database.</em></li><li><em>Inserting Data: For each run, the script inserts the run metadata, tags, parameters, and metrics into the respective database tables. This process centralizes the information and makes it readily accessible in your centralized MLflow instance.</em></li></ol><p><em>By running this script, you can effectively centralize your local MLflow experiments with minimal manual effort. It’s a practical approach for teams or individuals dealing with a significant number of experiments.</em></p><p><em>This automation not only saves time but also reduces the likelihood of errors during the migration process. As a result, you can focus on analyzing and deriving insights from your experiments rather than spending excessive time on administrative tasks.</em></p><p><em>With the completion of this script, you’ve acquired a valuable tool for managing and centralizing your machine learning experiments efficiently. As you continue to scale your MLflow projects and conduct more experiments, this automation will prove to be an indispensable asset, enhancing your productivity and fostering a more collaborative and organized environment for your machine learning endeavors.</em></p><p><strong><em>Conclusion and Key Takeaways:</em></strong></p><p><em>In this comprehensive guide, we have explored the process of migrating your local MLflow experiments to a centralized MLflow instance, creating a robust infrastructure for your machine learning projects. Let’s recap what we’ve accomplished and the valuable insights gained:</em></p><ol><li><em>Centralization for Collaboration: Centralizing your MLflow experiments allows teams to collaborate efficiently and access experiments from a single platform, irrespective of their origin. This enhances teamwork and knowledge sharing.</em></li><li><em>Requirements for Centralization: We’ve discussed the fundamental components required for centralizing your MLflow experiments, including a centralized MLflow instance, a PostgreSQL database to store experiment metadata, and a Minio bucket for artifact storage.</em></li><li><em>Uploading Model Artifacts: We began our journey by detailing how to upload model artifacts to a centralized storage solution, such as Minio. This ensures that your model files are accessible, organized, and secured in a centralized location.</em></li><li><em>Inserting Run Metadata: We delved into the insertion of run metadata into a PostgreSQL database. This metadata includes essential information about each experiment, such as run name, user details, timestamps, and artifact paths.</em></li><li><em>Handling Tags: Tags play a crucial role in categorizing and organizing experiments. We learned how to insert tags associated with MLflow runs into the database, making it easier to search and filter experiments.</em></li><li><em>Documenting Parameters: We covered the insertion of experiment parameters, which includes hyperparameters and configuration settings, into the PostgreSQL database. This documentation is vital for reproducibility and understanding the context of each experiment.</em></li><li><em>Recording Metrics: Metrics are essential for assessing the performance of machine learning models. We explored how to insert metrics into the database, enabling you to track the evolution of model performance over time.</em></li><li><em>Bulk Migration: To streamline the migration process, we provided a Python script that automates the migration of multiple runs in one go, saving time and effort.</em></li></ol><p><em>By following the steps outlined in this guide, you can establish a centralized platform for managing, tracking, and collaborating on your machine learning experiments. This results in improved workflow efficiency, better reproducibility, and enhanced team collaboration.</em></p><p><em>As you continue on your machine learning journey, keep in mind the importance of centralization and effective experiment management. Whether you are a data scientist, machine learning engineer, or researcher, the techniques and insights shared in this guide will empower you to take control of your MLflow experiments and make informed decisions based on the valuable data they provide.</em></p><blockquote>Lastly, I warmly invite you to learn more about our company. Visit our <a href="https://lionswerk.de/services/mlops/">website</a> to explore our services in depth.</blockquote><blockquote>Whether you have inquiries or seek more information, our support <a href="https://lionswerk.slack.com/">chat</a> is available, or you can reach out through various communication options provided on our website.</blockquote><blockquote>We are eager to assist and look forward to connecting with you.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=827be9e064f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/yelassad/migrating-local-mlflow-experiments-to-a-centralized-mlflow-instance-827be9e064f9">Migrating Local MLflow Experiments to a Centralized MLflow Instance</a> was originally published in <a href="https://medium.com/yelassad">yelassad</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLflow with remote Tracking Server, backend and artifact stores]]></title>
            <link>https://medium.com/yelassad/mlflow-with-remote-tracking-server-backend-and-artifact-stores-39912680a464?source=rss----b694c5719f35---4</link>
            <guid isPermaLink="false">https://medium.com/p/39912680a464</guid>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[mlflow-registry]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Zakariae Mkassi]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 11:02:26 GMT</pubDate>
            <atom:updated>2023-10-31T11:19:49.367Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VADQx00Mvsrx3KEcQ8X7Aw.png" /></figure><p><a href="https://mlflow.org/docs/latest/concepts.html">MLflow</a> is <strong><em>an open source platform to manage and track the ML lifecycle</em></strong>, including experimentation, reproducibility, deployment, and a central model registry.</p><p>MLflow has the ability to work with distributed architectures, which allows the tracking server, backend store, and artifact store to be located on remote hosts. For instance, consider the following scenario where a remote MLflow Tracking Server is used, along with a Postgres database for backend entity storage, and an S3 bucket for artifact storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYRPcnLlW9MznPKTr7ZFfA.png" /></figure><h3>Why use Docker with MLflow?</h3><p>By containerizing the MLflow server, it becomes easier to deploy and manage the server across different environments. Additionally, by using a remote artifact store and backend store, it is possible to use MLflow in a distributed architecture. This can be particularly useful when working with large datasets or when collaborating with multiple team members on a project.</p><h3>Postgresql Side:</h3><p>first thing to do is to create a separate user and database that dedicated to mlflow, by creating a separate user and database for each service, you can limit the scope of access that each service has to the database. If a service has a bug or vulnerability that allows an attacker to access the database, the attacker will only be able to access the data associated with that service, rather than the entire database. In addition, having a separate database for each service can make it easier to troubleshoot errors. If an error occurs, you can look at the logs and data associated with the specific service, rather than having to sift through a large database with data from multiple services.</p><p>to create a new user in PostgreSQL you should open a terminal where PostgreSQL is running and log in as a superuser :</p><pre>sudo -u postgres psql</pre><p>Create the new user “MLFLOW_USER” and set the password “PASSWORD”</p><pre>CREATE USER &lt;&lt;MLFLOW_USER&gt;&gt; WITH PASSWORD &lt;&lt;&#39;PASSWORD&#39;&gt;&gt;;</pre><p>Grant the user permission to create a database:</p><pre>ALTER USER &lt;&lt;MLFLOW_USER&gt;&gt; CREATEDB;</pre><p>create database “mlflow_db” that will be used by MLflow:</p><pre>CREATE DATABASE &lt;&lt;MLFLOW_DB&gt;&gt; OWNER &lt;&lt;MLFLOW_USER&gt;&gt;;</pre><h3>MinIO S3:</h3><p>MLflow major ability is the ability to log and store the artifacts generated during the machine learning workflow, such as models, data, and visualizations. These artifacts can be critical for reproducing and understanding the results of a machine learning experiment. To manage and store those artifacts in a scalable, durable, and secure way, you need to use S3 bucket.</p><p>To do that open MinIO web interface <a href="http://10.10.10.40:9001/">http://&lt;IP_ADRESSE&gt;:900</a>0 in a web browser. After log in with your credentials, click on “Bucket” and afterwards “Create Bucket” button.</p><p>In the “Bucket Name” field, enter a unique name for your bucket, something like “mlflow”. (Bucket names must be globally unique across all of S3)</p><ul><li>(Optional) Set a versioning policy for the bucket to enable versioning for objects.</li><li>(Optional) Set a Quota for the bucket to to limit the amount of data in the bucket.</li></ul><h3>MLflow Docker Image:</h3><p>Next is to create a Dockerfile that builds a Docker image with MLflow and use S3 minIO Bucket as an artifact store und PostgreSQL as a backend store.</p><p><strong>Dockerfile</strong></p><pre># Start from a base image with Python installed<br>FROM python:3.9</pre><pre># Install mlflow and dependencies<br>RUN pip install \<br>    mlflow \<br>    psycopg2 \<br>    boto3 &amp;&amp; \<br>    mkdir /mlflow/</pre><pre># Expose the default MLflow server port<br>EXPOSE 5000</pre><pre># Start the MLflow server when the container starts<br>CMD mlflow server \<br>    --host 0.0.0.0 \<br>    --port 5000 \<br>    --artifacts-destination s3://mlflow \<br>    --backend-store-uri postgresql://&lt;&lt;MLFLOW_USER&gt;&gt;:&lt;&lt;PASSWORD&gt;&gt;!@&lt;&lt;IP_ADDRESS&gt;&gt;:5432/&lt;&lt;MLFLOW_DB&gt;&gt;</pre><ul><li>--backend-store-uri specifies the URI for the MLflow backend store. The backend store is responsible for storing experiment and run metadata, such as run parameters, metrics, and artifacts. In this case, we&#39;re setting the backend store URI to the value to mlflow database that we did created at the beginning.</li><li>--artifacts-destination specifies the destination URI for storing artifacts. Artifacts are any files or data that are produced or used during the course of a run, such as trained models, visualizations, or data files. In this case, we&#39;re setting the artifacts-destination to the same value as the S3 bucket that’s was before created.</li><li>--host specifies the network interface to bind to. In this case, we&#39;re setting it to 0.0.0.0, which means that the MLflow server will be accessible from any network interface on the container host.</li></ul><p><strong>Docker build</strong></p><p>now is the turn of building the Docker image using the Docker file, to do that, let’s run the docker build command to build the Docker image. This command uses the Dockerfile to build the image and saves it the local machine.</p><pre>sudo docker build -t mlflow-server:latest .</pre><p><strong>Push Docker image in the private Registry</strong></p><p>to be able to push the new created image to the registry when need to log in, to do that we will run the following command</p><pre>docker login -u &lt;user&gt; -p &lt;password or acces-token &gt; my_registry.com<br>docker push mlflow-server:&lt;TAG&gt;</pre><p><strong>Run MLflow Container</strong></p><p>To run MLflow as a container and to use a remote S3 bucket as the artifact store, you will need to configure your MLflow container to use the appropriate credentials and endpoint to access the bucket.</p><p>so first thing to do is to create an environment variable file to configure all the needed settings, the file will be named mlflow.env and will look like the following:</p><pre>AWS_ACCESS_KEY_ID=&lt;&lt;YOUR_AWS_ACCESS_KEY_ID&gt;&gt;<br>AWS_SECRET_ACCESS_KEY=&lt;&lt;AWS_SECRET_ACCESS_KEY&gt;&gt;<br>S3_ENDPOINT_URL=http://&lt;&lt;IP_ADDRESS&gt;&gt;:9000<br>MLFLOW_S3_IGNORE_TLS=true</pre><p>📌 By S3_ENDPOINT_URL You must be sure that you are given the minIO API port number and not the console port number</p><p>next thing is the real a shell script that will make easier to run the container each time needed, the shell script name will be ‘mlflow.sh’ and will look like the following:</p><p>NoneBashCSSCC#ElixirGoHTMLObjective-CJavaJavaScriptJSONKotlinMermaid DiagramPerlPHPPowershellPythonRubyRustSQLSoliditySwiftTypeScriptYAMLCopy</p><pre>docker run --rm \<br>         -p 5000:5000 \<br>         --name=mlflow-server \<br>         --env-file=mlflow.env \<br>        -d  mlflow-server:&lt;&lt;TAG&gt;&gt;</pre><p>make the file executable</p><pre>chmod +x mlflow.sh</pre><p>and execute the shell script with the command ./mlflow.sh</p><p>after starting your container you will be able to access mlflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xOpQnCRUYrVj67E8EULVhQ.png" /></figure><p>Lastly, I warmly invite you to learn more about our company. Visit our <a href="https://lionswerk.de/services/mlops/">website</a> to explore our services in depth.</p><p>Whether you have inquiries or seek more information, our support <a href="https://lionswerk.slack.com/">chat</a> is available, or you can reach out through various communication options provided on our website.</p><p>We are eager to assist and look forward to connecting with you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39912680a464" width="1" height="1" alt=""><hr><p><a href="https://medium.com/yelassad/mlflow-with-remote-tracking-server-backend-and-artifact-stores-39912680a464">MLflow with remote Tracking Server, backend and artifact stores</a> was originally published in <a href="https://medium.com/yelassad">yelassad</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>