<?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 Sepideh Ebrahimi on Medium]]></title>
        <description><![CDATA[Stories by Sepideh Ebrahimi on Medium]]></description>
        <link>https://medium.com/@sebrahimi1988?source=rss-f3386c29ab15------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6nKMJYohCmSUAce6uYCO1A.png</url>
            <title>Stories by Sepideh Ebrahimi on Medium</title>
            <link>https://medium.com/@sebrahimi1988?source=rss-f3386c29ab15------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:40:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sebrahimi1988/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[MLOps Gym — Getting started with Feature Store]]></title>
            <link>https://medium.com/@sebrahimi1988/mlops-gym-getting-started-with-feature-store-59909fa01443?source=rss-f3386c29ab15------2</link>
            <guid isPermaLink="false">https://medium.com/p/59909fa01443</guid>
            <dc:creator><![CDATA[Sepideh Ebrahimi]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 10:25:23 GMT</pubDate>
            <atom:updated>2024-09-18T08:09:02.196Z</atom:updated>
            <content:encoded><![CDATA[<h3>MLOps Gym — Getting started with Feature Store</h3><p>This article is authored by <a href="https://www.linkedin.com/in/ben-mackenzie-5319aa17/">Ben MacKenzie</a> and <a href="https://www.linkedin.com/in/danielsparing/">Daniel Sparing</a> and originally published on <a href="https://community.databricks.com/t5/technical-blog/mlops-gym-databricks-feature-store/ba-p/67430">Databricks Community</a>. All the credit belongs to Ben and Daniel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*atiNDW6wzbmZx07Z" /></figure><p>This is the first of three articles about using the Databricks Features Store. The first article will focus on using existing features to create your dataset and the basics of creating feature tables. The second article will cover feature table creation in greater depth, feature discovery, and ensuring maximum re-usability. The final article will discuss feature and function serving and using the feature store with external models.</p><h3>What is a Feature Store?</h3><p>Machine learning uses existing data to build a model to predict future outcomes. In almost all cases, the raw data requires preprocessing and transformation before it can be used to build a model. This process is called feature engineering, and the outputs of this process are called features — the building blocks of the model.</p><p>Developing features is complex and time-consuming. An additional complication is that for machine learning, feature calculations need to be done for model training and then again when the model is used to make predictions. These implementations may not be performed by the same team or using the same code environment, which can lead to delays and errors. Additionally, different teams in an organization will often have similar feature needs but may not be aware of the work that other teams have done. A feature store is designed to address these problems.</p><p>A feature store is a centralized repository that enables data scientists to find and share features and also ensures that the same code used to compute the feature values is used for model training and inference.</p><h3>Databricks Feature Store</h3><p>Databricks’ <a href="https://docs.databricks.com/en/machine-learning/feature-store/index.html">Feature Store</a> has been merged into Unity Catalog (now referred to as “Feature Engineering in Unity Catalog”). Features are stored in Feature tables, which are regular Delta tables with primary keys and, optionally a timestamp key identified. This integration enables a number of capabilities.</p><ul><li><strong>Unified permissions model: </strong>Reduces platform complexity with a consistent approach to securing and governing your Data and AI assets</li><li><strong>Discoverability:</strong> The Feature Store UI, accessible from the Databricks workspace, lets you browse and search for existing features.</li><li><strong>End-to-end Lineage</strong>: Better understand both the upstream — i.e. the data sources — and downstream dependencies, such as the models, notebooks, jobs, and endpoints that reference the features. access the models, notebooks, jobs, and endpoints that use the feature.</li><li><strong>Data monitoring:</strong> Enhanced/Improved data monitoring: proactively detect and monitor your models to mitigate against data and model drift</li></ul><p>In addition to these capabilities provided by Unity Catalog there are a number of other capabilities provided by the service:</p><ul><li><strong>Integrates with model scoring and </strong><a href="https://docs.databricks.com/en/machine-learning/model-serving/index.html"><strong>serving</strong></a>. When you use features from Feature Store to train a model, the model is packaged with feature metadata. When you use the model for batch scoring or online inference, it automatically retrieves features from the Feature Store. The caller does not need to know about them or include logic to look up or join features to score new data. This makes model deployment and updates much easier.</li><li><strong>Point-in-time lookups</strong>. Feature Store supports time series and event-based use cases that require point-in-time correctness ensuring that no future data is used for training.</li><li><a href="https://docs.databricks.com/en/machine-learning/feature-store/online-feature-stores.html"><strong>Synchronizes</strong></a><strong> with online row-oriented data stores</strong> to enable online inference.</li><li><a href="https://docs.databricks.com/en/machine-learning/feature-store/on-demand-features.html"><strong>On-demand Features</strong></a></li><li><a href="https://docs.databricks.com/en/machine-learning/feature-store/feature-function-serving.html"><strong>Feature Serving</strong></a></li></ul><h3>Delta Tables vs Feature Tables</h3><p>Integrating the Feature Store with Unity Catalog unlocks a lot of capabilities and simplifies its use. It does raise a question though: is there any distinction between a Feature Table and a regular Delta table (assuming a primary key has been defined)?</p><p>From a technical perspective, there is no distinction. Any table (with a PK defined) can be used as a feature table. Whether it will be useful or not depends on what you are trying to do. Keep in mind that for standard machine learning algorithms all of the features for a given example must be condensed into a single row. This often means that data needs to be aggregated before it can be used in a machine learning model.</p><p>For example, suppose you are building a customer churn model and you have a fact table of customer interactions with your support organization. Is there relevant information there? Certainly! Can you use the fact table as is? I.e., in the context of a customer churn model could it be a feature table? No. The reason is simple: there is a one-to-many relationship between the customer and the interactions table. In a training set, each example must be a single row, so you would need to aggregate your interactions by the customer before you can use it as a feature table to predict if a specific customer will churn.</p><p>What if the entity you are making predictions about is an ‘event’ or a ‘fact’ — for example, whether a credit card or bank transfer transaction is fraudulent? In this case it does make sense to think of the fact table as a feature table. Any relevant dimension could also be regarded as a feature table. However, if there was an important signal in prior transaction history (for which there is a one-to-many relationship with the fact you are making a prediction about) you’d need to aggregate this before using it in a machine learning model.</p><h3>Using the Feature Store</h3><p>Let’s work through a simple example of using the Feature Store to create a training data set for a customer churn model. For now, we’ll assume that all of the features we want are already available in the feature store.</p><h3>Defining a lookup DataFrame</h3><p>We need to build a dataframe that includes the lookup keys and the ground truth label. The lookup keys consist of the primary key of the entity you are making predictions about and any foreign keys needed to retrieve relevant features. A timestamp is also required if any features of interest include a timestamp key (which is very often the case). There is a good example of this in the <a href="https://learn.microsoft.com/en-us/azure/databricks/machine-learning/feature-store/time-series#how-time-series-feature-tables-work.">documentation</a>.</p><p>How you construct this dataframe is critical to your machine learning effort. It determines what entities you include in your training data set, the point in time to retrieve a set of features (where applicable), and the label. We find it convenient to refer to this as the <strong>EOL dataframe</strong> (Entity, Observation time, Label).</p><p>Let’s suppose we track customer renewals in a table called <em>customer_subscriptions</em>. Here’s an example of how we might construct our <strong>EOL dataframe</strong>. Notice that we are setting the observation date to 3 months prior to the renewal data — this is so that our model will learn to predict when a customer is likely to churn while there is still time for us to take action. Notice also that we are only looking at customers with a 3-year contract.</p><pre>spark.sql(<br>    &quot;<br>    CREATE OR REPLACE VIEW renewal_eol AS<br>    SELECT    customer_id<br>             , to_date(dateadd(month, -3, renewal_date)) AS observation_date<br>             , churn <br>    FROM    customer_subscriptions<br>    WHERE   contract_length = 3<br>    &quot;<br>)<br><br>eol_df = spark.sql(&#39;select * from renewal_eol&#39;)</pre><h3>Defining Features to use in our model</h3><p>Let’s assume that we have pre-existing feature tables with information about consumption growth, interactions with customer service and the customer. We use the Databricks FeatureLookup API to define the features to include in our dataset:</p><pre>from databricis.feature_engineering.entities.feature_lookup import FeatureLookup<br><br>feature_lookups = [<br>   FeatureLookup(<br>       table_name=&quot;default.consumption_growth&quot;,<br>       feature_names=[&quot;6_month_growth_p1&quot;, &quot;6_month_growth_p2&quot;],<br>       lookup_key=&quot;customer_id&quot;,<br>       timestamp_lookup_key = &quot;observation_date&quot;<br>   ),<br>   FeatureLookup(<br>       table_name=&quot;default.customer_service_calls&quot;,<br>       feature_names=[&quot;customer_service_count&quot;],       <br>       lookup_key=&quot;customer_id&quot;,<br>       timestamp_lookup_key = &quot;observation_date&quot;<br>   ),<br>   FeatureLookup(<br>       table_name=&quot;default.customers&quot;,<br>       feature_names=[&quot;tier&quot;],       <br>       lookup_key=&quot;customer_id&quot;,<br>       timestamp_lookup_key = &quot;observation_date&quot;<br>   )<br>    <br>]</pre><h3>Generating a training dataset</h3><p>With our EOL dataframe and feature lookup definition, we are ready to create a training dataset using the FeatureEngineeringClient.</p><pre>from databricks.feature_engineering import FeatureEngineeringClient<br><br>fs = FeatureEngineeringClient()<br>training_set = fe.create_training_set(df=eol_df, feature_lookups=feature_lookups, label=&quot;churn&quot;)</pre><p>Notice that we used features from multiple tables to construct a training dataset. This will often be the case especially when you are using features that another team has already created for you and there simply will not be a single ready-made feature table with everything you need. Organizing feature tables by domain, source tables, update frequency or other criteria is important for getting the most out of a feature store. We’ll discuss this in more detail in the next blog article in this series.</p><p>See also the <a href="https://docs.databricks.com/en/machine-learning/feature-store/train-models-with-feature-store.html">Databricks documentation</a> and more detailed example <a href="https://docs.databricks.com/en/machine-learning/feature-store/example-notebooks.html">notebooks</a>.</p><h3>Mixing feature tables and non-feature tables for training</h3><p>In the above example, we assumed that all of our features were available in the feature store already. In many cases, you’ll want to use features that have not yet been stored in feature tables. To include these simply add them to the EOL dataframe. Features that will only be available at inference time (for example the amount of a credit card transaction) must be included in the EOL dataframe. See <a href="https://docs.databricks.com/en/machine-learning/feature-store/train-models-with-feature-store.html#train-and-score-a-model-using-a-combination-of-feature-store-features-and-data-residing-outside-feature-store">here</a>.</p><h3>Saving a model</h3><p>Once the model is trained using an ML algorithm flavor known to MLflow, in order to capture the feature lookup information we need to log the model with <a href="https://api-docs.databricks.com/python/feature-engineering/latest/feature_engineering.client.html?highlight=log_model#databricks.feature_engineering.client.FeatureEngineeringClient.log_model">log_model()</a> passing the model object and the TrainingSet object created earlier by <em>create_training_set</em>, see <a href="https://docs.databricks.com/en/machine-learning/feature-store/train-models-with-feature-store.html#train-models-and-perform-batch-inference-with-feature-tables">this section</a> or the <a href="https://docs.databricks.com/en/machine-learning/feature-store/train-models-with-feature-store.html#train-models-and-perform-batch-inference-with-feature-tables">notebook examples</a> for more details.</p><h3>Using a model for inference</h3><p>For batch inference, use <a href="https://api-docs.databricks.com/python/feature-engineering/latest/feature_engineering.client.html?highlight=score_batch#databricks.feature_engineering.client.FeatureEngineeringClient.score_batch">score_batch()</a> passing the model URI and the data frame to be scored; see <a href="https://api-docs.databricks.com/python/feature-engineering/latest/feature_engineering.client.html?highlight=score_batch#databricks.feature_engineering.client.FeatureEngineeringClient.score_batch">this section</a> or the <a href="https://docs.databricks.com/en/machine-learning/feature-store/train-models-with-feature-store.html#train-models-and-perform-batch-inference-with-feature-tables">notebook examples</a> for more details including how to get the model URI from the model name.</p><h3>Train a model with AutoML and Feature Tables</h3><p>You can also make use of Feature tables when using Databricks AutoML: this means that you are able to point AutoML to the same EOL table as you defined above. In this case, you would need to specify the feature tables to use either in the <a href="https://docs.databricks.com/en/machine-learning/automl/train-ml-model-automl-ui.html#feature-store">AutoML UI</a> or using the API and setting the <a href="https://docs.databricks.com/en/machine-learning/automl/train-ml-model-automl-api.html#classification-and-regression-parameters">feature_store_lookups</a> parameter.</p><h3>Notes on ‘point-in-time’ lookup</h3><p>In many cases the value of a feature changes over time. In such cases, you need a timestamp key in your feature table. When you retrieve the feature using the API you must include the observation date as described above. The Feature Store API will perform an ‘AS OF’ join to ensure that the most recent value of the feature at the time of the timestamp is used in the training set. See the <a href="https://learn.microsoft.com/en-us/azure/databricks/machine-learning/feature-store/time-series#how-time-series-feature-tables-work">documentation</a> for more details.</p><h3>Creating Feature Tables</h3><p>Here are a few examples of creating feature tables. In practice, this simply means identifying the Primary and optionally the Timeseries key using SQL DDL or the Python feature_engineering API. Any table can be used but often they will be dimension, fact, or aggregation tables so we are using standard data dimensional modeling language here. Note that we are not suggesting that an existing ‘star schema’ model will suffice for all of your ML needs. You will almost certainly need to create new tables (or extend existing ones) to capture important features for ML requirements.</p><h3>Type 1 Dimension Table</h3><p>A type 1 dimension table (for example a customer table) can be used as a feature table as long as the PK has been defined.</p><pre>ALTER TABLE customer ADD CONSTRAINT pk_customers PRIMARY KEY(customer_id)</pre><p>Alternatively</p><pre>from databricks.feature_engineering import FeatureEngineeringClient <br>fe = FeatureEngineeringClient()<br>fe.write_table(<br>  name=&#39;customer&#39;,<br>  primary_keys = [&#39;customer_id&#39;]<br>  df = customer_features_df<br> )</pre><h3>Type 2 Dimension Table</h3><p>A type 2 dimension table (for example a customer table) will have two columns to indicate the time range for which a particular row is active. These columns are generally a variant of ‘start date’ and ‘end date’. To use this kind of table as a feature table, define a primary key as a combination of the entity id (for example a customer id) and the column corresponding to the ‘start date’. For example:</p><pre>ALTER TABLE customer ADD CONSTRAINT pk_customers PRIMARY KEY(customer_id, row_effective_from TIMESERIES)</pre><p>Alternatively</p><pre>from databricks.feature_engineering import FeatureEngineeringClient <br>fe = FeatureEngineeringClient()<br>fe.write_table(<br>  name=&#39;customer&#39;,<br>  primary_keys = [&#39;customer_id&#39;, &#39;row_effective_from&#39;]<br>  df = customer_features_df,<br> )</pre><p>The point-in-time lookup capability in the Feature Store API will ensure that the correct row is used.</p><h3>Fact Table</h3><p>If your model makes predictions about an entity represented in a fact table (e.g, is a particular transaction fraudulent?) then just make sure the table includes a primary key constraint:</p><pre>ALTER TABLE transaction ADD CONSTRAINT pk_transaction_id PRIMARY KEY(transaction_id)</pre><p>If your model makes predictions about some other entity but there is important signal in the fact table, you would typically aggregate the facts and store the results in a new table. For example if your model is trying to detect credit fraud you might aggregate facts related to account transfers over some time window. This example is dealt with below.</p><p>The case where you don’t want to aggregate the facts in some way is rare. In practice this means you want to retrieve that fact that is closest — but prior to — the observation date. To do this simply include a timestamp in the primary key constraint on the fact table.</p><p>Note that the fact table needs to include the entity pk as a foreign key in order to be able to perform the lookup.</p><h3>Aggregation Table</h3><p>As discussed above a model will often include information from a related fact table. Typically these facts are aggregated based on the associated entity (e.g., customer) and a time window (though a simple aggregation based on the entity alone is possible).</p><p>Except in the case of a simple aggregation based on the related entity you must include a timeseries column in the primary key constraint. In a later module we will discuss the time density of aggregation (e.g,. Are 30 day running aggregations computed every day? week?).</p><pre>ALTER TABLE aggregation_table ADD CONSTRAINT pk_entity PRIMARY KEY(entity_id, timestamp TIMESERIES)</pre><p>Alternatively</p><pre>from databricks.feature_engineering import FeatureEngineeringClient <br>fe = FeatureEngineeringClient()<br>fe.write_table(<br>  name=&#39;aggregation_table&#39;,<br>  primary_keys = [&#39;entity-id&#39;, &#39;timestamp&#39;]<br>  df = aggregation_df,<br> )</pre><h3>Preprocessing Features</h3><p>The last step in feature engineering often involves transforming features to make them usable by particular machine learning algorithms. This is often referred to as pre-processing: transformations like scaling, normalizing, imputation and one-hot-encoding. Pre-processing should be performed as part of the model itself (for example in a sklearn pipeline) not performed ahead of time and included in the Feature Store. This allows data scientists to choose the kind of pre-processing appropriate for the algorithm they are using.</p><h3>Putting it all together</h3><p>In many machine learning projects you will use existing features as well as create new features for your model. This section highlights some of the key steps.</p><ol><li>Start with your EOL definition. Define what entities you want to make predictions about. You may want to segment by geography or other characteristics. Define your ‘observation date’ and the associated label.</li><li>Define feature lookups for existing features. If there are relevant features already available in your model define the feature lookup structure.</li><li>Add new features to the EOL dataframe. Any new features that you want to use should be calculated and added to the EOL dataframe.</li><li>Use the feature API to generate a training dataset.</li><li>Build and evaluate your model and your features. How well does the model perform? Which features are significant?</li><li>Repeat the process until you are satisfied with the model and your features. You will likely experiment with the mode algorithm and hyper-parameters. But you will also want to experiment with features and observation dates.</li></ol><p>Once you have a model you are happy with, new features should be saved in one or more feature tables along with appropriate pipelines for keeping them updated. This applies to all features except those that will only be available at inference time. These features need to be provided by the requesting system. When training a model using the feature store these features remain in the EOL dataframe.</p><p>Once you have created your new feature tables you should update the feature lookups to include the new features. Then re-build your model from scratch using an EOL dataframe.</p><p>When creating a new feature table you want to consider the following:</p><ol><li>What entities should be included? Your model may target only a subset of the entities it is making predictions about (e.g., it may only target customers in a geographic region). In order to maximize the reusability of your feature table across different data science teams, you may want to include all customers.</li><li>How much history to include?</li><li>How frequently should time-dependent features be re-calculated?</li></ol><p>For now, you might just include what is needed for your model. In future articles, we’ll discuss strategies to ensure that your features can be used by as many teams as possible.</p><h3>Coming up next!</h3><p>Next blog in this series: MLOps Gym — Getting started with version control in Databricks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59909fa01443" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps Gym — Some thoughts on the intersection of distributed systems and machine learning]]></title>
            <link>https://medium.com/@sebrahimi1988/mlops-gym-some-thoughts-on-the-intersection-of-distributed-systems-and-machine-learning-e13279650ad3?source=rss-f3386c29ab15------2</link>
            <guid isPermaLink="false">https://medium.com/p/e13279650ad3</guid>
            <dc:creator><![CDATA[Sepideh Ebrahimi]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 15:40:53 GMT</pubDate>
            <atom:updated>2024-09-17T10:52:50.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>MLOps Gym — Some thoughts on the intersection of distributed systems and machine learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IiTX7vKu6HeQ5X0_" /></figure><p>This article is written by <a href="https://www.linkedin.com/in/stuart-lynn/">Stuart Lynn</a> and originally published on <a href="https://community.databricks.com/t5/technical-blog/mlops-gym-harnessing-the-power-of-apache-spark-in-data-science/ba-p/68712">Databricks Community</a> and <a href="https://rightascension.substack.com/p/some-thoughts-on-the-intersection">Substack</a>. All the credit belongs to Stuart.</p><h3>Introduction and context</h3><p>This article describes the key ways in which data scientists can exploit the parallelisation power of <a href="https://spark.apache.org/">Apache Spark </a>to optimise their workflows, solve a new set of problems and scale their solutions for production applications. It identifies a number of specific tasks within the data science/machine learning domain that are good candidates for Spark and describes how Spark can be used to tackle these.</p><p>Many data science teams build solutions using Python-based tooling in a local (or basic cloud VM-based) development environment. Usually, this means they are subject to the following constraints:</p><ul><li>the data must fit in memory; and</li><li>the ability to parallelise tasks is limited to packages that provide support for multithreading.</li></ul><p>You can, of course, work around these (e.g., <a href="https://www.tensorflow.org/tutorials/distribute/input">lazy loading/sharding of data</a> and orchestrating a parallelisation strategy using libraries such as `<a href="https://docs.python.org/3/library/threading.html">threading</a>`), but this tends to introduce significant complexity and brittleness to workflows.</p><p>By using Databricks and Spark, a number of well-defined design patterns can be followed to overcome these constraints.</p><h3>Identifying opportunities within traditional data science workflows</h3><p>The diagram below asks us to consider the flows of data along the two primary data science workflows. Since the scope of data science work often extends beyond just the use of machine learning to create predictive models, we might choose to refer to these two workflows very generally as: “spotting the pattern” and “exploiting the pattern”. This allows us to expand our discussion to cover tasks from ML-adjacent fields such as operations research, engineering, and bioinformatics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*CCNn_JAYD9iSeWKa" /></figure><p>Let’s explore the three scenarios described in the diagram to understand the issues that might be encountered and how using Spark can help us overcome these.</p><h3>Scenario 1: Pre-processing data required for “spotting the pattern”</h3><p>In the case of tasks like supervised machine learning, “spotting the pattern” generally requires us to feed a large dataset to an algorithm whose objective is to determine the parameters of a model that accurately describes that data. In reality, at least for traditional ML applications, the datasets used for model training are not typically large enough to exhaust the memory available to the machine running the supervised learning process. Where they do exceed this limit, savvy data scientists tend to subsample this data, understanding that there is something of a law of diminishing returns at work here: gains in model performance generated by increasing the available data start to decrease beyond a certain point (see <a href="https://docs.google.com/presentation/d/1F-VqqkuExCGr2nm2BmdsQEashfNzKEQ4dH2nh8c_Pv0/edit#slide=id.g5d7ea79616_0_71">here</a> for a sidebar discussion on this topic).</p><p>Although the final training dataset provided to a model might not exceed the limitations of the model training environment, it is likely produced from more than one upstream dataset, some of which may be very large and require complex aggregations, e.g., turning millions of online shopping transactions into some set of customer behaviour variables by aggregating the number and value of each customer’s transactions over 30, 60 and 90-day intervals within each product category. This is the hurdle described in <em>scenario 1 </em>above.</p><p>In these situations:</p><ul><li>Databricks and Spark can be employed to allow data scientists to perform exploratory data analysis, data pre-processing and feature engineering at a far greater scale than would otherwise be possible.</li><li>This analytical work can be undertaken in the same environment in which models are trained, simulations run, etc. (i.e., the Databricks lakehouse), obviating the need to extract data from a data warehouse in order to begin those processes.</li><li>As a corollary, writing feature engineering code using Spark on Databricks allows for easy ‘productionisation’ of this code (using, e.g., <a href="https://docs.databricks.com/en/workflows/index.html">Databricks Workflows</a>) and greater interlock between the work of data engineers (who typically focus on ingesting new datasets, cleaning them and scheduling updates) and that of the data scientists, including the <a href="https://docs.databricks.com/en/data-governance/unity-catalog/data-lineage.html">ability to track data lineage</a> from ingestion to model training/inference.</li><li>This type of activity does not require the data scientist to master the PySpark API: both <a href="https://docs.databricks.com/en/pandas/pandas-on-spark.html">‘pandas on spark’</a> and <a href="https://docs.databricks.com/en/sql/get-started/visualize-data-tutorial.html">ad-hoc SQL analysis</a> are good alternatives.</li></ul><h3>Scenario 2: When the data isn’t big but the problem is</h3><p>This is exactly the problem described in <em>scenario 2</em>: the inputs to some analytical process are not prohibitively large, but the computations that need to be performed on them are very resource-intensive. There are many categories of problems within the data science domain that fit this description, including</p><ul><li>Simulation and optimization problems;</li><li>Entity resolution and other classes of polynomial time complexity problems; and</li><li>Fine-grained forecasting and other “grouped” model training applications.</li></ul><p>Let’s explore these common examples in turn.</p><h3>Simulation and optimization</h3><p>We have encountered many customers looking to solve simulation and optimization problems using Databricks. Depending on the specifics of the problem, these can be prime candidates for piggybacking on Spark.</p><p>An example of a ‘good’ candidate problem might be optimization at the entity level on a dataset covering multiple entities. We encountered a scenario just like this when working with a consumer goods organization aiming to optimize pricing across multiple markets.</p><p>A proven pattern to address this type of problem efficiently is to write a Spark <a href="https://docs.databricks.com/en/udf/pandas.html">pandas user defined function</a> (UDF) and apply it on a grouped Spark Dataframe. In this way, we can execute arbitrary python code on each group of rows from a Spark Dataframe. Spark feeds each group’s rows to the function as a pandas DataFrame object. The customer in question had already created an optimiser class that worked for a single market at a time so, within the UDF, all we needed to do was determine the parameters required for the optimiser to run and execute it on the incoming pandas DataFrame.</p><p>Let’s explore this solution with a code example. The first element is the basic Python function that runs the optimisation process:</p><pre>def optimise_for_market(pdf: pd.DataFrame) -&gt; pd.DataFrame:<br>    first_row = next(pdf.itertuples())<br>    results_df = pdf.copy()<br>    pricing_optimiser = PricingOptimiser(<br>        input_df=pdf,<br>        market_id=first_row.BU_ID,<br>        experiment=experiment,<br>        max_evals=200,<br>        initial_step_size=100,<br>    )<br>    prices, demand, return_code = pricing_optimiser.optimise()<br>    results_df[&quot;OPTIMAL_PRICE&quot;] = prices<br>    results_df[&quot;EXPECTED_DEMAND&quot;] = demand<br>    results_df[&quot;OPTIMISER_RETURN_CODE&quot;] = return_code<br><br><br>return results_df</pre><p>If you look at the type hints in the function declaration, you’ll see it takes a pandas.DataFrame as an input and returns a pandas.DataFrame. The returned DataFrame contains all of the original columns plus some extra columns with the outputs of the optimisation routine. Just as a side note here: there’s no rule that says the input and output DataFrames need to have the same number of rows, or that the output DataFrame needs to contain any of the same columns as the input.</p><p>The second part is the PySpark transformation that executes this UDF on groups of the input DataFrame’s rows:</p><pre>spark.conf.set(&quot;spark.sql.adaptive.enabled&quot;, &quot;false&quot;)<br>optimiser_return_schema = &quot;BU_ID long, PRODUCT_ID long, STORE_ID long, PRICE_LAST_WEEK double, UNITS_LAST_WEEK long, OPTIMAL_PRICE double, EXPECTED_DEMAND double, OPTIMISER_RETURN_CODE int&quot;<br>optimiser_inputs = opt_dataset___all_markets.repartition(sc.defaultParallelism)<br>optimiser_inputs.cache()<br>(<br>    optimiser_inputs.groupBy(&quot;BU_ID&quot;)<br>    .applyInPandas(optimise_for_market, schema=optimiser_return_schema)<br>    .write.mode(&quot;overwrite&quot;)<br>    .saveAsTable(&quot;optimiser_outputs&quot;)<br>)</pre><p>This is an example of an embarrassingly parallel computation in that none of the calls to the pricing optimization routine rely on the outcome of previous runs. Some aspects worth highlighting here:</p><ul><li>The key part of the pattern is groupBy().applyInPandas(). This will execute the pandas UDF optimise_for_market for each group of rows in its own Spark task.</li><li>We have to explicitly specify the schema of the dataframe returned by the UDF.</li><li>The 1:1 mapping between row group and Spark task is only guaranteed with <a href="https://spark.apache.org/docs/latest/sql-performance-tuning.html#adaptive-query-execution">Adaptive Query Execution</a> disabled. Hence, the spark.sql.adaptive.enabled=false directive is needed.</li></ul><p>Similar examples of ‘good’ problems might come from customers using Monte Carlo simulation or Approximate Bayesian Computation techniques to estimate the distribution of parameters in a model. All calls to the model algorithm are independent and inputs can be sampled ahead of time and represented as rows in an input Spark dataframe used to drive a process like the one above.</p><h3>“Grouped” / granular model training</h3><p>The canonical example here is fine-grained forecasting: producing forecasts at e.g., the store and SKU level. We’ve written about this quite a bit in the past:</p><ul><li>Time Series Forecasting With Prophet And Spark (<a href="https://databricks.com/blog/2020/01/27/time-series-forecasting-prophet-spark.html">blog</a>, <a href="https://www.databricks.com/notebooks/fine-grained-demand-forecasting.html">notebooks</a>)</li></ul><p>Fundamentally, these operations are ‘embarrassingly parallel’ and we would ideally execute runs in parallel. Spark provides the capability to parallelise arbitrary python code using the pandas UDF abstraction that was mentioned further up in this article and this is probably a good place to elaborate a little further on that pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/0*mNf7AsMQvgjb-O7p" /></figure><p>By applying a pandas UDF to a grouped Spark DataFrame, we can provide the rows comprising each group to a separate instance of the function, running inside its own Spark task with these tasks then being distributed across the cluster by the scheduler. In the case of fine-grained forecasting, the function in question would, at the minimum, fit a model to the incoming time series data and probably go on to then extrapolate and output some future predicted values.</p><p>Forecast models of this kind are something of a special case since they are often strongly coupled to recent data and tend to go out of date very quickly. For this reason, the models themselves are not typically persisted, rather, we retrain and perform inference in a single step, often on a daily or more frequent basis.</p><p>When the training and inference processes <em>are</em> logically segregated (e.g., training happens weekly, inference daily), then a grouped model training process will introduce complexity at inference time as the scoring code needs to select the appropriate model based on some input parameter. If your problem exhibits these characteristics, then the following blog will be helpful:</p><ul><li>Bootstrap your large-scale forecasting solution on Databricks with Many Models Forecasting (MMF) Project (<a href="https://medium.com/@anastasia.prokaieva/serve-many-forecasting-models-with-databricks-model-serving-at-once-80d5e3f32943">blog</a>, <a href="https://github.com/databricks-industry-solutions/many-model-forecasting">github project</a>).</li></ul><p>In either case, the mechanism at work here is still groupBy().applyInPandas().</p><h3>Problems that exhibit polynomial or exponential complexity with data volumes</h3><p>The canonical example in this category is <a href="https://en.wikipedia.org/wiki/Record_linkage">entity resolution/record linkage</a>. Spark has all of the internals to partition the problem appropriately and make it scale out successfully. See <a href="https://moj-analytical-services.github.io/splink/">splink</a>, <a href="https://github.com/databricks-industry-solutions/auto-data-linkage">arc</a>, and <a href="https://github.com/zinggai/zingg">zingg</a> as examples of how this can be implemented in practice.</p><p>Within the field of geospatial analytics, there are many operations that exhibit quadratic or worse time complexity, e.g., spatial joins between point and polygon sets for matching events to locations. Many Spark extensions such as <a href="https://github.com/databrickslabs/mosaic">Mosaic</a> and <a href="https://sedona.apache.org/1.5.0/">Sedona</a> have built-in optimisations for partitioning source data appropriately and controlling the complexity of these operations.</p><h3>Scenario 3: Scaling out for high-throughput production applications</h3><p>The third and final scenario described in the diagram belongs within the ‘exploit the pattern’ workflow.</p><p>The challenge here is that a significant skew often exists between the volume and velocity of data assumed in the development of an analytical product and those encountered in its intended destination environment.</p><h3>Pre-processing and feature engineering</h3><p>Let’s begin by discussing the “data-heavy” part of this workflow. As you’ll find on your journey through the MLOps Gym materials, an ability to decouple pre-processing and feature engineering processes from the model training and inference steps will make testing, versioning, and deploying changes to an analytical product much easier. It also enables data science teams to follow the patterns employed by their data engineering colleagues with regard to scheduling and orchestration of these tasks.</p><p>If, at the time of training and evaluating models, you are:</p><ol><li>building and iterating on your feature engineering code using PySpark, pandas on Spark, or as a chain of SQL views; and</li><li>saving features in feature tables on Unity Catalog (<a href="https://docs.databricks.com/en/machine-learning/feature-store/uc/feature-tables-uc.html#create-a-feature-table-in-unity-catalog">any Delta table with a primary key can be a feature table</a>)</li></ol><p>then, when it comes to deployment, the only work necessary is to wrap this code up as something that can be deployed as a Workflow. Your code can now scale to process very large volumes of data, potentially in a continuous and incremental fashion, if you opt to employ Spark structured streaming.</p><p>For some practical examples of how to implement this, take a look at our feature tables <a href="https://docs.databricks.com/en/machine-learning/feature-store/uc/feature-tables-uc.html#create-a-streaming-feature-computation-pipeline-to-update-features">documentation pages</a>. Here’s an example from that page:</p><pre>def compute_additional_customer_features(data):<br>    &quot;&quot;&quot;Returns Streaming DataFrame&quot;&quot;&quot;<br>    pass<br><br><br>from databricks.feature_engineering import FeatureEngineeringClient<br><br>fe = FeatureEngineeringClient()<br>customer_transactions = spark.readStream.load(&quot;dbfs:/events/customer_transactions&quot;)<br>fe.write_table(<br>    df=compute_additional_customer_features(customer_transactions),<br>    name=&quot;ml.recommender_system.customer_features&quot;,<br>    mode=&quot;merge&quot;,<br>)</pre><p>Code written in this way will allow features in a feature table to be continuously updated in place using a Spark streaming pipeline. Furthermore, with the advent of Databricks Feature Serving, it is trivial to sync these features into an online store for real-time scoring applications.</p><h3>Inference/execution</h3><p>When putting a predictive model into production, some analysis of the throughput and latency requirements of the application is needed in order to determine the appropriate deployment pattern:</p><ul><li>For the lowest cost, highest throughput applications where latency is not so critical, then a Spark batch pipeline that calls the model using the `<a href="https://docs.databricks.com/en/mlflow/models.html#api-commands">mlflow.pyfunc.spark_udf</a>` pattern is ideal.</li><li>If you wish to score incoming observations (delivered via, e.g., a pub/sub service), and are looking for near-real-time results but can tolerate sub-minute latency, then deploying MLflow models into a Spark structured streaming pipeline is the perfect fit. This can also be adapted for ‘incremental batch’ deployments using the Trigger.AvailableNow approach described <a href="https://docs.databricks.com/en/structured-streaming/triggers.html#configuring-incremental-batch-processing">here</a>.</li><li>If low latency is the top priority, then deploying models into a <a href="https://docs.databricks.com/en/machine-learning/model-serving/index.html">model serving</a> endpoint is the way to go.</li></ul><p>Here’s a very quick example of the mlflow.pyfunc.spark_udf pattern mentioned above, if you haven’t seen it before:</p><pre>import mlflow.pyfunc<br>from pyspark.sql.functions import struct<br><br>pyfunc_udf = mlflow.pyfunc.spark_udf(spark, model_uri=model_uri)<br>predicted_df = dataframe.withColumn(<br>    &quot;prediction&quot;,<br>    pyfunc_udf(struct(&quot;age&quot;, &quot;sex&quot;, &quot;bmi&quot;, &quot;bp&quot;, &quot;s1&quot;, &quot;s2&quot;, &quot;s3&quot;, &quot;s4&quot;, &quot;s5&quot;, &quot;s6&quot;)),<br>)</pre><p>This retrieves a model from the MLflow tracking server and delivers it to the script as a vectorized Spark User Defined Function (UDF) (more info <a href="https://docs.databricks.com/en/udf/pandas.html">here</a>). This is a well-proven pattern for scalable model inference in a batch or streaming pipeline and is compatible with many flavours of models. Take a look at the <a href="https://www.mlflow.org/docs/latest/models.html#built-in-model-flavors">MLflow documentation</a> for a comprehensive list. The only requirement is that you log the model using MLflow during your model training workflow.</p><p>The documentation <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#pyfunc-create-custom">also describes</a> how to customise the wrapped model’s predict() method behaviour.</p><h3>Opportunities within model tuning, deep-learning tasks, and working with unstructured data</h3><p>The preceding discussion of data science workflows and opportunities for employing Spark assumed the development of analytical applications that are fed structured data, and the advice therein applies mostly to the use of ‘traditional’ machine learning algorithms. Furthermore, we assumed that model training is a once-and-done activity (i.e. no compute-intensive model tuning activity was required) and, provided the data fits in memory, this can be tackled in a ‘single-node’ development environment.</p><p>The following sections of this document describe the options available for using Spark when these assumptions do not hold true. More details on each of these will be provided later in the MLOps Gym material.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1MsDCy5-5yiRVstR" /></figure><p>The diagram above identifies some scenarios for parallelisation of the model training and tuning processes.</p><h3>Model vs. data parallelism?</h3><p>At this point, it is probably worth articulating the distinction between ‘model parallel’ and ‘data parallel’ training in the context of deep learning.</p><ul><li>Model parallelism describes the pattern of splitting a large model between multiple machines, cores, GPUs, etc., and feeding the results of each training subprocess to its downstream neighbour(s) in the sequence to perform updates. The process can be parallelised by continuing to compute gradients on stale weights while these are updated in a concurrent process.</li><li>Data parallelism typically involves sharding data across multiple nodes, with each node training its own variant of the model. A supervisor process aggregates results from each worker subprocess and updates the ‘final’ model before distributing this back to the workers and initiating another round of training.</li></ul><p>Another common pattern of task parallelisation in the context of model training is parallel hyperparameter tuning. This process requires the training of many candidate models in the search for an optimal performing set of hyperparameters.</p><p>We shall examine how Spark can be used in all of these scenarios.</p><h3>Scenario 1: Model parallel training</h3><p>Spark 3.5.0 saw the introduction of a <a href="https://spark.apache.org/docs/3.5.0/api/python/reference/api/pyspark.ml.deepspeed.deepspeed_distributor.DeepspeedTorchDistributor.html">DeepspeedTorchDistributor</a> class within the pyspark.ml package, allowing for <a href="https://www.deepspeed.ai/tutorials/pipeline/">pipeline-parallel</a> training of pytorch models. More details and an example notebook can be found in our <a href="https://docs.databricks.com/en/machine-learning/train-model/distributed-training/deepspeed.html#distributed-training-with-deepspeed-distributor">docs</a>.</p><p>The benefits of this toolset will be particularly apparent when available GPU memory is limited and the models being trained are very large. This class also allows for some degree of data parallelism during both training and inference time, which is particularly useful for batch inference applications.</p><h3>Scenario 2: Data parallel model training</h3><p>Most often, we see this approach called for when customers are training models on datasets that comprise unstructured data. So why and how does our approach to efficient model training and evaluation change when we want to make predictions based on unstructured data: text, images etc?</p><p>By their nature, input datasets of this type are typically very large (e.g., libraries of several thousand images collected by borescope inspections of jet engine turbine blades), and deep-learning techniques will (usually) be best suited to tackling the tasks that use them.</p><p>Assuming that is the case, the training data will very often exceed the capacity of a single compute node and will require sharding across whatever compute target is being used to train the model. This is a problem that can also be solved fairly simply by using Spark with the appropriate extension library for your desired workflow.</p><p>Here are some example patterns for doing this:</p><ul><li><a href="https://docs.databricks.com/en/machine-learning/train-model/distributed-training/spark-tf-distributor.html">Distributed training with TensorFlow 2</a></li><li><a href="https://docs.databricks.com/en/machine-learning/train-model/distributed-training/spark-pytorch-distributor.html">Distributed training with TorchDistributor</a></li><li><a href="https://docs.databricks.com/en/machine-learning/load-data/petastorm.html">Load data using Petastorm</a></li><li><a href="https://docs.databricks.com/en/machine-learning/train-model/distributed-training/horovod-runner.html">HorovodRunner: distributed deep learning with Horovod</a></li></ul><p>In general, these approaches require packaging existing, ‘single-node’ model training code into a function or class and wrapping these with some decorator or parent class that will handle the sharding of data and parallelisation of the model training and evaluation processes.</p><h3>Scenario 3: Parallel hyperparameter tuning</h3><p>Data scientists often want to automate the process of determining the optimal hyperparameters for the algorithm responsible for producing their predictive models. There are several good options for parallelising these searches using Spark, including:</p><ul><li><a href="https://docs.databricks.com/en/machine-learning/automl/how-automl-works.html">Use the platform’s built-in AutoML features to perform a multi-algorithm hyperparameter search</a></li><li><a href="https://docs.databricks.com/en/machine-learning/automl-hyperparam-tuning/index.html#hyperparameter-tuning-with-hyperopt">Customised hyperparameter tuning with Hyperopt SparkTrials</a></li><li><a href="https://github.com/joblib/joblib-spark">Use the tuning classes within scikit-learn with the joblib-spark backend</a></li></ul><h3>Tuning with AutoML</h3><p>The Databricks AutoML tools perform a parallelised search for an optimal model across multiple algorithms and a basic hyperparameter search space. Although these tools abstract away a lot of the complexity of a search operation, you still have control over aspects such as the model evaluation metric to be optimised, the stopping criteria of the search, and so on. As a starting point for the ‘modeling’ and ‘evaluation’ phases of your project, this is a great option since it provides information about what techniques are likely to perform well on your task and saves writing heaps of boilerplate code.</p><h3>Hyperopt SparkTrials</h3><p>This is our go-to recommendation for performing parallel hyperparameter search since it allows you to take advantage of Hyperopt’s ability to refine the hyperparameter search space as the search progresses.</p><h3>scikit-learn + joblib-spark</h3><p>Some algorithms in scikit-learn (especially the tuning and cross-validation tools) let you specify a parallel backend. You can use the joblib-spark backend to use Spark as that parallel backend. See the <a href="https://github.com/joblib/joblib-spark">joblib-spark</a> github page for an example.</p><h3>Summary</h3><p>In the course of this article, we have:</p><ul><li>examined how data scientists can leverage the power of Apache Spark to create efficient data science and machine learning workflows;</li><li>discussed the scenarios where Spark excels such as handling large datasets, resource-intensive computations, high-throughput applications, model tuning, and deep learning; and</li><li>covered some of the different parallelization strategies that can be employed, such as model parallelism and data parallelism with some practical examples and patterns for using Spark to achieve these.</li></ul><h3>Coming up next!</h3><p>Next blog in this series: <a href="https://medium.com/@sebrahimi1988/mlops-gym-getting-started-with-feature-store-59909fa01443">MLOps Gym — Getting started with Feature Store</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e13279650ad3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps Gym — Beginners Guide to Cluster Config for MLOps]]></title>
            <link>https://medium.com/@sebrahimi1988/mlops-gym-beginners-guide-to-cluster-config-for-mlops-a525baf5c63f?source=rss-f3386c29ab15------2</link>
            <guid isPermaLink="false">https://medium.com/p/a525baf5c63f</guid>
            <dc:creator><![CDATA[Sepideh Ebrahimi]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 12:43:09 GMT</pubDate>
            <atom:updated>2024-08-29T15:41:38.569Z</atom:updated>
            <content:encoded><![CDATA[<p>MLOps Gym — Beginners Guide to Cluster Configuration for MLOps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q3xflBCfkw6pAG9O" /></figure><p>When setting up compute, there are many options and knobs to tweak and tune, and it can get quite overwhelming very quickly. To help you with optimally configuring your clusters, we have broken down this topic into two articles:</p><ol><li>Beginners Guide to Cluster Configuration for MLOps — where to start when you are at the early stages of your MLOps journey.</li><li>Advanced Cluster Configuration for MLOps — how to choose the best configuration for more sophisticated MLOps workloads and usage patterns.</li></ol><p>In this article, we will cover the first stage — the beginner’s guide.</p><h3>What type of compute should I choose?</h3><p><em>Compute</em>, or a <em>compute cluster,</em> refers to a computation resource built on one or more cloud virtual machines (VMs, also referred to as <em>nodes</em>) that you can use to accomplish your data engineering, data science, or AI/ML tasks.</p><p>Before we can begin the cluster creation/configuration process, we need to understand the use case required for the compute to determine the <em>type</em> of cluster.</p><p>There are several types of compute available on Databricks:</p><ul><li><strong>All-purpose compute, </strong>a.k.a. <strong>Interactive clusters, </strong>refer to a computing cluster that is suitable for interactive workloads such as ad-hoc analysis, data exploration, and development. You can attach your notebooks to an interactive cluster and run your code (Python, SQL, Scala, R) on it. Using this type of cluster is necessary for the early stages of your project when you are developing your code and experimenting. To control costs, you can define them to terminate after a predefined time of inactivity.</li><li><strong>Job compute, </strong>a.k.a. <strong>Job clusters, </strong>are often used when you’re ready to operationalize your code (Python, SQL, Scala, R). Job clusters are designed to terminate automatically once the specific job or task is completed and are more cost-efficient than all-purpose clusters. Depending on the Cloud and Tier you are on, you can save between 45% to 75% of the cost by switching from interactive to jobs clusters.</li><li><strong>SQL warehouses</strong> are compute resources that allow you to run SQL commands on Databricks.</li><li><strong>Pools</strong> are a set of idle, ready-to-use instances that you might share between different workloads.</li></ul><p>In addition, Databricks offers ML-specialized compute types that are tailored for specific use cases (out of the scope of this Beginners’ Guide):</p><ul><li><strong>Vector Search </strong>facilitates speedy, semantic-based searches by indexing data as vectors, enhancing accuracy in areas like natural language processing. There are two components to vector search: a storage component and a compute component. The storage component shows up in the Catalog tab on Databricks, and you can find the compute component under the compute tab.</li><li><strong>Model Serving </strong>allows you to serve your ML models at a REST API endpoint. It is low latency and serverless, and it comes in different flavours. Model serving supports both CPU and GPU, enabling serving for both traditional ML models and Large Language Models (LLMs).</li><li><strong>Online stores</strong> provide low latency data serving capabilities. It is designed to simplify the process of serving data from analytical systems to real-time ML models and applications, such as retrieving pre-computed features for real-time inference.</li></ul><p>Here is our recommendation on when to use it:</p><ul><li><strong>Use an interactive cluster</strong> if you are developing a solution, exploring, or doing ad-hoc analysis.</li><li><strong>Use a job cluster</strong> if you have a piece of code you want to automate (run as a workflow/ job on Databricks). We strongly recommend against using interactive clusters for your jobs. Job clusters are typically less costly than interactive clusters, so you can automate production jobs at a lower cost. However, since they can only be used to automate jobs, you cannot interact with job clusters the way you do with an interactive cluster.</li><li><strong>Use a SQL warehouse </strong>for SQL workloads. Databricks recommends the adoption of <a href="https://docs.databricks.com/en/serverless-compute/index.html#databricks-sql-serverless">serverless SQL warehouses</a> to take advantage of its advanced optimisation techniques.</li></ul><h3>How can I create a cluster?</h3><p>Once you have determined the type of compute, you are ready to start creating and configuring your cluster. You can create a Databricks cluster via the <a href="https://docs.databricks.com/en/clusters/configure.html">Databricks UI</a>, <a href="https://docs.databricks.com/api/workspace/clusters">Clusters API</a>, <a href="https://docs.databricks.com/en/dev-tools/cli/commands.html">Databricks CLI</a>, SDK (<a href="https://docs.databricks.com/en/dev-tools/sdk-python.html#create-a-cluster">Python</a>/<a href="https://docs.databricks.com/en/dev-tools/sdk-java.html#create-a-cluster">Java</a>/<a href="https://docs.databricks.com/en/dev-tools/sdk-go.html#create-a-cluster">Go</a>/<a href="https://docs.databricks.com/en/dev-tools/sdk-r.html#create-a-cluster">R</a>), or <a href="https://docs.databricks.com/en/dev-tools/terraform/index.html">Databricks Terraform provider</a>.</p><p>If creating via the Databricks UI:</p><ul><li>To create an <strong>interactive cluster</strong> via the UI, you should navigate to the Compute tab in the Databricks UI and hit “Create compute.”</li><li>To create a<strong> job cluster</strong> in the UI, navigate to Workflows &gt; Jobs and hit “Create job.” When creating your job, you are able to define the configurations to create a new job cluster. Creating a job cluster outside the context of a job is not possible.</li></ul><p>To create clusters via Clusters API, CLI, or Databricks Terraform provider, follow the instructions in the docs linked above.</p><h3>What access mode should I choose?</h3><p>When you create a cluster in Databricks, you must select an access mode. The access mode is a security feature that determines who can use a cluster and what data they can access via the cluster.</p><p>Available access modes for clusters can be found <a href="https://docs.databricks.com/en/clusters/configure.html#access-modes">here</a>.</p><p>If you are on Unity Catalog (which you should be if you are following Databricks’ recommendation), your choices are between the “single user” and “shared” access modes. Here is what each of these modes means:</p><ul><li>A single-user cluster can be assigned to and used by a single user. This cluster access mode supports all languages available on Databricks (Python, SQL, Scala, R).</li><li>A shared cluster can be used by multiple users and is designed to provide strict process isolation amongst users. This provides stronger security guarantees than would otherwise be possible if multiple users were to share a ‘single user’ cluster. However, this cluster access mode only supports Python, SQL, and, most recently, Scala on more recent runtime versions.</li></ul><p>If you are starting off your MLOps work on Databricks, you will find it easier to use a <strong>single-user </strong>cluster for both interactive workloads and jobs unless you are not able to do so due to <a href="https://docs.databricks.com/en/compute/access-mode-limitations.html">limitations</a>. In this scenario, every user or job will have their own cluster (probably with a single node, as you will see in the cluster sizing section below) and will not interfere with other users’ workloads.</p><h3>What runtime should I choose?</h3><p>The Databricks Runtime provides a pre-configured development environment complete with the operating system, Spark components, language interpreters, and analysis tools that you will need to get started quickly.</p><h3>Runtime flavors</h3><p>The Runtime comes in two flavors: Standard and ML. As you are working on an ML project, you most probably need the ML version as it comes with many popular Python-based data manipulation and machine learning packages (and their dependencies) pre-installed. MLflow, which is by far the most popular MLOps framework, is also pre-installed in ML runtimes.</p><p>You cannot (currently, as of April 2024) use the ML Runtime with a cluster configured for Shared Access Mode.</p><h3>Versioning</h3><p>Databricks releases newer runtime versions with more recent versions of libraries on a regular basis. They might also add/remove other libraries to/from more recent releases. We recommend that you either choose the latest runtime version to have access to the most recent versions of software or the latest <em>LTS</em> (Long-Term Support) version.</p><p>If you need a particular version of a library, you are able to selectively install, upgrade, or downgrade on a per-library basis, but it is good practice to try to stay as close to the latest DBR or latest LTS DBR as possible.</p><ul><li>Check out runtime release notes (<a href="https://docs.databricks.com/en/release-notes/runtime/index.html">AWS</a>, <a href="https://learn.microsoft.com/en-gb/azure/databricks/release-notes/runtime/">Azure</a>, <a href="https://docs.gcp.databricks.com/en/release-notes/runtime/index.html">GCP</a>) to find out which libraries and packages are included in them.</li><li>You can also check out <a href="https://medium.com/databricks-labs/upgrading-jobs-code-between-databricks-runtime-versions-made-seamless-29c22e701c3a">this tool</a> helping with DBR upgrades.</li></ul><h3>What are cluster policies and how to use them?</h3><p>Cluster policies are rules and definitions that can be imposed by your workspace administrator to limit your users’ ability to create compute clusters. It is primarily used as a governance measure to ensure consistency, enforce tagging, and control costs.</p><p>For example, if you wish to limit your users to creating only single-node, single-user clusters, you can do so by setting up cluster policies accordingly. You can mandate custom tagging to be applied to the cluster to facilitate the tracking of costs across projects, teams, and departments. These tags can then be used to aggregate Databricks and cloud provider costs for efficient cross-charging within large organizations.</p><p>Cluster policies also provide a reusable template for compute configurations that can be shared within and across teams. This way, you ensure that all the necessary dependencies are captured in the template and that the entire team works with the same compute configuration.</p><p>To learn how to set up your cluster policies, follow the documentation <a href="https://docs.databricks.com/en/administration-guide/clusters/policies.html">here</a>, and to learn about cluster policy best practices, refer to the documentation <a href="https://docs.databricks.com/en/administration-guide/clusters/policies-best-practices.html">here</a>.</p><h3>Cluster sizing</h3><h3>Start with Single Node</h3><p>When you are starting off your MLOps journey on Databricks, the most common scenarios are the following:</p><ul><li>Your workload uses little data (fits in memory).</li><li>Your code is non-distributed; for example, it uses pure Python, vanilla Pandas, or machine learning libraries such as sklearn.</li></ul><p>If any of these conditions apply to you, then a <strong>single node</strong> cluster provides all of the capabilities you will need without incurring the high cost of a cluster with many worker nodes. Using a single-node cluster is just like using a personal VM. You can size it like a personal laptop or size it to a larger machine if you’re working with GBs of data. In addition, you can read and write from UC tables and volumes.</p><p>When we are choosing a cluster, even when it is a single node, there are multiple aspects that you should consider. CPU, disk, and memory are parameters that you can experiment with and make decisions on when looking for the best configuration for your workload.</p><h3>CPU</h3><p>The optimal number of CPU cores depends on your specific use case, workload characteristics, budget constraints, and the scalability requirements of your application.</p><p>By default, pure Python code, Pandas, or sklearn algorithms run on a single CPU core. However, there are mechanisms to leverage multiple cores for such tasks.</p><p>For example,</p><ul><li>Python’s built-in <a href="https://docs.python.org/3/library/threading.html">threading</a> and <a href="https://docs.python.org/3/library/multiprocessing.html">multiprocessing</a> libraries can be used to parallelise the execution of arbitrary Python code.</li><li>For more complex code, you might want to look at parallel execution using Ray, <a href="https://docs.ray.io/en/latest/ray-core/examples/gentle_walkthrough.html">configured to run as a ‘local’ cluster</a>.</li><li>To parallelise Pandas on multiple cores of a single machine, you can use libraries such as <a href="https://github.com/modin-project/modin">Modin (Pandas on Ray)</a> and <a href="https://www.dask.org/">Dask</a>.</li><li>Sklearn provides <a href="https://scikit-learn.org/stable/computing/parallelism.html">mechanisms to parallelise</a> some of its operations as well.</li></ul><p>Here is our recommendation:</p><ul><li><strong>If you are not thinking about parallelisation,</strong> the number of CPU cores shouldn’t be a concern to you. You can start with a small number of cores, for example, 4.</li><li><strong>If you want to parallelise your code</strong>, take your budget into consideration. Choose a balance between performance and cost that aligns with your budget constraints. More CPUs might mean faster code execution, but the speed of execution does not scale linearly with the number of cores due to parallelisation overhead.</li><li>If you are really looking to optimize for speed and scalability in your code, then you read our guide (to be published soon) to incorporate Spark into data science and machine learning workflows.</li></ul><h3>Disk</h3><p>A VM’s disk in the cloud is primarily focused on hosting the operating system, software, and runtime environment of the virtual machine. It serves immediate, dynamic, and temporary storage needs associated with the VM’s operation.</p><p>Due to this, it can often be difficult to estimate how much disk you would need to run your workload. Fortunately, cloud providers allow you to have autoscaling on your local disk.</p><ul><li>On AWS and GCP, you can enable it by choosing “<strong>Enable autoscaling local storage</strong>” in the cluster config.</li><li>On Azure, it is enabled by default.</li></ul><h3>Memory</h3><p>Selecting the right memory size for a virtual machine involves careful analysis of the operating system, applications, workload characteristics, scalability needs, and budget considerations. When you choose a VM with a certain memory size, a good portion of that memory is allocated to the OS and running applications on it. As a result, choosing a memory of, for example, 14GB does not mean you have 14GB of memory to hold the data you are processing.</p><p>To determine how much memory you have available, navigate to the cluster’s page &gt; Metrics and check out the Memory utilization graph. In the example below, you can see that out of a total of 14GB VM memory, there is about 5.28GB free after the OS takes the memory it requires.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SkQG4UXqWiSQ5GpD" /></figure><p>Additionally, allocating VMs with excessive memory can be problematic due to the increased cost of garbage collection (GC) for large heaps.</p><p>Another factor to take into consideration when choosing memory is the fact that the data size on disk could be different than the data size in memory. Factors such as compression, serialization, additional structures, data representation, and processing overhead might contribute to this discrepancy in one way or another.</p><h4>How can I find out the size of my data in memory?</h4><p>To determine what memory size you need for your data processing, read a portion of the data, for example, using Pandas, and check out the memory usage in the Metrics tab. You can then extrapolate how much data is going to be needed for the entire dataset.</p><p>Once you have identified CPU, disk, and memory requirements for your workload, you can scan through available VM types on your cloud provider and choose the best one accordingly.</p><h3>Scale if necessary</h3><p>In other scenarios, when you need to leverage Spark’s distribution for distributed inference or training, etc., the question that often comes up in the context of choosing a cluster is “What cluster size should I choose?” On a single-node cluster, Spark can still leverage multiple CPUs to parallelise tasks, but in most scenarios, and as your data gets bigger, you are looking into sizing a multi-node cluster. When choosing a cluster, there are multiple aspects that you should consider. CPU, disk, and memory of your cluster are parameters that you can experiment with and make decisions on when looking for the best configuration for your workload. Check out the Advanced <a href="https://docs.google.com/document/d/19Jr26wL0KvCp2MDakvrTyfU471x3GFBMmT2u45gbJLQ/edit">Cluster Configuration for MLOps</a> for more details.</p><h3>Summary</h3><p>This article is a beginner’s guide to cluster configuration for MLOps using Databricks, detailing how to choose the right type of compute cluster, create clusters, manage access, set policies, size clusters, and select runtimes.</p><p>We recommend using interactive clusters for development and job clusters for automated tasks to control costs. We discuss the importance of selecting the right access mode, with options for single-user or shared clusters, and the significance of cluster policies for managing resources and costs. We also cover how to size a cluster based on CPU, disk, and memory needs, as well as the importance of selecting the right Databricks Runtime, highlighting the differences between Standard and ML runtimes and the need to stay updated with the latest versions.</p><p>Check out the official Databricks Cluster Configuration Best Practices documentation (<a href="https://docs.databricks.com/en/clusters/cluster-config-best-practices.html">AWS</a> | <a href="https://learn.microsoft.com/en-gb/azure/databricks/clusters/cluster-config-best-practices">Azure</a> | <a href="https://docs.gcp.databricks.com/clusters/cluster-config-best-practices.html">GCP</a>) and general Databricks Compute documentation (<a href="https://docs.databricks.com/en/compute/index.html">AWS</a> | <a href="https://learn.microsoft.com/en-us/azure/databricks/compute/">Azure</a> | <a href="https://docs.gcp.databricks.com/en/compute/index.html">GCP</a>) for further advice. <a href="https://community.databricks.com/t5/technical-blog/basics-of-databricks-workflows-part-3-the-compute-spectrum/ba-p/59986">Basics of Databricks Workflows — Part 3: The Compute Spectrum</a> also provides a great overview of compute resources on Databricks with a focus on Data Engineering.</p><h3>Coming up next!</h3><p>Next blog in this series: <a href="https://medium.com/@sebrahimi1988/mlops-gym-some-thoughts-on-the-intersection-of-distributed-systems-and-machine-learning-e13279650ad3">MLOps Gym — Some Thoughts on​​ the Intersection of Distributed Systems and Machine Learning</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a525baf5c63f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps Gym — Unity Catalog Setup for MLOps]]></title>
            <link>https://medium.com/@sebrahimi1988/mlops-gym-unity-catalog-setup-for-mlops-94ad01158779?source=rss-f3386c29ab15------2</link>
            <guid isPermaLink="false">https://medium.com/p/94ad01158779</guid>
            <dc:creator><![CDATA[Sepideh Ebrahimi]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 12:28:35 GMT</pubDate>
            <atom:updated>2024-08-23T12:43:46.771Z</atom:updated>
            <content:encoded><![CDATA[<p>MLOps Gym — Unity Catalog Setup for MLOps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y2CEvO1ya2GpBO7V" /></figure><p><a href="https://www.databricks.com/product/unity-catalog">Unity Catalog</a> (UC) is Databricks unified governance solution for all data and AI assets on the Data Intelligence Platform. UC is central to implementing MLOps on Databricks as it is where all your assets reside and are governed. Therefore, using UC is a prerequisite for all of the practices we recommend in the MLOps Gym series. In this article, we will give you recommendations on how to organize UC properly to be scalable and future-proof. We will address questions such as:</p><ul><li>How should you organize use cases/projects?</li><li>How should you organize raw data, features, models, and assets of each use case?</li><li>What privileges should each role in the team have?</li><li>Do you need a playground area for development?</li><li>Should you leverage managed or external tables?</li><li>How should you access your ML assets from outside Databricks, e.g., AzureML or Amazon SageMaker?</li></ul><h3>Unity Catalog Overview</h3><p>Centralizing governance on Databricks with Unity Catalog brings a multitude of benefits.</p><p>Your users and groups are no longer bound to the workspace — they’re managed centrally at the <a href="https://docs.databricks.com/en/getting-started/concepts.html#accounts-and-workspaces">account</a> level (Check out the <a href="https://docs.databricks.com/en/administration-guide/users-groups/index.html#how-do-admins-enable-identity-federation-on-a-workspace">identity federation documentation</a>.). This means that managing access permissions across different workspaces is simpler too. In this setup, you can create your assets in any workspace and use them in others, provided the right permissions have been <em>granted</em>.</p><p>Before moving on to the next section, it is crucial that you understand the UC terminology including metastore, catalog, table, etc. Unity Catalog’s <a href="https://docs.databricks.com/en/data-governance/unity-catalog/index.html">documentation</a> and the <a href="https://www.databricks.com/resources/ebook/the-big-book-of-mlops">Big Book of MLOPs v2</a> provide detailed definitions of all the terms in a generic sense and in the context of MLOps respectively.</p><h3>Managed vs External</h3><p>Tables and volumes can be <a href="https://learn.microsoft.com/en-us/azure/databricks/data-governance/unity-catalog/create-tables#--managed-tables">managed</a> or <a href="https://learn.microsoft.com/en-us/azure/databricks/data-governance/unity-catalog/create-tables#--external-tables">external</a>. Data meant to be processed on and accessed only within Databricks best be stored in managed tables/volumes. Managed tables are low maintenance and enjoy enhanced performance.</p><p>When working with managed tables/volumes, one caveat is that their content is not accessible to outside tools without going through a Databricks cluster or SQL warehouse. In the context of MLOps, this point becomes particularly pertinent as an ML pipeline encompasses data from different sources and might serve different downstream applications.</p><p>Depending on your architecture, you might need direct access to the data by external tools such as AWS SageMaker or AzureML. In such cases, you should store your assets in external tables/volumes on UC.</p><h3>How to organize your business assets in UC?</h3><p>Now that you are familiar with the different objects in UC, let’s examine what decisions you have to make to organize your data and AI assets. When working with a three-level namespace, you have to think about how to organize your content in the following three dimensions.</p><h3>Team</h3><p>The size and complexity of your organization have an important role in designing your UC layout.</p><p>At one end of the spectrum — e.g. in large organizations or where different teams are operating completely independently from one another out of choice or due to regulations — customers could choose a high level of segregation between different teams’ data and AI assets, and therefore have a separate catalog/schema per team. In this case each team — including the data science team — has permission to work with their dedicated catalog/schema and is completely cut off from other teams’ assets.</p><p>At the other end of this spectrum — e.g. in smaller organizations — customers might forgo separation per team and allow all teams to work across shared catalogs/schemas with the right access control in place.</p><h3>Business Context</h3><p>The business context of your projects is another dimension that you should take into consideration when designing the layout of your UC. In some businesses, data and AI assets associated with one project or business unit must not leak into any others leading to customers having a separate schema per use case. Some other projects might be transient in nature or might share resources with other projects and not require their own separate schema. An example is a one-off analysis project that resides in a shared “experiments” schema for all such analyses.</p><h3>Environment Scope</h3><p>Depending on the number of environments you use in your development cycle, you can choose to use catalogs to separate different “quality” of data and AI assets. In the context of MLOps, the data and models you have in your lower environments such as your development environment, are by design lower in quality and more experimental. As you progress in your MLOps lifecycle, you test them and you gradually promote them to higher environments, the highest of which is your production environment.</p><p>As an example, if you have 4 environments, sandbox, dev, staging, and prod, then you probably want to have a separate catalog per environment to have the highest level of isolation between high-quality and low-quality assets.</p><h3>Example UC Setup Patterns for MLOps</h3><p>Now let’s have a look at a few different ways that you can organize your data and AI assets in UC</p><h3>Scenario 1</h3><p><strong>Description</strong></p><p>Organizations where different teams and business units have the flexibility to share data and models with each other. For instance, multiple business units with their own data science and BI teams can collaborate and exchange common data and features, fostering innovation across the organization.</p><p>This scenario is thoroughly described in the Big Book of MLOps v2.</p><p><strong>Catalog</strong>: One per environment, Sandbox, Dev, Staging, Prod. The medallion schemas</p><p>(Bronze, Silver, Gold) are replicas of one another. For simplicity, only the content of the Dev catalog is displayed below.</p><p><strong>Schema</strong>: In the Sandbox catalog: one schema per team/ project</p><p>In the Dev/Staging/Prod catalogs: One schema per Bronze/Silver/Gold and then more schemas per use case/project</p><p><strong>Assets</strong>: Data tables in Bronze/Silver/Gold schemas</p><p>Generic feature tables — reusable across different use cases — in Gold schema</p><p>Use case specific features as well as other use case specific assets such as models, functions and volumes in the use case schema</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UqWF0_StZ03ijxHW" /></figure><h3>Scenario 2</h3><p><strong>Description</strong></p><p>Organizations where business units have to segregate their data and AI assets due to regulation or other reasons. For instance, if you are working in an organization with business units that are completely independent in their data and functionality such as two brands of an umbrella company this scenario applies to you. Another instance is when a particular sector of the business operates under strict regulations and handles confidential data, necessitating isolation and heightened security measures to safeguard it from the rest of the company’s data.</p><p><strong>Catalog</strong>: One per business unit and environment, BU-Sandbox, BU-Dev, BU-Staging,</p><p>BU-Prod. The medallion catalogs(Bronze, Silver, Gold) are replicas of one another. For simplicity, only the content of the Dev catalog is displayed below.</p><p><strong>Schema</strong>: In Sandbox catalog: one schema per team/ project</p><p>In Dev/Staging/Prod catalogs: One schema per Bronze/Silver/Gold and then more schemas per use case/project</p><p><strong>Assets</strong>: Data tables in Bronze/Silver/Gold schemas</p><p>Generic feature tables — reusable across different use cases — in Gold schema</p><p>Use case specific features as well as other use case specific assets such as models, functions and volumes in the use case schema</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_DytiRPPkneqofna" /></figure><h3>Who should have access to what and to what degree?</h3><p>Following the principle of least privilege as generally recommended by Databricks. users should only have access to assets that they absolutely require and with the minimum privilege required. Many of our customers choose to completely close off their Prod environment to individual users for modification to avoid human error. Instead they only allow Service Principals to operate their jobs in Production.</p><p>But wouldn’t this cause a problem with data discoverability? Not necessarily. You are able to grant “BROWSE” privileges to all users on assets you wish to be discoverable. The BROWSE privilege allows users to see the metadata and therefore discover assets but not be able to access the assets themselves.</p><p>Another best practice is to grant privileges to groups rather than individual users. For example, if you have a team of BI analysts, create a group and add all members to it, then assign privileges to that group instead of the users one by one. In this case, if somebody new joins or someone leaves the team all you need to do is to add/remove them to that group instead of granting them access to all different assets individually.</p><h3>Summary</h3><p>In conclusion, setting up Unity Catalog for MLOps offers a flexible, powerful way to manage data and ML assets across diverse organizational structures and technical environments. Unity Catalog’s design supports a variety of architectures, enabling direct data access for external tools like AWS SageMaker or AzureML through the strategic use of external tables and volumes. It facilitates tailored organization of business assets that align with team structures, business contexts, and the scope of environments, offering scalable solutions for both large, highly segregated organizations and smaller entities with minimal isolation needs. Moreover, by adhering to the principle of least privilege and leveraging the BROWSE privilege, Unity Catalog ensures that access is precisely calibrated to user needs, enhancing security without sacrificing discoverability. This setup not only streamlines MLOps workflows but also fortifies them against unauthorized access, making Unity Catalog an indispensable tool in modern data and machine learning operations.</p><p>Check out the UC best practices on <a href="https://learn.microsoft.com/en-us/azure/databricks/data-governance/unity-catalog/best-practices">Azure</a> and <a href="https://docs.databricks.com/en/data-governance/unity-catalog/best-practices.html">AWS</a> to find out more about how to optimize your UC setup.</p><h3>Coming up next!</h3><p>Next blog in this series: <a href="https://medium.com/@sebrahimi1988/mlops-gym-beginners-guide-to-cluster-config-for-mlops-a525baf5c63f">MLOps Gym — Beginners Guide to Cluster Configuration for MLOps</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94ad01158779" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MLOps Gym — Beginners Guide to MLflow]]></title>
            <link>https://medium.com/@sebrahimi1988/mlops-gym-beginners-guide-to-mlflow-39d011aea50f?source=rss-f3386c29ab15------2</link>
            <guid isPermaLink="false">https://medium.com/p/39d011aea50f</guid>
            <dc:creator><![CDATA[Sepideh Ebrahimi]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 12:25:25 GMT</pubDate>
            <atom:updated>2024-08-23T12:29:17.293Z</atom:updated>
            <content:encoded><![CDATA[<p>MLOps Gym — Beginners Guide to MLflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*ZRkSjhTMD9HYy4XD" /></figure><h3>MLflow</h3><p><a href="https://mlflow.org/docs/latest/introduction/index.html">MLflow</a> stands out as the leading open source MLOps tool, and we strongly recommend its integration into your machine learning lifecycle. With its diverse components, MLflow significantly boosts productivity across various stages of your machine learning journey. The utilisation of MLflow is integral to many of the patterns we showcase in the MLOps Gym.</p><p>Built on top of OS MLflow, Databricks offers a managed MLflow service that focuses on enterprise reliability, security, and scalability. Among its many advantages, the managed version of MLflow natively integrates with <a href="https://docs.databricks.com/en/notebooks/index.html">Databricks Notebooks</a>, making it simpler to kickstart your MLOps journey. For a detailed comparison between OS and Managed MLflow, refer to the <a href="https://www.databricks.com/product/managed-mlflow">Databricks Managed MLflow product page</a>.</p><p>Although MLflow encompasses seven core components (<a href="https://mlflow.org/docs/latest/tracking.html#tracking">Tracking</a>, <a href="https://mlflow.org/docs/latest/model-registry.html#registry">Model Registry</a>, <a href="https://mlflow.org/docs/latest/llms/deployments/index.html#deployments">MLflow Deployment for LLMs</a>, <a href="https://mlflow.org/docs/latest/models.html#model-evaluation">Evaluate</a>, <a href="https://mlflow.org/docs/latest/llms/prompt-engineering/index.html#prompt-engineering">Prompt Engineering UI</a>, <a href="https://mlflow.org/docs/latest/recipes.html#recipes">Recipes</a>, and <a href="https://mlflow.org/docs/latest/projects.html#projects">Projects</a> ) as of the current date (March 2024), our focus in this article will be on the initial five components. We chose these components because they are most effective in solving MLOps challenges for our customers with minimal friction. We will provide recommendations on when and how to leverage them effectively.</p><p>We have broken this guide to MLflow into three parts:</p><ol><li><em>Beginners’ guide to MLflow </em>will cover MLflow essentials for all ML practitioners. In this article, we discuss <strong>Tracking</strong> and <strong>Model Registry</strong> components.</li><li><a href="https://community.databricks.com/t5/technical-blog/mlops-gym-evaluating-large-language-models-with-mlflow/ba-p/72815"><em>Evaluating Large Language Models with MLflow</em></a><em> </em>is dedicated to the <strong>Evaluate </strong>component.</li><li>Deploying Large Language Models with MLflow will cover the remainder of MLflow’s LLM-related components such as <strong>MLflow Deployment for LLMs</strong> and<strong> </strong>the<strong> Prompt Engineering UI</strong>.</li></ol><p>Here are our suggested steps for getting started with MLflow. Remember that in the remainder of this article, “MLflow” refers to the Databricks-managed version of MLflow.</p><h3>Use MLflow Tracking</h3><p>Your entry point to the MLflow world is probably MLflow Tracking. Using this component, you can log every aspect of your machine learning experiment, such as source properties, parameters, metrics, tags, and artifacts. MLflow Tracking assists data scientists during training and evaluating models, obviating the need to manually record the parameters and results of every experiment and facilitating reproducibility.</p><p>MLflow Tracking comprises the following components:</p><ul><li><a href="https://www.mlflow.org/docs/latest/tracking/server.html">Tracking Server</a>, which is an HTTP server hosted on Databricks Control Plane for tracking runs/ experiments.</li><li><a href="https://www.mlflow.org/docs/latest/tracking/backend-stores.html">Backend Store</a>, which is a SQL database hosted on Databricks Control Plane to store metadata for runs/experiments such as run id, start and end time, parameters, etc.</li><li><a href="https://www.mlflow.org/docs/latest/tracking/artifacts-stores.html">Artifact store</a>, which is where MLflow stores the actual artifacts of runs such as model weights, data files, etc. Databricks uses <a href="https://docs.databricks.com/en/dbfs/index.html">DBFS</a> as its default artifact store for MLflow.</li><li>Tracking <a href="https://www.mlflow.org/docs/latest/tracking.html#tracking-ui">UI</a> and <a href="https://www.mlflow.org/docs/latest/tracking/tracking-api.html">APIs</a>, which allow you to interact with MLflow Tracking API through UI or API calls, respectively. The UI has tools for exploring metadata and artifacts and comparing performance metrics between runs.</li></ul><p>The key concepts in the MLflow Tracking realm are <em>runs</em> and <em>experiments</em>. Runs are a detailed record of individual executions of code. Each run captures the associated metadata and resulting output or “artifacts”. An experiment is a collection of runs related to a specific ML task that allows for easier comparison.</p><p>For example, for a single command execution or “run” of `python train.py`, MLflow Tracking would record the artifacts such as the model weights, images, etc.; as well as metadata such as the metrics, parameters, and start/end times. A collection of these runs with different variations (e.g. the ML algorithm) could be grouped as an experiment which allows you to more easily compare and select the best-fitting model.</p><p>For more information, you can refer to the <a href="https://mlflow.org/docs/latest/tracking.html#concepts">MLflow documentation</a>:</p><p>On Databricks, matters are made even simpler. By default, a notebook is linked to an experiment with the same name, and the runs of that experiment are all bundled together.</p><h3>How do you interact with MLflow Tracking on Databricks?</h3><p>MLflow Tracking tightly integrates with Databricks ecosystem. There are multiple touchpoints with MLflow Tracking on the Databricks platform, including ML Runtimes, Notebooks, and the Tracking UI (Experiments).</p><h4>ML Runtime</h4><p>MLflow is provided out-of-the-box with <a href="https://www.databricks.com/product/machine-learning-runtime">ML Runtimes</a>. On Standard Runtimes, you can<a href="https://pypi.org/project/mlflow/"> install MLflow using PyPi</a>.</p><h4>Notebooks</h4><p>MLflow is natively integrated with Databricks Notebooks. That means two things:</p><ul><li>You can import MLflow and call its various methods using your API of choice (<a href="https://mlflow.org/docs/latest/python_api/index.html#python-api">Python</a>, <a href="https://mlflow.org/docs/latest/rest-api.html#rest-api">REST</a>, <a href="https://mlflow.org/docs/latest/R-api.html#r-api">R API</a>, and <a href="https://mlflow.org/docs/latest/java_api/index.html#java-api">Java API</a>). The managed Tracking Server will capture and log whatever you ask it to such as parameters, metrics, artifacts, etc. MLflow provides these capabilities out of the box without you needing to set up any infrastructure or tweak any knobs to get this functionality. Additionally, each run preserves the version of the notebook associated with it, making it completely reproducible.</li><li>The <a href="https://www.databricks.com/blog/2019/04/30/introducing-mlflow-run-sidebar-in-databricks-notebooks.html">MLflow Run Sidebar</a>, located on the right-hand side of your Notebooks, lets you monitor runs directly within your notebooks. It enables you tocapture a snapshot of each run, ensuring that you can revisit earlier versions of your code at any time.</li></ul><p>Autologging</p><p>As of ML Runtime 10.3, <a href="https://docs.databricks.com/en/mlflow/databricks-autologging.html#databricks-autologging">Autologging</a> is available on all Databricks notebooks. Autologging means you don’t need to import and call MLflow explicitly to capture your experiments. All you need to do is write your training code using <a href="https://docs.databricks.com/en/mlflow/databricks-autologging.html#supported-environments-and-frameworks">a variety of supported ML libraries</a> (e.g., sklearn), and pretty much every aspect of the experiment, including metrics, parameters, model signature, artifacts, and dataset, will be logged automatically.</p><p>When you attach your notebook to an ML Runtime, Databricks Autologging calls mlflow.autolog() which then uses a predefined set of parameters, metrics, artifacts, etc. to log your experiments. If you want to log any other aspect of your experiment not covered by Autologging (e.g., SHAPLY values), you can <a href="https://docs.databricks.com/en/mlflow/databricks-autologging.html#track-additional-content">manually log them using the MLflow client</a>.</p><p>One important point to note is that when creating a run using the <a href="https://mlflow.org/docs/latest/python_api/mlflow.html#module-mlflow">MLflow fluent API</a>, autologging isn’t applied automatically. You will have to call mlflow.autolog() manually within the “with” block for it to take effect.</p><p><strong>with</strong> mlflow<strong>.</strong>start_run() <strong>as</strong> run:</p><p>mlflow<strong>.</strong>autolog()</p><p>……</p><h4>Tracking UI</h4><p>Everything you capture in your notebooks using MLflow Tracking is visible under the Experiments tab in Databricks. By default, there is a 1:1 mapping between notebooks and experiments. Therefore in the Tracking UI, you can find all the notebook runs under one experiment. If you click on an experiment, you can further explore the experiment’s runs and drill down on relevant information about that experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g0YG1p-kPTuAMere" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lx9RHZ8cbTG-4-tb" /></figure><h3>How can I start using MLflow Tracking?</h3><p>Now that you know the essentials of MLflow Tracking, open a notebook and begin writing your ML code. Autologging will automatically capture the training run metadata for you. Navigate to the Experiments tab and look for the experiment with the same name as your notebook. Analyse the run metrics, parameters, etc., embedded within that experiment.</p><h3>Use MLflow Model Registry with Unity Catalog</h3><p>Another critical component of MLflow is the Model Registry. It provides a centralized repository for managing and organizing machine learning models. You can think of Model Registry as a one-stop shop for all the models you want to “keep” for deployment, testing, or any other purposes. Models that are “logged” with MLflow Tracking can be “registered” to the Model Registry.</p><h3>What is a model flavour?</h3><p>A model flavour refers to how a machine learning model is packaged and stored. When registering a model, you can register it with a “<a href="https://mlflow.org/docs/latest/models.html#built-in-model-flavors">native</a>” flavour such as sklearn, TensorFlow, etc., or with a Python flavour known as “<a href="https://mlflow.org/docs/latest/models.html#python-function-python-function">pyfunc</a>.” A native flavour saves the model as a native object (e.g., a pickle file for sklearn flavour). In contrast, the pyfunc flavour stores the models as a generic <a href="https://mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#filesystem-format">filesystem format</a> defined and supported by MLflow.</p><p>If you register a model with a pyfunc flavour, you can only load and use it as a Python object. However, suppose you register a model with a native flavour, Databricks will automatically create an additional Python flavour for you, enabling you to load and use the model both as a native object or a Python one.</p><h3>Workspace Model Registry vs Unity Catalog Model Registry</h3><p>Before the introduction of <a href="https://docs.databricks.com/en/mlflow/models-in-uc.html">Models in Unity Catalog (UC</a>), the default scope for the Model Registry home was limited to a workspace. This meant you could only access a model registered to your Model Registry within the boundaries of that specific workspace. If you wanted to move models from one workspace to another (e.g., to promote from a dev workspace to a prod one), you had to go through the extra trouble of using<a href="https://docs.databricks.com/en/mlflow/migrate-mlflow-objects.html#copy-mlflow-objects-between-workspaces"> an open source tool</a> to move objects between workspaces. Another option was to <a href="https://docs.databricks.com/en/machine-learning/manage-model-lifecycle/multiple-workspaces.html">set up a remote Model Registry</a> and share it between workspaces, which was also laboursome.</p><p>Models in UC solve this problem and much more. Now, models live in UC alongside your features and raw data, making lineage tracking seamless. UC takes the concept of Model Registry outside the boundaries of a workspace and holds it at an account level. You can register your models in a schema of a catalog, easily accessed between different workspaces or moved to other catalogs/schemas.</p><p>One major change when moving from workspace Model Registry to UC is using “aliases” over “stages” to promote models from development to production. When working with the workspace Model Registry, you would use MLflow model stages (None, Staging, Production, Archived) to progress models from the development stage (typically None) to testing (Staging) and then to production (Production). Once done with a model, you would move it to the “Archived” stage. However, in the UC world, the concept of stages is replaced by model aliases. You have aliases such as “Challenger” and “Champion” for models to be tested and in production, respectively.</p><h3>How can I start using the MLflow Model Registry?</h3><p>You can use MLflow.register_model() to register any model you have logged during a run. Another option is to pass a “registered_model_name” argument when you are logging your model with mlflow.&lt;MODEL_FLAVOR&gt;.log_model(), and it will both log and register the model at the same time.</p><p>To use UC as your model registry, all you need to do is:</p><p>import mlflow</p><p>mlflow.set_registry_uri(“databricks-uc”)</p><p>Then use a 3-level namespace for your model names following the &lt;CATALOG&gt;.&lt;SCHEMA&gt;.&lt;MODEL_NAME&gt; pattern.</p><h3>End-to-end ML Experience with MLflow (Beginners version)</h3><p>Let’s look at a step-by-step experience using MLflow from experimentation through registering a model to Model Registry.</p><ol><li>Create a notebook and write your ML code in it (e.g. sklearn)</li><li>Check the Experiments tab and explore your results by navigating to the experiment with the same name as your notebook. If you have multiple runs within the same experiment, you can select and compare their different metrics in the UI.</li><li>Decide which model is the “winner.” Then, use mlflow.register_model() to register it to the Model Registry.</li><li>Load the model in a notebook using mlflow.&lt;MODEL_FLAVOR&gt;.load_model() and run inference.</li></ol><h3>Coming up next!</h3><p>Next blog in this series: <a href="https://medium.com/@sebrahimi1988/mlops-gym-unity-catalog-setup-for-mlops-94ad01158779">MLOps Gym — Unity Catalog Setup for MLOps</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39d011aea50f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing MLOps Gym: Your Practical Guide to MLOps on Databricks]]></title>
            <link>https://medium.com/@sebrahimi1988/introducing-mlops-gym-your-practical-guide-to-mlops-on-databricks-1a62259e39cc?source=rss-f3386c29ab15------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a62259e39cc</guid>
            <dc:creator><![CDATA[Sepideh Ebrahimi]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 11:49:37 GMT</pubDate>
            <atom:updated>2024-08-23T12:26:03.500Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*h7sj1s54dot6ZtWc" /></figure><p>Welcome to the MLOps Gym, where we guide you through the essential steps of implementing MLOps practices on Databricks, ensuring that your machine learning projects move from ad hoc experimentation to robust, scalable, and reproducible workflows. In this blog series, we will take you through three key phases to elevate your MLOps proficiency: Crawl, Walk, and Run.</p><h3>Crawl: Building the foundations for repeatable workflows</h3><p>In this phase, we will focus on transitioning from ad hoc data science practices to establishing repeatable workflows.</p><p>Among other topics, here, we will delve into:</p><ul><li>the fundamentals of setting up Databricks environments such as cluster configuration, Unity Catalog, etc.</li><li>leveraging version control to ensure consistency and reproducibility in your machine learning experiments.</li><li>proper use of MLflow</li></ul><p>Whether new to MLOps or looking to refine your approach, the Crawl phase provides you with the foundation for success.</p><h3>Walk: Integrating CI/CD</h3><p>Our focus in this phase shifts toward integrating Continuous Integration and Continuous Deployment (CI/CD) practices into your MLOps pipeline.</p><p>Here are some of the topics we will cover:</p><ul><li>automating testing, deployment, and monitoring processes</li><li>ensuring reproducibility through data versioning and dependency management</li></ul><p>By mastering CI/CD on Databricks, you will streamline project management, accelerate time to market, and foster a culture of agility and innovation.</p><h3>Run: Elevating MLOps with rigor and quality</h3><p>In this final phase, we will explore the advanced techniques to enhance the rigor and quality of your MLOps practice.</p><p>We will dive deeper into topics such as:</p><ul><li>model explainability, bias detection, and end-to-end lineage</li><li>empowering you to maintain model integrity, compliance, and reliability at scale.</li></ul><p><em>Elevating</em> your MLOps game with the prescribed best practices, tools, and frameworks will enable you to meet the demands of enterprise-grade machine learning deployments.</p><h3>Coming up next!</h3><p>We’re thrilled to announce that the MLOps Gym series in the coming weeks. Stay tuned as we roll out this comprehensive guide, taking you from the basics of establishing repeatable workflows to the advanced techniques to enhance the rigor and quality of your MLOps practice.</p><p>Next blog in this series: <a href="https://medium.com/@sebrahimi1988/mlops-gym-beginners-guide-to-mlflow-39d011aea50f">MLOps Gym — Beginners Guide to MLflow</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a62259e39cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>