<?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 Fernandez Estevez Ariadna on Medium]]></title>
        <description><![CDATA[Stories by Fernandez Estevez Ariadna on Medium]]></description>
        <link>https://medium.com/@afernaes?source=rss-e4728e5c8b10------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*k7_IYj-m9fmiK7yb.jpg</url>
            <title>Stories by Fernandez Estevez Ariadna on Medium</title>
            <link>https://medium.com/@afernaes?source=rss-e4728e5c8b10------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:29:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@afernaes/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[Vertex AI Tips + Tricks: Secure your Vertex AI Workbench Deployments Using Terraform]]></title>
            <link>https://medium.com/@afernaes/vertex-ai-tips-tricks-secure-your-vertex-ai-workbench-deployments-using-terraform-d101080e6670?source=rss-e4728e5c8b10------2</link>
            <guid isPermaLink="false">https://medium.com/p/d101080e6670</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[vertex-ai-workbench]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <dc:creator><![CDATA[Fernandez Estevez Ariadna]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 10:22:10 GMT</pubDate>
            <atom:updated>2023-06-07T10:22:10.834Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>As more organisations adopt Artificial Intelligence and Machine Learning technologies, there is a growing need for scalable and secure infrastructure to support Data Science teams. Google Cloud’s <a href="https://cloud.google.com/vertex-ai">Vertex AI</a> is a powerful platform that provides a collaborative environment for building and deploying ML models, with features such as model version control, feature store, automated Machine Learning, and integration with popular tools like <a href="https://jupyter.org/">Jupyter Notebooks</a> in its <a href="https://cloud.google.com/vertex-ai-workbench">Vertex AI Workbench</a>.</p><p>For many enterprise customers, however, security constraints can become a barrier to adopting Data Science tools. For example, with Vertex AI Workbench, notebook instances are by default exposed to the internet directly through public IP addresses, which can pose an unacceptable security risk. In this blog post, we show how you can deploy secured Vertex AI Workbench instances using <a href="https://github.com/teamdatatonic/terraform-google-secure-vertex-workbench">Datatonic’s open-source Terraform module</a>.</p><h3>Motivation</h3><p>User-Managed and Managed Notebooks on Vertex AI allow users to easily deploy GCE VMs with JupyterLab pre-installed. These VMs use an external IP address by default for access to the internet to set up the instance (running startup scripts), expose the Jupyter user interface, and access third-party services (such as <a href="https://pypi.org/">PyPI</a> and <a href="https://github.com/">GitHub</a>).</p><p>The problem with this is the security issue that arises with external IP addresses. GCE VM Security best practice states that VMs should not have an external IP assigned to them (unless absolutely necessary), as it opens the instance up to attack from the public internet. Therefore, by default, Vertex AI Managed and User-Managed Notebooks are vulnerable to attack from the public internet too. Using Datatonic’s open-source Terraform module, you can deploy secured Vertex Workbench instances without using external IP addresses.</p><h3>Architecture Overview</h3><p>The following design is built in this Terraform module. All the details on the specific parts of the architecture will be explained throughout as we advance in the sections of this blog post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VK-z2a8qV0Zx1IJm1Un9g.png" /></figure><h3>Network</h3><p>Since we will not be using public IP addresses for the Vertex Workbench instances, we will need to create a private network that the instances can attach to in order to access the internet.</p><p>The first thing we need to set up is the private network (VPC) for Vertex AI Workbench Notebooks. This involves defining the IP address range for the network, as well as any subnets that will be used to isolate resources within the network. We will also need to specify the routing and firewall rules that will govern traffic within and outside the network.</p><p>Subnets are used to divide the IP address space of a VPC network into smaller sub-networks. You can specify the name of the subnet, the IP address range, region, project, and whether or not to allow private IP access from Google services. As this Terraform module is all about creating secure-by-default (i.e., private) notebooks, we configure the subnet to be able to access Google services only using <a href="https://cloud.google.com/vpc/docs/private-google-access">Private Google Access</a>.</p><p>Next, we need to establish Private Services Access (PSA) between our VPC network and Google’s network. PSA is essentially a private peering between a VPC network in your project and Google’s network, meaning VMs can leverage Google Services without the need for external IP. It’s required to privately use Vertex AI and has to be set up to use our own VPC network with Vertex Workbench notebooks. For more information about PSA, check out Google’s documentation <a href="https://cloud.google.com/vpc/docs/private-services-access#private-services-supported-services">here</a>.</p><p>Finally, we need to set up Cloud DNS records to enable private connectivity to all Google Service APIs from our notebooks. We need this because Google Cloud is entirely API driven. For example, when we want to leverage Google Cloud Storage, we are always using storage.googleapis.com. Google Cloud services all map to *.googleapis.com, which are public endpoints.</p><p>Because our Workbench instances do not have public (external) IP addresses enabled, they are unable to reach the public Google Service API endpoints. Luckily, Google Cloud also has private endpoints for a majority of its services, meaning that all traffic stays inside the Google network. All we simply have to do is set up DNS records to re-point requests to the public endpoints (*.googleapis.com) to the private Google Service APIs.</p><p>We also configure some network routes using <a href="https://cloud.google.com/vpc/docs/routes">Cloud Routes</a>, which are required to funnel requests to the restricted/private Google endpoints as default rather than attempt to access the public endpoints. There is also a route for internet traffic, for when certain internet access is allowed (more on that below).</p><h3>Firewall Rules</h3><p>We also need to define firewall rules that specify which traffic is allowed to enter or leave the private network. This is critical for maintaining data privacy and security, as it helps to prevent unauthorised access to sensitive data or resources.</p><p>The default rules are already defined in the module, but you can add additional ones if you like. The following firewall rules are provisioned by default:</p><ul><li><strong>Ingress-allow-tcp-git</strong>: Allows access to receive requests from Workbench to GitHub</li><li><strong>Egress-allow-tcp-git</strong>: Allows access to send requests from Workbench to GitHub</li><li><strong>Egress-deny-all:</strong> Deny all outbound traffic to the internet (lowest priority — we can allow some traffic using rules with a higher priority)</li><li><strong>Ingress-allow-tcp-ssh-from-iap:</strong> Allows IAP SSH access to VMs, which is useful for debugging</li><li><strong>Egress-allow-private-gcp-services:</strong> Allows access to private Google API endpoints</li><li><strong>Egress-allow-restricted-gcp-services:</strong> Allows access to restricted Google API endpoints</li><li><strong>Egress-allow-fastly-cdn-for-pypi:</strong> Allows access from Workbench to PyPI to install Python libraries</li></ul><h3>NAT Router</h3><p>Cloud NAT is used to allow the Vertex Workbench instances with only internal IP addresses to communicate with the public internet. This connectivity to the public internet is limited by the firewall rules described above, meaning that only listed IP addresses can be reached from Vertex Workbench.</p><p>Cloud NAT is used only within our Vertex subnetwork, to fully limit the exposure of our VPC to the internet. A Cloud Router is also deployed here as a prerequisite to using the Cloud NAT.</p><h3>IAM Roles, Service Account &amp; Buckets</h3><p>We will also create a service account that can act as the owner of our notebooks. This Service Account will need certain permissions to be able to communicate with the network configuration.</p><p>A <a href="https://cloud.google.com/storage">Google Cloud Storage</a> bucket is created and a post-startup script is written to it, which is then used by the Workbench instances. The script is responsible for implementing two security features (<strong>disable_nbconvert</strong> and <strong>disable_downloads</strong>), as they are not configurable via the Terraform resource at present.</p><h3>Notebooks</h3><p>With the network infrastructure in place, we can now create the actual Vertex AI Workbench instances that data science teams will use to develop and deploy ML models. There are two types of instances that we can create: user-managed notebooks, which are created and managed by individual data scientists, and Google-managed notebooks, which are fully managed by Google Cloud. For more detailed information on when we should choose user-managed or Google-managed notebooks, take a look at this <a href="https://blog.thecloudside.com/exploring-vertex-ai-workbench-google-cloud-338de45270c1">comprehensive post on Medium</a>.</p><h3>Build the Infrastructure with the Terraform module</h3><p>Now that we’ve covered the individual components of our Vertex AI Workbench Notebooks environment, it’s time to bring them all together and build the infrastructure using <a href="https://github.com/teamdatatonic/terraform-google-secure-vertex-workbench">the Terraform module</a>. This module provides a simple and reusable way to create a private network with a NAT router, firewall rules, DNS server, and Vertex AI Workbench Notebooks, all in one go.</p><p>By using a Terraform module, we can easily deploy and manage our Vertex AI Workbench Notebooks environment in a consistent and scalable manner. In the module, you can see an <strong>example</strong> folder that summarises everything you need to add to run the module. In the <strong>main.tf</strong> file you can see:</p><pre>module &quot;private_vertex_nb_instances&quot; {<br> source                        = &quot;../&quot;<br> project                       = var.project<br> zone                          = var.zone<br> region                        = var.region<br> notebooks                     = var.notebooks<br> additional_vertex_nb_sa_roles = var.additional_vertex_nb_sa_roles<br> vpc_network_name              = var.vpc_network_name<br> subnet_ip_cidr_range          = var.subnet_ip_cidr_range<br> vpc_sc_enabled                = false<br> additional_fw_rules           = var.additional_fw_rules<br> gcs_bucket_name               = var.gcs_bucket_name<br> gcs_labels                    = var.gcs_labels<br>}</pre><p>You can see that we need to define the source of the module. In this particular case, we are working in the same repository, therefore our source is ../, but we could also define <strong>“teamdatatonic/secure-vertex-workbench/google”</strong></p><p>We also have a <strong>terraform.auto.vars</strong> file; here is where we define the variables we have defined in the <strong>main.tf:</strong></p><pre>project              = &quot;example-project&quot;<br>zone                 = &quot;europe-west1-b&quot;<br>region               = &quot;europe-west1&quot;<br>vpc_network_name     = &quot;example-vpc&quot;<br>subnet_ip_cidr_range = &quot;10.1.0.0/24&quot;<br>gcs_bucket_name      = &quot;example-bucket-name”<br>gcs_labels           = { &quot;foo&quot; : &quot;bar&quot; }<br><br>notebooks = {<br> &quot;example-user-managed-instance&quot; : {<br>   &quot;labels&quot; : { &quot;foo&quot; : &quot;bar&quot; },<br>   &quot;instance_owner&quot; : &quot;example@example.com&quot;<br>   &quot;metadata&quot; : {}<br>   &quot;type&quot; : &quot;user-managed-notebook&quot;,<br> }<br> &quot;example-google-managed-instance&quot; : {<br>   &quot;labels&quot; : { &quot;foo&quot; : &quot;bar&quot; },<br>   &quot;instance_owner&quot; : &quot;example@example.com&quot;<br>   &quot;metadata&quot; : {}<br>   &quot;access_type&quot; : &quot;SERVICE_ACCOUNT&quot;<br>   &quot;type&quot; : &quot;google-managed-notebook&quot;<br> }<br>}<br><br>additional_vertex_nb_sa_roles = [<br> &quot;roles/dataproc.editor&quot;,<br> &quot;roles/dataproc.hubAgent&quot;<br>]<br><br>additional_fw_rules = [{<br> name                    = &quot;egress-allow-example-google&quot;<br> description             = &quot;Allow egress example&quot;<br> direction               = &quot;EGRESS&quot;<br> priority                = 65534<br> ranges                  = [&quot;142.250.178.14/32&quot;] # google.com<br> source_tags             = null<br> source_service_accounts = null<br> target_tags             = null<br> target_service_accounts = null<br> allow = [{<br>   protocol = &quot;tcp&quot;<br>   ports    = [&quot;443&quot;]<br> }]<br> deny = []<br> log_config = {<br>   metadata = &quot;INCLUDE_ALL_METADATA&quot;<br> }<br>}]</pre><p>In this case, we can see that the notebook map is creating two notebooks with two different types. The <strong>type</strong> value is what allows us to decide if we want to deploy a user-managed notebook or a Google-managed notebook.</p><p>Note also that, for the <strong>google-managed-notebook</strong> type, if we define the <strong>acces_type</strong> to be SERVICE_ACCOUNT (the possibilities are SINGLE_USER, SERVICE_ACCOUNT OR UNDEFINED), the variable <strong>instance_owner</strong> will not be used, and the service account email will be used instead. In this file, we also define additional service account roles in additional_vertex_nb_sa_roles variable and additional firewall rules in <strong>additional_fw_rules</strong> variable.</p><p>Once you have defined your Terraform module and all the required variables, you can use the following commands to create, update, and destroy the infrastructure:</p><ul><li><strong>terraform init:</strong> This command initialises a new or existing Terraform working directory by downloading and installing the required providers and modules. You should run this command once before using any other Terraform command.</li><li><strong>terraform plan:</strong> This command generates an execution plan based on the Terraform configuration files in your working directory. It shows what actions Terraform will take to create or modify the infrastructure, such as creating new resources, updating existing resources, or deleting no longer needed resources. It does not make any changes to your infrastructure.</li><li><strong>terraform apply:</strong> This command creates or updates the infrastructure according to the execution plan generated by terraform plan. It prompts you to confirm the execution plan before applying the changes. Once you confirm, Terraform will create or update the resources as specified in the configuration files.</li><li><strong>terraform destroy:</strong> This command destroys all the resources created by Terraform. It prompts you to confirm the destruction of each resource before proceeding. Once you confirm, Terraform will delete all the resources created by the module.</li></ul><h3>Conclusion</h3><p>In this blog post, we have explored how to create secure-by-default Vertex AI Workbench notebooks using Terraform. We walked through the key components of our Vertex AI Workbench environment, including the network settings, NAT router, firewall rules, DNS server, and Workbench instances. We demonstrated how to use <a href="https://github.com/teamdatatonic/terraform-google-secure-vertex-workbench">the Terraform module</a> to build the infrastructure in a repeatable and scalable way.</p><p>By using Terraform to manage our Vertex AI Workbench environments, we can achieve greater consistency, scalability, and security, while minimising manual effort and potential errors. With the power of Infrastructure-as-Code, we can easily automate the creation, modification, and destruction of our cloud infrastructure, enabling faster innovation and more efficient resource utilisation.</p><p><strong><em>Datatonic is </em></strong><a href="https://datatonic.com/insights/datatonic-google-cloud-specialization-partner-award-machine-learning/"><strong><em>Google Cloud’s Machine Learning Partner of the Year</em></strong></a><strong><em> with a wealth of experience developing and deploying impactful Machine Learning models and MLOps Platform builds. Need help with developing an ML model, or deploying your Machine Learning models fast? Have a look at our </em></strong><a href="https://datatonic.com/insights/vertex-ai-mlops-platform/"><strong><em>MLOps 101 webinar,</em></strong></a><strong><em> where our experts talk you through how to get started with Machine Learning at scale or </em></strong><a href="https://datatonic.com/contact"><strong><em>get in touch</em></strong></a><strong><em> to discuss your ML or MLOps requirements!</em></strong></p><blockquote>The author would like to thank <a href="https://medium.com/@jonny.browning">Jonny Browning</a> and <a href="https://stan-hill.medium.com/">Stan Hill</a> for their careful review and thoughtful comments</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d101080e6670" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vertex AI Tips +Tricks: Data Validation in Vertex Pipelines using Great Expectations]]></title>
            <link>https://medium.com/@afernaes/vertex-ai-tips-tricks-data-validation-in-vertex-pipelines-using-great-expectations-74bfaf7e2c77?source=rss-e4728e5c8b10------2</link>
            <guid isPermaLink="false">https://medium.com/p/74bfaf7e2c77</guid>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[mlops-platform]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[great-expectations]]></category>
            <dc:creator><![CDATA[Fernandez Estevez Ariadna]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 10:33:48 GMT</pubDate>
            <atom:updated>2023-01-24T10:39:46.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSdG88NfVOJQDyc6dzco5w.png" /></figure><h3>Introduction</h3><p>Building reliable and reproducible Machine Learning systems in production is a tough challenge that involves many facets beyond just the development of the ML model. Among these, data quality controls are an essential component for achieving high-quality models and predictions.</p><p>Data quality or data validation analysis includes identifying data inconsistencies and errors (such as missing fields or values), inconsistent formatting, and incorrect values (for example, negative incomes) etc. If some of these erroneous data points are included when training the model, this can lead to incorrect predictions, thus lowering the performance of the model. Similarly, if the data used at prediction time does not have the same characteristics as the data used to train the model, the predictions can often be unreliable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qNdTTX7UGHh0P9Qm" /><figcaption>D. Sculley et. al. NIPS 2015: Hidden Technical Debt in Machine Learning Systems</figcaption></figure><p><strong>In this blog post, we will show how to implement data validation using Great Expectations on Google Cloud’s Vertex AI Pipelines. Vertex AI Pipelines is based on KubeFlow Pipelines (KFP), an open-source platform for building Machine Learning pipelines using containers, and provides a great way to orchestrate your Machine Learning workflow on Google Cloud.</strong></p><p>Every ML pipeline involves several steps of accessing or manipulating data, such as data ingestion or feature engineering. In this post, we explain how to develop KFP components that can validate the data within any of these steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*lwj14ahspGAErXBZ" /></figure><p>We will create KFP components to perform two different tasks:</p><ol><li>Creating a Great Expectations Datasource.</li><li>Data validation, which will output a report and optionally include logging &amp; alerting.</li></ol><h3>What is Great Expectations?</h3><p>Great Expectations is an open-source Python tool for data validation, profiling and documentation. With Great Expectations, we can assert what we expect from a dataset through the use of “Expectations”, which are essentially assertions or unit tests applied to data. Great Expectations offers a great way to mitigate data quality issues that persist through machine learning pipelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*e4f0FHhhyaxCcHhV" /></figure><p>Before we jump into building components, we need to familiarise ourselves with key terminology and concepts within the Great Expectations workflow:</p><ul><li><strong>Data Context — </strong>A Data Context represents a Great Expectations project. It organises storage and access for Expectation Suites, Datasources, notification settings and data fixtures. The Data Context is created by instantiating Great Expectation via the CLI and is configured and maintained via the resulting <em>great_expectations.yml</em> file.</li><li><strong>Datasources — </strong>A Datasource is a configuration that describes where the data is, how to connect to it, and which execution engine to use when running a Checkpoint. Therefore, Datasources have two components: <em>storage </em>(e.g. BigQuery tables) and <em>compute </em>(e.g. SQLAlchemy). One of the main advantages of Great Expectations is the ability to validate data across various data sources, such as in-memory Pandas, Spark data frames, CSV files stored on the cloud, or relational databases such as BigQuery and PostgreSQL.</li><li><strong>Expectations — </strong>Expectations provide a language for describing the expected behaviour of data. They are stored within Expectation Suites, which are a collection of Expectations in JSON format. Expectation Suites and Datasets have a many-to-many relationship; an Expectation Suite can be used to validate data across one or more datasets, and one dataset can be validated using one or more Expectation Suites. Some commonly used Expectations include checking for missing values, validating data types, and validating whether a value is found in a predefined set, or is between a min and a max value. The full list of available Expectations can be found in the <a href="https://greatexpectations.io/expectations">Expectations Gallery</a>.</li><li><strong>Batch Request — </strong>A Batch Request defines a batch of data to run Expectations on from a given data source. They can describe data in a file, database, or dataframe.</li><li><strong>Checkpoint Config — </strong>Checkpoint Configs describe which Expectation Suite should be run against which data, and what actions to take during and after a run (e.g., sending Slack notifications informing of failed validations).</li><li><strong>Data Docs — </strong>Data Docs are clean, human-readable documents that contain information about a validation, such as the Expectation Suite used for validation, the result of each Expectation assertion etc. Data Docs exist in HTML inside the Data Context.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FCYC35V48yej3nCR" /></figure><p>In order to perform a validation, we need to have a Datasource and an Expectation Suite already defined. Then, using a Checkpoint that combines the different available Datasource and Expectations, we are able to validate that all the Expectations have been successfully satisfied.</p><h3>How can we integrate Great Expectations in Vertex AI?</h3><p>Before we create a Data Validation component using Great Expectations, we first need to set up our Google Cloud project to be able to run Great Expectations with a Data Context located in Google Cloud Storage.</p><h4>Data Context creation in GCS</h4><p>First, we need to create the Data Context. At the time of writing, Great Expectations does not allow us to create a Data Context directly on a remote bucket. Therefore, we need to create the Data Context locally and then copy the resulting directory to a GCS bucket.</p><p>To start, open your terminal and run these commands:</p><pre>pip install great_expectations<br>great_expectations init</pre><p>This will install the Great Expectations library and initialise it. In the terminal, we will see a message from Great Expectations saying that a new Data Context will be created, and with this, a new directory that contains the following structure:</p><pre>   great_expectations<br>   |-- great_expectations.yml<br>   |-- expectations<br>   |-- checkpoints<br>   |-- plugins<br>   |-- .gitignore<br>   |-- uncommitted<br>       |-- config_variables.yml<br>       |-- data_docs<br>       |-- validations</pre><p>Selecting <em>yes</em> when prompted will allow Great Expectations to create the folder structure. The resulting folders and files are self-explanatory: <em>great_expectations.yml</em> contains the information on the Data Context and Data Sources. The <em>expectations</em> folder contains all the JSON Expectations Suite files, the <em>checkpoints</em> folder contains all the YAML checkpoints files, and so on. The <em>uncommitted/data_docs/local_site_validations </em>folder will contain the Data Docs in HTML format, which are the outputs of the applied validations.</p><p>Once we create the <em>great_expectations</em> directory, we then need to copy it into a GCS bucket by running the following:</p><pre>gsutil cp -r great_expectations gs://&lt;BUCKET NAME&gt;/great_expectations</pre><p>As a note, we need to take into account that Great Expectations only works with a local Data Context. Luckily for us, Vertex Pipelines uses <a href="https://cloud.google.com/vertex-ai/docs/training/code-requirements#fuse">GCSFuse</a> to make Google Cloud Storage buckets available in the filesystem under <em>/gcs/&lt;BUCKET NAME&gt;</em>.</p><p>In the future, every time we have to specify a path to either a Vertex pipeline component or in a notebook in Workbench with this GE backend, we will need to provide the following:</p><pre>import great_expectations as gx<br>context = gx.data_context.DataContext(context_root_dir=/gcs/&lt;BUCKET NAME&gt;/great_expectations)</pre><p>This Data Context definition is what will allow us to work with a Great Expectations backend located in GCS, that can be used in any part or tool of the project.</p><p>The workflow to create components which will run validations using Great Expectations is as follows:</p><ol><li>Connect to Datasources</li><li>Create Expectation Suites</li><li>Create a validation component, which will include creating Checkpoints</li><li>Create Logging &amp; Alerting logic</li></ol><h3>1. Connect to Datasources</h3><p>The first step of the workflow is to define the connections to all Datasources we want to validate. <strong>For this blog post, we will only focus on creating a Datasource that connects to a GCS bucket that contains CSV files</strong>. Defining the Datasource connections is done by configuring the <em>great_expectations.yml</em> file. There are a few ways to do this, and the <a href="https://docs.greatexpectations.io/docs/guides/connecting_to_your_data/connect_to_data_overview/">Great Expectations documentation</a> contains guides that cover most use cases.</p><p>Depending on the use case, the files we need to validate may stay static over time (i.e. location of the files/tables remain unchanged) or the data may be generated as a Dataset Artifact, thus being located in a particular subfolder of the pipeline_root bucket of the <a href="https://cloud.google.com/vertex-ai/docs/pipelines/build-pipeline">Vertex Pipeline</a>.</p><h4>1.1. Static Datasource</h4><p>If we expect our CSV files to always be stored in the same GCS bucket, we therefore only expect to create the Datasource once, as Great Expectations will link that Datasource with that particular bucket. The code below shows how to create a new Datasource:</p><pre>from ruamel import yaml<br><br>import great_expectations as gx<br>from great_expectations.core.batch import Batch, BatchRequest, RuntimeBatchRequest<br><br>context = gx.get_context()<br><br>datasource_yaml = rf&quot;&quot;&quot;<br>name: {DATASOURCE_NAME}<br>class_name: Datasource<br>execution_engine:<br>    class_name: PandasExecutionEngine<br>data_connectors:<br>    default_runtime_data_connector_name:<br>        class_name: RuntimeDataConnector<br>        batch_identifiers:<br>            - default_identifier_name<br>    default_inferred_data_connector_name:<br>        class_name: InferredAssetGCSDataConnector<br>        bucket_or_name: {BUCKET_NAME}<br>        prefix: {PREFIX_NAME}<br>        default_regex:<br>            pattern: (.*)\.csv<br>            group_names:<br>                - data_asset_name<br>&quot;&quot;&quot;<br><br>context.add_datasource(**yaml.load(datasource_yaml))</pre><p>Make sure to edit the Datasource name and the GCS bucket and prefix name for where your CSV file(s) are located. For validation purposes, we recommend following the <a href="https://docs.greatexpectations.io/docs/guides/connecting_to_your_data/filesystem/pandas">Test your new Datasource</a> section of the Great Expectations documentation.</p><p><strong>NOTE:</strong> The line of code <em>context=gx.get_context()</em> is advisable if you are working locally. However, as we have already mentioned, we aim to use Great Expectations in a production environment and therefore we recommend working in a Workbench and pointing the Data Context to the GCS backend that we have uploaded previously, by defining the context as follows:</p><pre>context = gx.data_context.DataContext(context_root_dir=/gcs/&lt;BUCKET NAME&gt;/great_expectations)</pre><h4>1.2. Dynamic Datasource</h4><p>When dealing with Vertex AI Pipelines, it is very common to work with intermediate Artifacts that sit between different components. Amongst these Artifacts, we will find Datasets, which sometimes can be outputs of pre-processing or featuring engineering steps generated by a particular component. These Artifacts are usually stored in a sub-path that is automatically generated by Vertex inside the <em>pipeline_root</em> bucket that we define when building the pipeline. This means that the location of the Dataset changes every time a new pipeline run takes place. Therefore, for this particular use case, we need to create a new Vertex AI Pipelines component that automatically updates the location of the Datasource in the Great Expectations Data Context.</p><p>The component that works for this use case is introduced below. The steps followed by the component are:</p><ol><li>Firstly, we have the full path of the Dataset Artifact as an Input, but we need to split that path into the bucket name and the prefix (the subpath inside the bucket where the Dataset is located) to add it to the Datasource definition.</li><li>We define the Datasource and add it to the Great Expectations Data Context as we did in the Static Datasource.</li><li>We want to validate that the Datasource connection is established and working properly. This step is not mandatory, but it is recommended. For this, we need to have an Expectation Suite already loaded into our GCS backend. We also need to create a BatchRequest from the Datasource. We finally validate the data through a validator object using the BatchRequest and the Expectation Suite. If the validator fails, the component fails.</li></ol><pre>from kfp.v2 import dsl<br>from kfp.v2.dsl import Dataset, Input<br><br><br>@dsl.component(base_image=&quot;python:3.9&quot;, packages_to_install=[&quot;great_expectations==0.15.32&quot;])<br>def create_gcs_great_expectations_datasource(<br>   dataset_bucket: str<br>   dataset: Input[Dataset],<br>   datasource_name: str,<br>   ge_context_root_dir: str,<br>   expectation_suite_validation: str,<br>   data_connector_name: str,<br>  <br>):<br><br>   import logging<br>   from pathlib import Path<br><br>   import great_expectations as gx<br>   from great_expectations.core.batch import BatchRequest<br>   from pathlib import Path<br><br>   context = gx.data_context.DataContext(context_root_dir=ge_context_root_dir)<br>   <br>   bucket=Path(dataset.path).parts[2]<br>   datasource_prefix = &quot;/&quot;.join(Path(dataset.path).parts[3:-1])<br><br>   datasource_yaml = rf&quot;&quot;&quot;<br>       name: {datasource_name}<br>       class_name: Datasource<br>       execution_engine:<br>           class_name: PandasExecutionEngine<br>       data_connectors:<br>           default_runtime_data_connector_name:<br>               class_name: RuntimeDataConnector<br>               batch_identifiers:<br>                   - default_identifier_name<br>           {data_connector_name}:<br>               class_name: InferredAssetGCSDataConnector<br>               bucket_or_name: {bucket}<br>               prefix: {datasource_prefix}<br>               default_regex:<br>                   pattern: (.*)\.csv<br>                   group_names:<br>                       - data_asset_name<br>       &quot;&quot;&quot;<br><br>   context.add_datasource(**yaml.load(datasource_yaml))<br>   # Test the connection<br>   context.test_yaml_config(yaml_config=datasource_yaml)<br>   logging.info(&quot;Data Source updated&quot;)<br><br>   data_asset_name = dataset.path.replace(f&quot;{pipeline_root_path}/&quot;, &quot;&quot;).replace(&quot;.csv&quot;, &quot;&quot;)<br>   logging.info(f&quot;Data Asset Name: {data_asset_name}&quot;)<br><br>   batch_request = BatchRequest(<br>       datasource_name=datasource_name,<br>       data_connector_name=data_connector_name,<br>       data_asset_name=data_asset_name,<br>   )<br><br>   context.get_expectation_suite(expectation_suite_name=expectation_suite_validation)<br>   context.get_validator(<br>       batch_request=batch_request, expectation_suite_name=expectation_suite_validation<br>   )<br><br>   logging.info(&quot;Data Source successfully created&quot;)</pre><p>After creating our GCS datasource, the datasources section of the <em>great_expectations.yml</em> file looks like this:</p><pre>datasources:<br> my_datasource:<br>   data_connectors:<br>     default_runtime_data_connector_name:<br>       module_name: great_expectations.datasource.data_connector<br>       batch_identifiers:<br>         - default_identifier_name<br>       class_name: RuntimeDataConnector<br>       name: default_runtime_data_connector_name<br>     default_inferred_data_connector_name:<br>       module_name: great_expectations.datasource.data_connector<br>       default_regex:<br>         pattern: (.*)\.csv<br>         group_names:<br>           - data_asset_name<br>       prefix: my_prefix<br>       class_name: InferredAssetGCSDataConnector<br>       name: default_inferred_data_connector_name<br>       bucket_or_name: dataset_bucket<br>   module_name: great_expectations.datasource<br>   execution_engine:<br>     module_name: great_expectations.execution_engine<br>     class_name: PandasExecutionEngine<br>   class_name: Datasource</pre><h3>2. Create Expectation Suites</h3><p>There are four workflows that can be used to create an Expectation Suite (in-depth instructions <a href="https://docs.greatexpectations.io/docs/guides/expectations/create_expectations_overview">here</a>), but in this blog, we will focus on creating one using the interactive workflow with Python<em> </em>method by writing code in a Jupyter notebook. This method requires the Datasource we want to validate against to be configured in the <em>great_expectations.yml</em> file as we did in the <strong>1. Connect to Datasources</strong> section.</p><p>This method has the following workflow:</p><ol><li>Create a Batch Request, which specifies a batch of data to be used to create Expectations against.</li><li>Specify the name of our Expectation Suite.</li><li>Instantiate a validator<em> </em>object responsible for running our Expectation Suite against the data.</li><li>Create Expectations using the validator object and save them in the Expectation Suite.</li></ol><p>The code below shows how to create an Expectation Suite and add a few Expectations. As usual, remember to edit the variable names.</p><pre>import great_expectations as gx<br>from great_expectations.core.batch import BatchRequest<br><br>DATASOURCE_NAME = {DATASOURCE_NAME}<br>DATA_CONNECTOR_NAME = {DATA_CONNECTOR_NAME}<br>GCS_PREFIX = {GCS_PREFIX}<br>FILE_NAME = {FILE_NAME.csv}<br>EXPECTATION_SUITE_NAME = {EXPECTATION_SUITE_NAME}<br><br>context = gx.data_context.DataContext(context_root_dir=/gcs/&lt;BUCKET_NAME&gt;/great_expectations)<br><br>batch_request = BatchRequest(<br>    datasource_name = DATASOURCE_NAME,<br>    data_connector_name = DATA_CONNECTOR_NAME,<br>    data_asset_name = f&quot;{GCS_PREFIX}/{FILE_NAME}&quot;<br>) <br><br>suite = context.create_expectation_suite(expectation_suite_name = EXPECTATION_SUITE_NAME, overwrite_existing=True)<br><br>validator = context.get_validator(<br>    batch_request = batch_request,<br>    expectation_suite_name = {EXPECTATION_SUITE_NAME}<br>)<br><br># Expect all `customer_id` values to not be null<br>validator.expect_column_values_to_not_be_null(column=&#39;customer_id&#39;)<br><br># Expect all `unique_key` values to be unique<br>validator.expect_column_values_to_be_unique(column=&#39;unique_key&#39;)<br><br># Expect all `unique_key` values to be 40 characters long<br>validator.expect_column_value_lengths_to_equal(column = &#39;unique_key&#39;, value=40)<br><br># Expect `taxi_trip_in_seconds` values to be greater than 0<br>validator.expect_column_values_to_be_between(column = &#39;taxi_trip_in_seconds&#39;, min_value=0)<br><br># Expect mean of all `taxi_trip_fare` values to be between 20 and 30 dollars<br>validator.expect_column_mean_to_be_between(column = &#39;taxi_trip_fare&#39;, min_value=20, max_value=30)<br><br># Expect `trip_start_timestamp` dates to be between 01/01/2000 and today<br>validator.expect_column_values_to_be_between(column = &#39;trip_start_timestamp&#39;, min_value=date.fromisoformat(&quot;2000-01-01&quot;), max_value=datetime.date.today().strftime(&#39;%Y-%m-%d&#39;))<br><br># Expect `payment_type` values to be in set {&#39;Cash&#39;, &#39;Credit Card&#39;}<br>validator.expect_column_values_to_be_in_set(column = &#39;payment_type&#39;, value_set=[&quot;Cash&quot;, &quot;Credit Card&quot;])<br><br>validator.save_expectation_suite(discard_failed_expectations=False)</pre><p>After creating the Expectation Suite, remember to use <em>gsutil</em> to copy the resulting JSON file into the expectations folder in GCS.</p><p><strong>NOTE:</strong> We know that the Expectation Suites are stored automatically in the <em>great_expectations/expectations</em> folder. Alternatively, we can also define any other folder or bucket to host our Expectations Suites. Great Expectations calls this an Expectation Store. We just need to update the <em>great_expectations.yml</em> file accordingly, but for more information refer <a href="https://docs.greatexpectations.io/docs/guides/setup/configuring_metadata_stores/how_to_configure_an_expectation_store_in_gcs/">here</a>.</p><p><strong>Considerations</strong></p><p>The list of all available Expectations can be found <a href="https://greatexpectations.io/expectations/">here</a>. However, there are a few things we need to consider:</p><ul><li>Among all of the Expectations present in the Expectations Gallery, only the ones labelled to be in Production will work and therefore are available through the <em>great_expectations</em> Python Library.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*hEiaexeCrSMMFSdY" /></figure><ul><li>Not all the Expectations are available across all types of Datasources. Before using an Expectation, please check whether it can be integrated with your required Datasource</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wybHOkUQZFqa2cvV" /></figure><ul><li>Custom Expectations can be also created. For more information refer <a href="https://legacy.docs.greatexpectations.io/en/0.13.8/guides/how_to_guides/creating_and_editing_expectations/how_to_create_custom_expectations.html#how-to-guides-creating-and-editing-expectations-how-to-create-custom-expectations">here</a>.</li></ul><h3>3. Data Validation Component</h3><p>We can now create the Data Validator component inside a Vertex AI Pipelines component that will allow us to validate our connected Datasource using the Expectation Suite we’ve just created. The recommended method for validating data is through the use of Checkpoints. Checkpoints will validate data, save validation results, run any actions we have specified, and finally create Data Docs with their results.</p><p>The logic is simple. We need to provide all the information we mentioned before: everything related to the Data Context, Datasource and the Expectation Suite. In addition, we have an Output[HTML] Artifact that will be used to output the results of the validation in HTML format, by making use of Great Expectation’s Data Docs.</p><p>The component consists of the following steps:</p><ol><li>Definition of the Data Context (remember that we use a Data Context located in GCS).</li><li>As mentioned before, to perform a validation we need to create a Checkpoint where we define the combination of Expectation Suite and Dataset that needs to be validated.</li><li>We will run the newly created and saved Checkpoint, resulting in a <em>CheckpointResult</em> object that contains appropriate metadata.</li><li>Finally, we parse the <em>CheckpointResult</em> into a <em>ExpectationSuiteValidationResult</em> object to be able to render its HTML and show it as an output.</li></ol><pre>from kfp.v2 import dsl<br>from kfp.v2.dsl import HTML, Output<br><br>@dsl.component(<br>    base_image=&quot;python:3.9&quot;,<br>    packages_to_install=[&quot;great_expectations==0.15.32&quot;, &quot;google-cloud-logging==3.2.5&quot;],<br>)<br>def data_validation(<br>    ge_context_root_dir: str,<br>    checkpoint_name: str,<br>    datasource_name: str,<br>    data_connector_name: str,<br>    data_asset_name: str,<br>    expectation_suite_validation: str,<br>    output_html: Output[HTML],<br>    project_id: str,<br>) -&gt; list:<br><br>  import logging<br>  <br>  import great_expectations as gx<br>  from great_expectations.render.renderer import ValidationResultsPageRenderer<br>  from great_expectations.render.view import DefaultJinjaPageView<br>  from ruamel import yaml<br>  <br>  context = gx.data_context.DataContext(context_root_dir=ge_context_root_dir)<br>  <br>  # In order to create a validation step, a checkpoint needs to be created.<br>  # Checkpoints combine the data_asset_name with its corresponding expectation suite.<br>  <br>  yaml_config = f&quot;&quot;&quot;<br>              name: {checkpoint_name}<br>              config_version: 1.0<br>              class_name: SimpleCheckpoint<br>              run_name_template: &quot;%Y%m%d-%H%M%S&quot;<br>              validations:<br>                - batch_request:<br>                    datasource_name: {datasource_name}<br>                    data_connector_name: {data_connector_name}<br>                    data_asset_name: {data_asset_name}<br>                    data_connector_query:<br>                      index: -1<br>                  expectation_suite_name: {expectation_suite_validation}<br>              &quot;&quot;&quot;<br>  <br>  context.add_checkpoint(**yaml.load(yaml_config))<br>  # Run checkpoint to validate the data<br>  checkpoint_result = context.run_checkpoint(checkpoint_name=checkpoint_name)<br>  <br>  # Validation results are rendered as HTML<br>  document_model = ValidationResultsPageRenderer().render(<br>      list(checkpoint_result.run_results.values())[0][&quot;validation_result&quot;]<br>  )<br>  <br>  if not output_html.path.endswith(&quot;.html&quot;):<br>      output_html.path += &quot;.html&quot;<br>  <br>  # Write validation results as output HTML<br>  with open(output_html.path, &quot;w&quot;) as writer:<br>      writer.write(DefaultJinjaPageView().render(document_model))</pre><p>The final HTML output Artifact shows the results of the validations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sqSC82LmDfRHu8ii" /></figure><p><strong>NOTE: </strong>In the example code here we have defined the configuration using YAML in a string to be consistent with the Great Expectations documentation. However, you could also define the configuration directly in a Python dictionary.</p><h3>4. Logging &amp; Alerting</h3><p>We now have a pipeline component that reads a Datasource, loads an Expectation Suite and validates our data. But what if our Expectations fail? Should the pipeline fail? To enable this, we have to add the following lines of code into the component:</p><pre>if not checkpoint_result[&quot;success&quot;]:<br>        raise RuntimeError(f&quot;Validations failed&quot;)</pre><p>Or perhaps we only want the component to send a log to Google Cloud Logging, which we can use later to generate custom alerts or e-mails. If we want to be more specific we can, for example, generate specific logs for any monitoring and alerting tool. We can add the following code snippet to the already existing component, which will help us to parse the validation results and generate the proper logging alerts.</p><p>These are the steps followed:</p><ol><li>Get a dictionary with all the validation results.</li><li>Create a Google Logger. If we want to search for a particular logging message in the future, it will be easier if this logging message has a particular name, shape or message.</li><li>Iterate over all the validation results and check the columns and Expectations that have failed.</li><li>Log those particular failures.</li></ol><pre># Return validation results to check its results<br>validation_results = (checkpoint_result.to_json_dict()<br>            .get(&quot;run_results&quot;)<br>            .get(str(list(checkpoint_result.get(&quot;run_results&quot;).keys())[0]))<br>            .get(&quot;validation_result&quot;)<br>            .get(&quot;results&quot;)<br>        )<br><br>import google.cloud.logging<br>from google.cloud.logging.handlers import CloudLoggingHandler<br>from google.logging.type import log_severity_pb2 as severity<br><br><br># Create a handler for Google Cloud Logging.<br>log_name=&quot;great_expectations_logger&quot;<br>gcloud_logging_client = google.cloud.logging.Client(project=project_id)<br>gcloud_logging_handler = CloudLoggingHandler(gcloud_logging_client, name=log_name)<br>gcs_logger = gcloud_logging_client.logger(log_name)<br><br># Handle failed validations to check in which lists appear (ERRORS &amp; WARNINGS)<br>errors = []<br>for validation in validation_results:<br>   if not validation[&quot;success&quot;]:<br>      column_failed = validation[&quot;expectation_config&quot;][&quot;kwargs&quot;][&quot;column&quot;]<br>      expectation_failed = validation[&quot;expectation_config&quot;][&quot;expectation_type&quot;]<br>      errors.append(column_failed, expectation_failed)<br><br><br>if errors:<br>  json_payload = {&quot;message&quot;: f&quot;Great Expectations Errors: {errors}&quot;}<br>  gcs_logger.log_struct(json_payload, severity=severity.ERROR)</pre><p>This piece of code will generate specific logs if validations fail. If we want, we could generate a specific alert by querying those specific logs. For further information about creating Alerts on Vertex Pipelines, refer to this <a href="https://datatonic.com/insights/vertex-ai-setting-alerts-pipelines-google-cloud-monitoring/">blog post</a>.</p><p>In our particular case, we could use the following query to find the logs generated by this component as follows:</p><pre>logName=&quot;projects/{my_project}/logs/great_expectations_logger&quot;<br>resource.type=&quot;k8s_container&quot;<br>severity=&quot;ERROR&quot;<br>jsonPayload.message:&quot;Great Expectations Errors&quot;</pre><h3>Conclusion</h3><p>Poor data quality is one of the biggest challenges in Machine Learning, and it often leads to silent failures or poor performance in production. Now you can use Great Expectations to ensure data quality in your production ML pipelines on Vertex AI! In this post, we have shown only a simple example of data validation using Great Expectations, but it is a very powerful tool so be sure to check out the <a href="https://docs.greatexpectations.io/docs/">Great Expectations documentation</a> for more details. Finally, don’t forget to <a href="https://medium.com/datatonic">follow us on Medium</a> for more Vertex AI Tips and Tricks and much more!</p><p>Datatonic is <a href="https://datatonic.com/insights/datatonic-google-cloud-specialization-partner-award-machine-learning/">Google Cloud’s Machine Learning Partner of the Year</a> with a wealth of experience developing and deploying impactful Machine Learning models and MLOps platform builds. Need help with developing an ML model, or deploying your Machine Learning models fast? Have a look at our <a href="https://datatonic.com/insights/vertex-ai-mlops-platform/">MLOps101 webinar</a>, where our experts talk you through how to get started with Machine Learning at scale or <a href="https://datatonic.com/contact/">get in touch</a> to discuss your ML or MLOps requirements!</p><blockquote>The author would like to thank <a href="https://medium.com/u/3a1fa3c248b">Valentin I Cojocaru</a> and <a href="https://medium.com/u/ff760d36db53">Jonny Browning</a> for their careful review and thoughtful comments</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74bfaf7e2c77" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>