<?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 Penny Qian on Medium]]></title>
        <description><![CDATA[Stories by Penny Qian on Medium]]></description>
        <link>https://medium.com/@pennyqxr?source=rss-cfd77288e590------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cALEYdywZXR0NeWcS2vr9A.png</url>
            <title>Stories by Penny Qian on Medium</title>
            <link>https://medium.com/@pennyqxr?source=rss-cfd77288e590------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:29:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pennyqxr/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[Data validations on Vertex AI for metadata and content check]]></title>
            <link>https://medium.com/@pennyqxr/data-validations-on-vertex-ai-for-metadata-and-content-check-ae2d790b7546?source=rss-cfd77288e590------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae2d790b7546</guid>
            <category><![CDATA[great-expectations]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Penny Qian]]></dc:creator>
            <pubDate>Tue, 23 May 2023 12:44:20 GMT</pubDate>
            <atom:updated>2023-05-23T12:44:20.581Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*69tC1z-OvqEouP-s" /><figcaption>Photo by <a href="https://unsplash.com/@nataruta?utm_source=medium&amp;utm_medium=referral">Ната Рута</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://cloud.google.com/vertex-ai">Vertex AI</a> is a unified artificial intelligence platform that offers all of Google’s cloud services under one roof. When we start to develop ML solutions on Vertex AI, one common issue is to ensure the quality of the data for downstream processing (analytics, visualizations, machine learning, etc).</p><p>In principle, the data validation should happen across the whole machine learning development cycle, from data ingestion to final predictions, as the figure is shown below. The scope of this article will be focusing on pre-training and post-prediction data validations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrhpNDATUf7joW9rDxMnhw.png" /></figure><h3>Metadata validation</h3><p>Medatada in simple words describe as data about data. Verifying metadata can be a lightweight way to sense if the data is in good shape with minimum effort. To verify the metadata of incoming data tables, we need several steps:</p><ul><li>read the dependency tables metadata and convert it into an agreeable format</li><li>performs checks on the metadata of the table, which can simply be some pre-defined assertions</li><li>output the test results</li></ul><p>Each of the steps can be described as a component such as a Kubeflow component, that together forms a Kubeflow pipeline @dsl.pipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*faouRsOUSgCxHJ7rMCC3-w.png" /></figure><p>In our case, our data is stored in GCP BigQuery, and we can simply fetch the metadata using the BigQuery client and perform the checks as below:</p><pre>from google.cloud import bigquery<br><br>client = bigquery.Client(project=PROJECT_ID)<br><br># define a lambda function to get the delta days<br>get_delta_day = lambda td: td.days<br><br># perform general checks<br>  for bq_table in bq_tables:<br>      table = client.get_table(bq_table)<br>      print(<br>          &quot;Got table &#39;{}.{}.{}&#39;.&quot;.format(<br>              table.project, table.dataset_id, table.table_id<br>          )<br>      )<br>      print(&quot;Table schema: {}&quot;.format(table.schema))<br>      print(&quot;Table description: {}&quot;.format(table.description))<br>      print(&quot;Table has {} rows&quot;.format(table.num_rows))<br><br>      assert table.num_rows &gt; 0, &quot;Table has no rows&quot;<br>      assert (<br>          get_delta_day(datetime.now(pytz.utc) - table.modified) &lt; 30<br>      ), &quot;Table is not updated in the last 30 days&quot;<br><br># Table specific checks<br>table1 = client.get_table(&quot;table_name&quot;)<br><br># add example assert here<br>assert (<br>    get_delta_day(datetime.now(pytz.utc) - table1.modified) &lt; 3<br>), &quot;Table is not updated in the last 3 days&quot;</pre><p>In Vertex AI each component can be linked using dependency logics. You can refer to our full pipeline example <a href="https://github.com/PennyQ/pennyq-medium/blob/main/data-validation-vertex-ai/metadata-validation.py">here</a> which contains two steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*hISjgSdL_MrZFKU-VkRn6g.png" /></figure><h3>Content validation</h3><p>There are multiple choices regarding a tool for data validation. For example, the <a href="https://endjin.com/blog/2023/03/a-look-into-pandera-and-great-expectations-for-data-validation">comparison</a> of <a href="https://pandera.readthedocs.io/en/stable/index.html">Pandera</a> and <a href="https://docs.greatexpectations.io/docs/">Great Expectations</a> the two popular Python libraries.</p><p>In this article, we chose Great Expectations (GE) to implement for the reasons below:</p><ul><li>GE can serve for data science-specific expectations (e.g. validate the distribution range, specify expectations relevant to the business)</li><li>Provides a centralized and readable place for the test suites</li><li>Includes a nice dashboard for the test results summary</li><li>Can auto-generate expectations based on fed data</li></ul><p>Before jumping into the implementation, Great Expectations has a few key terminology and concepts in the workflow:</p><ul><li><strong>Data Context:</strong> represents a GE project, is created by instantiating GE via the CLI and configured via the great_expectations.yml file</li><li><strong>Datasources:</strong> a configuration that describes where the data is, how to connect to it, and which execution engine to use when running a Checkpoint.</li><li><strong>Expectations:</strong> description of the expected behavior of data.</li><li><strong>Batch Request:</strong> defines a batch of data to run Expectations on from a given data source.</li><li><strong>Checkpoint config</strong>: defines which Expectation Suite to run against which data, and which actions to take during and after a run.</li></ul><h4>Implementation</h4><p>The workflow of Great Expectations works as below: the data to be validated gets into GE, and through the validation the results go out</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*wBfdkZQDkpKP9P63.png" /><figcaption>source: <a href="https://docs.greatexpectations.io/docs/">https://docs.greatexpectations.io/docs/</a></figcaption></figure><p>To integrate the above in Vertex AI, we need several steps, and we also use a GCS bucket to store the initiation folders together as the output results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apuyXJXthnB_qnL-mbPR4g.png" /></figure><p>To start with the implementation, open your terminal and run these commands:</p><pre>pip install great_expectations<br>great_expectations init<br>gsutil cp -r great_expectations gs://{your_gcs_bucket}</pre><p>This will create an initiation folder of Great Expectations and copy it to GCS bucket. For the Vertex AI component, the files that are stored in GCS bucket can be accessed as the way for the filesystem. Because the GCS will be mounted as a filesystem automatically via Cloud Storage FUSE.</p><p>One thing to note here is that the root directory `/gcs` is not readable. If you run ls /gcs, you will get an “Input/output error”. However, it is okay to read the bucket root such as ls /gcs/example-bucket. So in our case, we can access the Great Expectation folder via the path of /gcs/{your_gcs_bucket}/great_expectations</p><p>After initiation, we can start adding the data source to the Great Expectations config. In our case the main data source is from the GCS bucket, so we need to specify it in the <a href="https://docs.greatexpectations.io/docs/terms/data_connector/">data connector</a> part, as shown below:</p><pre>context = gx.data_context.DataContext(<br>        context_root_dir=&quot;/gcs/penny-trial-bucket/great_expectations&quot;<br>    )<br><br>    datasource_yaml = rf&quot;&quot;&quot;<br>    name: my_datasource<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: penny-trial-bucket<br>            prefix: great_expectations_test_csvs<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;)</pre><p>After that, we can define a batch request that can fetch a selection of records from the data source that can be used in validation.</p><pre>batch_request = RuntimeBatchRequest(<br>        datasource_name=&quot;my_datasource&quot;,<br>        data_connector_name=&quot;default_runtime_data_connector_name&quot;,<br>        data_asset_name=&quot;&quot;,  # this can be anything that identifies this data_asset for you<br>        runtime_parameters={<br>            &quot;path&quot;: &quot;&quot;<br>        },  # Add your GCS path here.<br>        batch_identifiers={&quot;default_identifier_name&quot;: &quot;default_identifier&quot;},<br>    )<br><br># rewrite so the format can be correct<br>batch_request.data_asset_name = &quot;great_expectations_test_csvs/test-data1&quot;<br>batch_request.runtime_parameters[&quot;path&quot;] = f&quot;gs://penny-trial-bucket/great_expectations_test_csvs/test-data1.csv&quot;</pre><p>and also create the test suite, this test suite is then written to the GE initiation folder in GCS bucket `penny-trial-bucket/great_expectations/expectations/test-suite.json`</p><pre>suite = context.create_expectation_suite(<br>    expectation_suite_name=&quot;test_suite&quot;, overwrite_existing=True<br>)<br>validator = context.get_validator(<br>    batch_request=batch_request, expectation_suite_name=&quot;test_suite&quot;<br>)<br><br># Expect all `customer_id` values to not be null<br>validator.expect_column_values_to_not_be_null(column=&quot;seq&quot;)<br><br># Expect all `unique_key` values to be unique<br>validator.expect_column_values_to_be_unique(column=&quot;name/first&quot;)<br><br># # Expect `taxi_trip_in_seconds` values to be greater than 0<br>validator.expect_column_values_to_be_between(<br>    column=&quot;age&quot;, min_value=0, max_value=150<br>)<br><br># And save the final state to JSON<br>validator.save_expectation_suite(discard_failed_expectations=False)</pre><p>Now the final step is to create a checkpoint to assign the test suite we created to the batch data we wanna validate, and then output the test results. The concept of the checkpoint is a bundle of batch requests, data sources, and validators as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hB95XWnbCwL_qct5.png" /><figcaption>source: <a href="https://docs.greatexpectations.io/docs/terms/checkpoint/">https://docs.greatexpectations.io/docs/terms/checkpoint/</a></figcaption></figure><pre># Define the checkpoint<br>yaml_config = f&quot;&quot;&quot;<br>      name: my_checkpoint<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: my_datasource<br>            data_connector_name: default_inferred_data_connector_name<br>            data_asset_name: great_expectations_test_csvs/test-data1<br>            data_connector_query:<br>              index: -1<br>          expectation_suite_name: test_suite<br>      &quot;&quot;&quot;<br><br># Add the checkpoint to context<br>context.add_checkpoint(**yaml.load(yaml_config))<br><br># Run checkpoint to validate the data<br>checkpoint_result = context.run_checkpoint(checkpoint_name=&quot;my_checkpoint&quot;)<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># Write validation results as output HTML<br>with open(&quot;/gcs/penny-trial-bucket/output.html&quot;, &quot;w&quot;) as writer:<br>    writer.write(DefaultJinjaPageView().render(document_model))</pre><p>The final results are then written to the GCS bucket. The full Vertex AI pipeline and code are <a href="https://github.com/PennyQ/pennyq-medium/blob/main/data-validation-vertex-ai/content-validation.py">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*746hMEA1L2nnzaT-OcZgFw.png" /></figure><h3>Conclusions</h3><p>In this article, we went through the two general types of data validation metadata validation and content validation. For each type, we also provided an implementation in Vertex AI as part of the model training or prediction pipeline.</p><p>These implementations are good for experiments and can be further improved for team collaborations. For example, the test suites can be stored and version controlled so as to be shared across the team. Also, the components can be wrapped into containers so they can be imported into the existing pipelines more easily.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae2d790b7546" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Helm repository in two ways: using Google Cloud Artifact and Github Pages]]></title>
            <link>https://medium.com/@pennyqxr/creating-a-helm-repository-in-two-ways-using-google-cloud-artifact-and-github-pages-bad1a250fe9b?source=rss-cfd77288e590------2</link>
            <guid isPermaLink="false">https://medium.com/p/bad1a250fe9b</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[google-cloud]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[helm]]></category>
            <dc:creator><![CDATA[Penny Qian]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 09:54:29 GMT</pubDate>
            <atom:updated>2023-01-20T09:54:29.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rWMrr8UIlhzfr1in" /><figcaption>Photo by <a href="https://unsplash.com/@loik_marras?utm_source=medium&amp;utm_medium=referral">Loik Marras</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Helm is the tool to install and manage K8S applications.</p><p>A <em>Chart</em> is a Helm package. It contains all of the resource definitions necessary to run an application, tool, or service inside of a Kubernetes cluster. Think of it like the Kubernetes equivalent of a Homebrew formula, an Apt dpkg, or a Yum RPM file.</p><p>A <em>Repository</em> is a place where charts can be collected and shared. It’s like the <a href="https://hub.docker.com/">Docker Hub</a> for Docker images or the <a href="https://pypi.org/">PyPI Library</a> for Python packages, but for Kubernetes packages.</p><h4>Deploy from an unpackaged chart</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAvHkRHI1BpKYQIN8a-wAA.png" /></figure><p>The simple pipeline to deploy an unpackaged <em>chart</em> is shown above. The code is committed to a remote repository, that triggers a CI/CD pipeline to build the Docker image and push it to an image registry. Then Helm directly build the <em>chart</em> from the Docker image that is stored in the registry, and installs it to the target K8S cluster as a <em>release</em>.</p><p>This works well in the testing environment, while in production, often one chart is installed many times into the same cluster, as different <em>releases. </em>So it is important to keep a track of the different versions of the chart for rollback and debugging. Also, we could shorten the deployment process, by reusing stored Helm charts rather than building the same chart every time.</p><h4>Deploy from a packaged chart</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQfBb4Ks_XoEJVyr9X4CJw.png" /></figure><p>This pipeline added a step to build and push the Helm chart to the Helm repo. Once the chart is pushed to the Helm repo, it can be reused in other releases in different environments, no need to be built again.</p><p>There are several ways to set up a Helm repo, here I listed two that I have been trying out:</p><h4>Set up the Helm repo using Github Pages</h4><p><a href="https://pages.github.com/">Github Pages</a> is a static site hosting service that takes HTML, CSS, and JavaScript files straight from a repository on GitHub, optionally runs the files through a build process, and publishes a website. The benefit of adopting it is that you keep your project site code in the same code repo as the project itself.</p><p>For the implementation steps, <a href="https://helm.sh/docs/topics/chart_repository/#github-pages-example">helm.sh</a> has a clear walk-through page for it. I just wanna address the challenge I encountered when implementing a private Helm repo. We follow the steps and created a page like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*wf7E23rkT8Wgi7hUOLoaIw.png" /></figure><p>For the private GitHub Pages, if we simply added the above link to the Helm repo, there will be an error of authentication failure. Instead, we need to redirect the entry of the above URL to the the new endpoint ofraw.githubusercontent.com in the index.yamlThe new endpoint supports the basic authentication required for the private feed.</p><pre># Generate the index.yaml that pointed to the new endpoint<br>helm repo index . --url https://raw.githubusercontent.com/{your_org_name}/{your_project_name}/gh-pages/<br><br># Push the change to the remote pos<br>git add index.yaml<br>git commit -m &quot;Updated from ref: $GITHUB_SHA&quot;<br>git push origin gh-pages</pre><p>And then boom! When we access to the GitHub pages URL <a href="https://scaling-adventure-820c3edc.pages.github.io/index.yaml">https://scaling-adventure-820c3edc.pages.github.io/index.yaml</a> the repo page is working!</p><pre>apiVersion: v1<br>entries:<br>  model-api:<br>  - apiVersion: v2<br>    appVersion: 1.16.0<br>    created: &quot;2023-01-19T13:11:23.369817737Z&quot;<br>    description: A Helm chart for Kubernetes<br>    digest: 637ebc468865ccbfcf6a218d349ac647da9aa2b8ac02353610b72ecdefc2346a<br>    name: model-api<br>    type: application<br>    urls:<br>    - https://raw.githubusercontent.com/ingka-group-digital/pco-model-apps/gh-pages/model-api-0.1.0.tgz<br>    version: 0.1.0</pre><p>For the full procedures about creating a private helm repository using github pages enterprise via CICD pipeline, I’d recommend <a href="https://im5tu.io/article/2022/01/creating-a-private-helm-repository-using-github-pages-enterprise/">this</a> clear tutorial to walk through.</p><h4>Set up the Helm repo using Google Artifact Registry</h4><p><a href="https://cloud.google.com/artifact-registry">Google Artifact Registry</a> is an evolution of Container Registry, that can serve as a single place for the organisation to manage not only the container images, but also non-container artifacts like language packages for Python, Java, and Node.</p><p>The setup procedures are also clearly stated on the <a href="https://cloud.google.com/artifact-registry/docs/helm/store-helm-charts#console">Google Cloud page</a>. Firstly, we need to <a href="https://cloud.google.com/artifact-registry/docs/helm/authentication">authentication</a> Helm with Google Cloud, the safest way as recommended is to use the short-lived access token that a service account uses to access your Google Cloud resource.</p><p>Once the authentication is done, we can let Helm interact with the artifact registry, such as pushing the chart to the repo, or showing the chart information.</p><pre># push the built chart to the remote artifact repo<br>helm push model-api-0.1.0.tgz oci://europe-west4-docker.pkg.dev/{your_google_cloud_project}/helm-repo<br><br># list the images that are stored under the artifact repo<br>gcloud artifacts docker images list europe-west4-docker.pkg.dev/{your_google_cloud_project}/helm-repo<br><br># we can show the chart that lies on the docker artifact repo<br>helm show chart oci://europe-west4-docker.pkg.dev/{your_google_cloud_project}/helm-repo/model-api<br># Output is like below:<br># apiVersion: v2<br># appVersion: 1.16.0<br># description: A Helm chart for Kubernetes<br># name: model-api<br># type: application<br># version: 0.1.0</pre><h4>Conclusion</h4><p>Both ways provide a storage place for Helm charts that have version controlling and some access control. We do encounter some difficulties to set up during the real production environment. For GitHub Pages, the difficulty lies in creating the Private Helm repo. While for the Google Artifact Registry, authentication requires some tuned-up to get it to work.</p><h4>Reference:</h4><p><a href="https://codefresh.io/docs/docs/new-helm/helm-best-practices/">HELM Best practices</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bad1a250fe9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage Infrastructure as Code via Terraform for GCP]]></title>
            <link>https://medium.com/@pennyqxr/manage-infrastructure-as-code-via-terraform-for-gcp-9a245dd085d3?source=rss-cfd77288e590------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a245dd085d3</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[infrastructure]]></category>
            <dc:creator><![CDATA[Penny Qian]]></dc:creator>
            <pubDate>Wed, 30 Nov 2022 09:56:09 GMT</pubDate>
            <atom:updated>2022-11-30T09:56:09.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uTiHYiaFweF1np2n" /><figcaption>Photo by <a href="https://unsplash.com/@erikvandijk?utm_source=medium&amp;utm_medium=referral">Erik van Dijk</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong>Terraform</strong> is an open-source infrastructure as code software tool that enables you to safely and predictably create, change, and improve infrastructure.</blockquote><p>So according to the definition above. Terraform knows what are there in the remote infrastructure, and how to make changes to it. So how does Terraform knows about these and manage the changes?</p><h3>Statefile</h3><p>Terraform manage its knowledge by using a statefile Here is an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8uril5sh80fMIqmCQdFFw.png" /></figure><p>The statefile can be viewed as an internal API. In this example, we have several GCP resources that are managed by Terraform. When we run &gt;&gt;&gt; terraform state list, this gives me a list of resources managed by Terraform. Terraform will refer to the state file, which can be stored either locally or remotely while storing remotely is recommended, compare the remote infrastructure to the code and then make adjustments as necessary.</p><p>The actual content of this file is a JSON formatted mapping of the resources defined in the configuration and those that exist in your infrastructure. An example state file part is as below:</p><pre>{<br>&quot;mode&quot;: &quot;managed&quot;,<br>&quot;type&quot;: &quot;google_composer_environment&quot;,<br>&quot;name&quot;: &quot;composer_env&quot;,<br>&quot;provider&quot;: &quot;provider[\&quot;registry.terraform.io/hashicorp/google\&quot;]&quot;,<br>&quot;instances&quot;: […]<br>…<br>}</pre><p>It is also sometimes necessary to manipulate the state file, such as remove items when they have been imported incorrectly or no longer exist in the real infrastructure, or import items that already exist to bring them under Terraform management. <em>The later one can happen a lot when the cloud console UI interaction is enabled</em>.</p><p>Directly editing the JSON file can be error prone, Terraform provides several commands to update the state file:</p><ul><li>terraform state rm — Remove an item from the state file.</li><li>terraform state show — Show a resource in the state file.</li></ul><h3>Configurations</h3><p>OK, now we can start make changes to the infrastructure via Terraform. In Terraform this is called generate an execution plan It works as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZUqhWhUhlkPxbAkJYiFMQ.png" /></figure><p>Locally we stored Terraform configurations into terraform files ends with .tf. A simple Terraform configuration can be one file that consists of terraform, provider and resource.</p><pre>terraform {<br>  #required_version = &quot;~&gt;1.1.0&quot;<br>  required_providers {<br>    google = {<br>      source  = &quot;hashicorp/google&quot;<br>      version = &quot;&gt;=3.71.0&quot;<br>    }<br>  }<br>  backend &quot;gcs&quot; {<br>    bucket = &quot;your_gcs_bucket_name&quot;<br>  }<br>}<br><br>provider &quot;google&quot; {<br>  region  = &quot;us-central1&quot;<br>}<br><br>resource &quot;google_composer_environment&quot; &quot;airflow&quot; {<br>  name   = &quot;example-composer-env&quot;<br>  region = &quot;us-central1&quot;<br>}</pre><p>There are nice features provided by Terraform to organise the configurations in a neat way:</p><p>input variables — Unlike variables found in programming languages, Terraform’s input variables don’t change values during a Terraform run such as plan, apply, or destroy. Instead, they allow users to more safely customize their infrastructure by assigning different values to the variables before execution begins, rather than editing configuration files manually.</p><p>dependency lock file — Similar to Python requirements.txt, that tracks <em>provider</em> dependencies. When multiple users or automation tools run the same Terraform configuration, they should all use the same versions of their required providers.</p><p>modules — <em>Modules</em> are containers for multiple resources that are used together. A module consists of a collection of .tf and/or .tf.json files kept together in a directory. Modules are the main way to package and reuse resource configurations with Terraform.</p><h3>Apply Changes</h3><p>Firstly, we need to initiatize via the command terraform init This will allow Terraform to install the providers and modules referenced by the configuration.</p><p>Then, it will reference the locally cached providers and modules to create a plan of resource changes via the command terraform plan -out tfplan This will allow to preview the actions Terraform would take to modify your infrastructure. It also allows to save a speculative plan which can be applied later.</p><p>At this moment, no changes are made to the remote infrastructure, until the plan is applied and approved via the command terraform apply Terraform will provide a list of actions to be made, and apply changes to the remote infrastructure and the state file.</p><p>If the changes are applied successfully, you will see the texts like</p><pre>Apply complete! Resources: 1 added, 0 changed, 1 destroyed.</pre><p>Of course, things won’t always work. Especially in a lot of case, we often start working with an existing Terraform configurations that already is out of sync with the remote cloud environment. To sync Terraform with the remote cloud environment, I will write it in another article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a245dd085d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airflow logging and alerting on Google Cloud]]></title>
            <link>https://medium.com/@pennyqxr/airflow-logging-and-alerting-on-google-cloud-b07246efc2c2?source=rss-cfd77288e590------2</link>
            <guid isPermaLink="false">https://medium.com/p/b07246efc2c2</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[alerts]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Penny Qian]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 16:58:28 GMT</pubDate>
            <atom:updated>2022-08-24T16:58:28.433Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GBeE87n6XNzDSBBH" /><figcaption>Photo by <a href="https://unsplash.com/@moritz_photography?utm_source=medium&amp;utm_medium=referral">Moritz Kindler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Two types of Composer Airflow logs</h3><ul><li><strong>Airflow logs</strong>: associated with single DAG tasks. The task logs can be viewed in the Cloud Storage logs folder associated with the Cloud Composer environment, the logs can also be viewed in the <a href="https://cloud.google.com/composer/docs/how-to/accessing/airflow-web-interface">Airflow web interface</a> .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TuoyBdNihnDW5Wz76pZlw.png" /><figcaption>Airflow logs in the web interface</figcaption></figure><ul><li><strong>Streaming logs</strong>: a superset of the logs in Airflow, for example, uncategorised logs that Airflow pods generate and the Airflow scheduler logs, the full list can be found <a href="https://cloud.google.com/composer/docs/concepts/logs">here</a>. The streaming logs can be accessed using the Cloud Logging (logs explorer), or Cloud Monitoring. <a href="https://cloud.google.com/logging/docs/view/logs-explorer-interface">Logs explorer </a>can be filtered by properties such as log file and level, predefined label, task name, workflow, and execution date.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UetuJ__6eEmEHiQO-dm5Ew.png" /><figcaption>Airflow streaming logs on Logs Explorer</figcaption></figure><h3>Read and write logs to GCP</h3><p>To enable to read and write logs to Google Cloud storage, a few configurations are required in airflow.cfg:</p><pre><strong>[logging]</strong><br><em># Airflow can store logs remotely in AWS S3, Google Cloud Storage or Elastic Search.</em><br><em># Users must supply an Airflow connection id that provides access to the storage</em><br><em># location. If remote_logging is set to true, see UPDATING.md for additional</em><br><em># configuration requirements.</em></pre><pre>base_log_folder = /home/airflow/gcs/logs</pre><pre>remote_logging = True</pre><pre>remote_log_conn_id = google_cloud_default</pre><pre>remote_base_log_folder = gs://europe-west1-bucketname-bucket/logs</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MTT7xGSj5--Un_UE2heeWQ.png" /><figcaption>Google Cloud default connection defined in Airflow</figcaption></figure><p>And the service account and project ID are also set for GCP environment within Airflow variables</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_tsd0lYMOMwg07Z4CuOJg.png" /></figure><p>By default Application Default Credentials are used to obtain credentials. The connection package needs to be installed, such as pip install &#39;apache-airflow[google]&#39;</p><p>Make sure the service account assigned has read and write access to the Google Cloud Storage bucket defined above in remote_base_log_folder</p><h3>Two ways to add alerts</h3><p>The most straightforward way to add alerts is through Logs Explorer action create alert that creates logs-based alert policy. Such alerts can be sent to multiple channels including slack and the alerts are managed on Monitoring -&gt; Alerting -&gt; Policies panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3s9MN6fd22OSUvBdwJ2Dsw.png" /></figure><p>Airflow also has a built-in capability to send alerts on emails, but it can easily gets lost in the pile of other 1000 unread emails. So it is just easier to get alerts on the team channel such as via Slack</p><p>Each task in Airflow contains a parameter called on_failure_callback (of <a href="https://stackoverflow.com/questions/111234/what-is-a-callable-in-python">callable</a> type) to which you pass a function to be called when a task fails, that we could use to pass a function to send fail alerts to Slack.</p><pre>with DAG(</pre><pre>&quot;your_dag_name&quot;,</pre><pre>description=&quot;...&quot;,</pre><pre>default_args=ARGS,</pre><pre>schedule_interval=&quot;0 2 * * *&quot;,  # every day</pre><pre>on_failure_callback=slack_cb.send_fail_slack_alert,</pre><pre>) as dag:</pre><pre>    ...</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dda1a3231e56190c7c1024a3e1a47543/href">https://medium.com/media/dda1a3231e56190c7c1024a3e1a47543/href</a></iframe><p>In this way, an alert will be sent out each time when a DAG run failed as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wL6kKyQLb6utPeVqXNKdaA.png" /></figure><h3>Conclusion</h3><p>This article aims to summarise and show the logging and alerting methods we used in our projects for monitoring Airflow on the Google Cloud environment.</p><p>There are still many other ways to do so, and we also see some limitations with our current solutions, one big limitation is that the errors that happen outside the DAG run level are not captured in the on_failure_callback One possible way to tackle it is to add different levels of loggings and add more alert policies based on filter fields.</p><p>At the end, I would like to recommend a nice reference article which gives a overview of how logging working in Airflow</p><p><a href="https://www.astronomer.io/guides/logging/">Logging in Airflow - Airflow Guides</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b07246efc2c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy a Flask app to Azure — two ways using AKS and Azure Functions]]></title>
            <link>https://medium.com/@pennyqxr/deploy-a-flask-app-to-azure-two-ways-using-aks-and-azure-functions-6f8958e85329?source=rss-cfd77288e590------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f8958e85329</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-kubernetes-service]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Penny Qian]]></dc:creator>
            <pubDate>Tue, 14 Dec 2021 20:47:57 GMT</pubDate>
            <atom:updated>2021-12-14T20:47:57.902Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploy a Flask app to Azure — two ways using AKS and Azure Functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4cqdur_uklPqfa-v" /><figcaption>Photo by <a href="https://unsplash.com/@sapegin?utm_source=medium&amp;utm_medium=referral">Artem Sapegin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Azure Functions</h3><p><a href="https://docs.microsoft.com/en-us/azure/azure-functions/">Azure Functions</a> is <strong>a serverless (function as a service) solution</strong> that allows users to write less code and maintain less infrastructure. The deploying and maintaining servers part is provided by cloud infrastructure so that users can focus on the pieces of application code to run.</p><p>One great scenario to use Azure Functions is an <strong>event handler</strong>, for example, building a web API that responds to database changes. These code blocks of the web API are called “functions”. Different functions can run anytime you need to respond to critical events.</p><p>As Azure Functions is claimed to be “compute on-demand”, the scaling is automatically configured by cloud infrastructure.</p><h3><strong>Implementation with Azure Functions</strong></h3><p><strong>Flask Hello World example</strong></p><p>There are plenty of Flask hello world examples available online. For our Flask app, we want to achieve a minimum of the followings:</p><ul><li>Expose the app with a public URL</li><li>Can receive and react to HTTP requests</li></ul><p>To run the Flask application, one straightforward method is to use the Azure App Service CLI az webapp up, which deploys the zipped code to a new resource group and create an App Service accordingly. The Python code is running a Linux container(in default) in App Service using a built-in image. Ref. <a href="https://docs.microsoft.com/en-us/azure/app-service/quickstart-python?tabs=bash&amp;pivots=python-framework-flask">Azure doc</a> for detailed steps.</p><p><strong>Microservice design + Serverless framework</strong></p><p>Although Azure App Service provides a serverless framework to automatically containerize the Python app, it also decreases the customization for the microservice design, for example, network policy control for ports.</p><p>Gladly the Azure Functions also allows deployment resources as registered docker images. In our case, we can:</p><ol><li>Containerize the app (create a Dockerfile and build the image)</li><li>Register the built image on a container registry, for Dockerhub(<em>follow the steps on </em><a href="https://docs.docker.com/docker-hub/"><em>https://docs.docker.com/docker-hub/</em></a><em>) or Azure Container Registry</em></li></ol><p>3. Configure the container deployment settings to include the docker registry, this can be done by UI (see the screenshot below), or via a CI/CD pipeline, for example, using ACR and <a href="https://github.com/microsoft/azure-pipelines-tasks/blob/master/Tasks/AzureFunctionAppContainerV1/README.md">Azure Function App on Container Deploy</a> task to <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/targets/function-app-container?view=azure-devops&amp;tabs=yaml#deploy-with-the-azure-function-app-for-container-task">deploy with the azure function app for container task</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/0*HFhdAXsUzM-pzCBJ" /><figcaption>Source: <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/targets/function-app-container?view=azure-devops&amp;tabs=yaml">https://docs.microsoft.com/en-us/azure/devops/pipelines/targets/function-app-container?view=azure-devops&amp;tabs=yaml</a></figcaption></figure><h3>Azure AKS</h3><p>Microservices is an application design that is opposite to the monolith application design. With microservices, one application can be broken down into multiple smaller components and be developed and maintained separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*ai8ljj-15Sk8azTg.png" /><figcaption>source: <a href="https://aws.amazon.com/microservices/">https://aws.amazon.com/microservices/</a></figcaption></figure><p>Kubernetes, aka K8S, is a <strong>container orchestration system</strong> perfect for automating the management, scaling, and deployment of microservice applications. K8S is part of the Azure Kubernetes Service (AKS), together with an integrated continuous integration and continuous delivery (CI/CD) experience, and enterprise-grade security and governance.</p><h3>Implementation with Azure AKS</h3><p>The solution design diagram to expose our Flask app to external traffic is as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gmtuvx0VCRLB0mQZlVxvpA.png" /></figure><p>Several concepts inside this diagram:</p><ul><li><strong>Ingress</strong>, act as a proxy between a client requesting a resource and a server providing that resource. <a href="https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.22/#ingress-v1-networking-k8s-io">Ingress</a> exposes HTTP and HTTPS routes from outside the cluster to <a href="https://kubernetes.io/docs/concepts/services-networking/service/">services</a> within the cluster. Traffic routing is controlled by rules defined on the Ingress resource.</li><li><strong>Service</strong>, act as a load balancer, is an abstraction that defines a logical set of Pods and a policy by which to access them. A Service can map <em>any</em> incoming port to a targetPort.</li><li><strong>Pod</strong>, a group of containers that share resources like file systems, kernel namespaces and an IP address.</li></ul><p>To implement the above design diagram, we take the steps below:</p><ol><li><em>Deploy a Kubernetes service on Azure (this can be done via </em><a href="https://docs.microsoft.com/en-us/azure/aks/kubernetes-walkthrough-portal#create-an-aks-cluster"><em>Azure Portal</em></a><em> or Azure CLI)</em></li><li>Connect to the provisioned AKS</li><li>Create a deployment , service and ingress in YAML (as the code snipped showed below)</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09d784677d69e8a6c09878c811b41612/href">https://medium.com/media/09d784677d69e8a6c09878c811b41612/href</a></iframe><ul><li>when I create my aks cluster, I used --enable-addons http_application_routing argument, as below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RSVreDJTYo6NFJVSQswl6Q.png" /></figure><ul><li>on deployment , change the container image to your registered image on Docker hub or other registries with tags, also change the containerPort to your exposed port</li><li>on ingress , the host domain can be retracted via the following CLI command</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q__S9Zs0f5Nuv0NnBtv9ug.png" /></figure><ul><li>I also adopted the <a href="https://github.com/curtdept/aks_nodelocaldns/blob/main/nodelocaldns.yaml">nodecaldns</a> to resolve the <a href="https://github.com/Azure/AKS/issues/1492">AKS local DNS issue</a></li></ul><h3>In summary of AKS vs App Services</h3><ul><li>There is a steeper learning curve for AKS since Linux and Kubernetes specific terminology and concepts are required in order to perform the deployment</li><li>The Azure App Service provides a code-less way for running a function and maintenance.</li><li>AKS can provide most ‘utility’ type functions out of the box (e.g. route aggregation and certificates). In contrast, the user customization from Azure App Service is quite limited.</li><li>AKS Opens up the potential for Service Mesh architecture and offers infrastructure simplicity for an application ecosystem that contains many app service instances.</li></ul><h3>References:</h3><p><a href="https://levelup.gitconnected.com/moving-from-azure-app-services-to-azure-kubernetes-service-part-1-e489857c6440">https://levelup.gitconnected.com/moving-from-azure-app-services-to-azure-kubernetes-service-part-1-e489857c6440</a></p><p><a href="https://www.bmc.com/blogs/kubernetes-port-targetport-nodeport/">Using Kubernetes Port, TargetPort, and NodePort</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiYSZAn36Z24%3Fstart%3D363%26feature%3Doembed%26start%3D363&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiYSZAn36Z24&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiYSZAn36Z24%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4ff3970d9cef7707d6cff52f997f877/href">https://medium.com/media/a4ff3970d9cef7707d6cff52f997f877/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f8958e85329" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitor Machine Learning applications with Azure Application Insights]]></title>
            <link>https://medium.com/@pennyqxr/monitor-machine-learning-applications-with-azure-application-insights-97eeee97e3f1?source=rss-cfd77288e590------2</link>
            <guid isPermaLink="false">https://medium.com/p/97eeee97e3f1</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[alerts]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Penny Qian]]></dc:creator>
            <pubDate>Tue, 02 Nov 2021 12:31:44 GMT</pubDate>
            <atom:updated>2021-11-02T12:31:44.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yL0RVqAukO6Htjqw" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://docs.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview">Application Insights</a> is a feature of <a href="https://azure.microsoft.com/en-us/services/monitor/">Azure Monitor</a>, it is an extensible Application Performance Management (APM) service for developers and DevOps professionals.</p><p>For this article, we will walk through an Python example, which logs customized machine learning metrics into the Application Insights, and query through Kusto and set alerts.</p><h3>Solution</h3><p>To collect the performance data regarding our machine learning applicaiton, we used <a href="https://github.com/census-instrumentation/opencensus-python">OpenCensus for Python</a>: a library that allows users to collect application metrics and distributed traces, and transfer these collected data to a backend of user’s choice in real time.</p><p>There are also other options to add metric instrumentation into applications: Monitoring API (e.g. Google StackDriver REST API), Prometheus (open-source), and OpenCensus. In this article we will adopt OpenCensus for implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*DHSPRS8DQJBUDoP9d-vvBQ.png" /></figure><p>In our case, the collected data/metrics can be used by data scientists and machine learning engineers to understand the performance of the models and applications. The backend we used here is the Azure Application Insights, which provides plenty of methods to <a href="https://docs.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview#where-do-i-see-my-telemetry">explore with the telemetry data</a>.</p><h3>Implementation</h3><p><strong>Pre-queries</strong></p><ol><li>Install OpenCensus packages</li></ol><pre>pip install opencensus-ext-azure<br>pip install opencensus</pre><p>2. Extract the instrumentation key and endpoints of the Application Insights that is going to be used (it lies on the overview page of the Application Insights resource page). The key and endpoints will be used to set up the connection to the Application Insights. Because there is no authentication for users who hold the key and endpoints, means that anyone with the key and endpoints can write to the Application Insights. So it is recommended to store it into secrets management tool (e.g. Azure KeyVault) and extract from there.</p><p><strong>Python example</strong></p><p>We present a Python example below. Execute this script once, and one trace will be sent to the Application Insights.</p><p>This example contains several key steps below:</p><ul><li>set up the azure handler connection with given instrumentation key and ingestion endpoint</li><li>tag the logs to be received so it can be queried using tags</li><li>configure the azure handler, set log formatter and add telemetry processor</li><li>initiate Python logger, let it be handled by the azure handler we defined above</li><li>log something</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/579959781fe1578cf4c91846bc09f530/href">https://medium.com/media/579959781fe1578cf4c91846bc09f530/href</a></iframe><p><strong>Query the metrics</strong></p><p>Metrics in Application Insights are done via <a href="https://docs.microsoft.com/en-us/azure/data-explorer/kusto/query/">Kusto query</a>: a read-only SQL like request to process data and return results. We tagged our custom metrics as <em>custom_dimensions</em> so we can easily extract using the same tag in the query, as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXoyOCnnJM6ibRYRF6UZvA.png" /></figure><p><strong>Use the traces</strong></p><p>The traces can be used in multiple ways, for example, create an alert based on the metrics to notify the specific action group when thresholds of metrics are reached. This do involve extra cost.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpHcbhtabQn4dwY7_RyiMQ.png" /></figure><h3>In Wrap</h3><ul><li>Application Insights is a built-in feature from Azure, for applications adopting Azure resources and running on Azure, Application Insights provides an easy way to monitor and measure.</li><li>The configurations (add alerts) are mainly using UI instead of configuration as code, which is error prone and adds more effort for application operation and maintenance.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97eeee97e3f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Pipeline Tip (1): auto-sync repositories between Azure projects]]></title>
            <link>https://medium.com/@pennyqxr/azure-pipeline-tip-1-auto-sync-repositories-between-azure-projects-a078262fe0c9?source=rss-cfd77288e590------2</link>
            <guid isPermaLink="false">https://medium.com/p/a078262fe0c9</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[sync]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Penny Qian]]></dc:creator>
            <pubDate>Thu, 07 Oct 2021 09:10:00 GMT</pubDate>
            <atom:updated>2021-10-07T09:10:00.946Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sGdgwZONnJU1qjK4" /><figcaption>Photo by <a href="https://unsplash.com/@by_syeoni?utm_source=medium&amp;utm_medium=referral">Suhyeon Choi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Scenario Description</strong></h3><p>In a big organization, the IT permissions on different projects/teams can be different. Sometimes the repository has to be run/operationalized under one team’s space, while the development happens under another team’s space. In this case, the frequent synchronization between repositories in two project/team spaces is required.</p><p>One solution we proposed in this article is to use the Azure Pipeline to perform an auto-sync when new commits are made to the repositories.</p><h3><strong>Implementation</strong></h3><p>If you are new to Azure Pipelines, you can check the <a href="https://docs.microsoft.com/en-us/azure/devops/pipelines/get-started/what-is-azure-pipelines?view=azure-devops">official documents/tutorials</a>. We implement with the following YAML definitions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ac86b14e639c458a0acbc9421bcdae7/href">https://medium.com/media/3ac86b14e639c458a0acbc9421bcdae7/href</a></iframe><p>Key features in this yaml definition:</p><ul><li>variables we firstly defined the values that are going to be used in the bash commands</li><li>git config --global to get git working properly, we need a few global configurations. Because Azure DevOps require the authorization way to be basic, by default the git credential authority is set to be Auto</li><li>PAT personal access token is used as the password. We used it here to configure Git with Azure DevOps. The PAT value is stored as a Pipeline variable and it has to be <a href="https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&amp;tabs=preview-page#use-a-pat">Base64-encoded with HTTP basic authentication</a>.</li><li>git clone --bare <a href="https://git-scm.com/docs/git-clone">Make a <strong>bare</strong> Git repository</a>. That is, instead of creating &lt;directory&gt; and placing the administrative files in &lt;directory&gt;/.git, make the &lt;directory&gt; itself the $GIT_DIR.</li><li>git push --mirror Instead of naming each ref to push, specifies that all refs under refs/ (which includes but is not limited to refs/heads/, refs/remotes/, and refs/tags/) <a href="https://git-scm.com/docs/git-push">be mirrored to the remote repository</a>. Newly created local refs will be pushed to the remote end, locally updated refs will be force updated on the remote end, and deleted refs will be removed from the remote end.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a078262fe0c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to train and track ensemble models with MLflow]]></title>
            <link>https://medium.com/@pennyqxr/how-to-train-and-track-ensemble-models-with-mlflow-a1d2695e784b?source=rss-cfd77288e590------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1d2695e784b</guid>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Penny Qian]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 10:01:16 GMT</pubDate>
            <atom:updated>2021-09-28T10:01:16.903Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SgOm_D7kcCyKHj7C" /><figcaption>Photo by <a href="https://unsplash.com/@gwundrig?utm_source=medium&amp;utm_medium=referral">Manuel Nägeli</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What are ensemble models?</h3><p><a href="https://towardsdatascience.com/ensemble-models-5a62d4f4cb0c">Ensemble modeling</a> is a process where multiple diverse models are created to predict an outcome, either by using many different modeling algorithms or using different training datasets. The ensemble model then aggregates the prediction of each base model and results in one final prediction for the unseen data.</p><p>The motivation for using ensemble models is to reduce the generalization error of the prediction. As long as the base models are diverse and <em>independent</em>, the prediction error of the model decreases when the ensemble approach is used. The approach seeks the wisdom of crowds in making a prediction.</p><p>Even though the ensemble model has multiple base models within the model, it acts and performs as a single model. Most of the practical data mining solutions utilize ensemble modeling techniques. (ref. <a href="https://www.sciencedirect.com/topics/computer-science/ensemble-modeling">https://www.sciencedirect.com/topics/computer-science/ensemble-modeling</a>)</p><p>Common types of ensembles include:</p><ul><li><strong>Boosting</strong>: involves incrementally building an ensemble by training each new model instance to emphasize the training instances that previous models misclassified.</li><li><strong>Bootstrap aggregating</strong> (often abbreviated as bagging): having each model in the ensemble vote with equal weight. As an example, the random forest algorithm combines random decision trees with bagging to achieve very high classification accuracy.</li><li><strong>Stacking</strong>: training a learning algorithm to combine the predictions of several other learning algorithms. An example image is as below. (ref. <a href="https://en.wikipedia.org/wiki/Ensemble_learning">https://en.wikipedia.org/wiki/Ensemble_learning</a>)In this article, we only cover the stacking scenario for implementation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3uusFIv0lUwBz5F5.png" /><figcaption>Image source: <a href="https://towardsdatascience.com/ensemble-models-for-classification-d443ebed7efe">https://towardsdatascience.com/ensemble-models-for-classification-d443ebed7efe</a></figcaption></figure><h3>Implementation with MLflow</h3><p><a href="https://www.mlflow.org/docs/latest/index.html">MLflow</a> is an open-source platform for managing the end-to-end machine learning lifecycle. <em>MLflow Models</em> manages and deploys models from a variety of ML libraries to a variety of model serving and inference platforms.</p><p>MLflow does not naturally support ensemble models, but with iteration, we can enable it with Python or other programming languages.</p><p><strong>Model training</strong></p><p>Different from single model training, for ensemble models, we initiate a model pool to store candidate models identified by a unique model_key . Each mlflow run is a complete loop over all the model_keys.</p><p>Within the run, a forloop goes over all model_keys and train the model with the training dataset. mlflow sklearnn save_model will automatically save the metadata as well as trained model into a folder, similar to below:</p><pre># Directory written by mlflow.sklearn.save_model(model, &quot;my_model&quot;)<br>my_model/<br>├── MLmodel<br>├── model.pkl<br>├── conda.yaml<br>└── requirements.txt</pre><p>Besides, for the final decision-making model to pick the best model from the pool, we separately aggregate the model result in results_dict and save them as <a href="https://docs.python.org/3/library/pickle.html">pickle</a> objects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1562363947e24ec4a01a0dd5755ff8c/href">https://medium.com/media/e1562363947e24ec4a01a0dd5755ff8c/href</a></iframe><p>The model saved by MLflow can be tracked using the <a href="https://www.mlflow.org/docs/latest/tracking.html#tracking">tracking server UI</a>, as shown in the screenshot below. Each trained model in the model pool comes with a MLflow default save format folder and result/pickle file. Each of these files can be downloaded on the UI for further exploration and analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*oF3j6e8V-V3LqmTxfNKYKA.png" /></figure><p><strong>Model scoring/prediction</strong></p><p>The model scoring/prediction part is similar to the training part. We each each trained model using the run_id and model_key.</p><p>We then can apply predictions to the fetched model, get the predictions of multiple models into a list, and from where we can select the best model and prediction result for decision making.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d747a12801219dd35c3d6e4fdcc19b48/href">https://medium.com/media/d747a12801219dd35c3d6e4fdcc19b48/href</a></iframe><p>The model run_id can be passed as an argument when defining endpoint within MLproject file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9ff61d299e1ccbda70b94f65e8856b0/href">https://medium.com/media/e9ff61d299e1ccbda70b94f65e8856b0/href</a></iframe><h3><strong>Wrap-up</strong></h3><ul><li>In this article, we went through the concepts of ensemble models, and different types of them.</li><li>We introduced an Python implementation for the stacking scenario using MLflow features.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1d2695e784b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How save and load FastText model in MLflow format]]></title>
            <link>https://medium.com/@pennyqxr/how-save-and-load-fasttext-model-in-mlflow-format-37e4d6017bf0?source=rss-cfd77288e590------2</link>
            <guid isPermaLink="false">https://medium.com/p/37e4d6017bf0</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[fasttext]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Penny Qian]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 13:12:42 GMT</pubDate>
            <atom:updated>2021-11-02T12:39:31.467Z</atom:updated>
            <content:encoded><![CDATA[<h3>MLflow Custom Pyfunc for Saving and Loading Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b9Qw4pjGjoUgPGak" /><figcaption>Photo by <a href="https://unsplash.com/@matthewhenry?utm_source=medium&amp;utm_medium=referral">Matthew Henry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Concepts of MLflow</strong></h3><blockquote><a href="https://mlflow.org/">MLflow </a>is an open source platform to streamline machine learning development, including tracking experiments, packaging code into reproducible runs, and sharing and deploying models.</blockquote><p>MLflow currently provides four components to help manage the ML workflow, including:</p><ul><li><strong>MLflow Models</strong>: are a standard format for packaging machine learning models that can be used in a variety of downstream tools. For example, a TensorFlow model can be loaded as a TensorFlow DAG, or as a Python function to apply to input data. We will deep dive more into this component later.</li><li><strong>MLflow Projects:</strong> are a standard format for packaging reusable data science code. For example, <a href="https://github.com/mlflow/mlflow-example">a MLflow example</a> can be structured in a folder that includes main code and dependency file.</li><li><strong>MLflow Registry: </strong>offers a centralized model store, set of APIs, and UI, to collaboratively manage the full lifecycle of an MLflow Model. It provides model lineage (which MLflow experiment and run produced the model), model versioning, stage transitions (for example from staging to production or archiving), and annotations.</li><li><strong>MLflow Tracking: </strong>is an API and UI for logging parameters, code versions, metrics, and artifacts when running your machine learning code and for later visualizing the results. It can run either locally or remotely.</li></ul><h3>Beyond Built-in Model Flavors</h3><p>As described in the MLflow Models part, each Model is saved as a directory containing arbitrary files and a descriptor file that lists several <em>“flavors”</em> (a convention that deployment tools can use to understand the model) the model can be used in.</p><p>By default, MLfow provides several standard flavors that can be directly used in your applications, for example, <a href="https://www.mlflow.org/docs/latest/models.html#pytorch-pytorch">PyTorch</a>, <a href="https://www.mlflow.org/docs/latest/models.html#xgboost-xgboost">XGBoost</a>. Which means, saving PyTorch models in MLflow format can be done via <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pytorch.html#mlflow.pytorch.save_model">mlflow.pytorch.save_model()</a> and <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pytorch.html#mlflow.pytorch.log_model">mlflow.pytorch.log_model()</a> methods; and loading MLflow Models can be done simply via <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pytorch.html#mlflow.pytorch.load_model">mlflow.pytorch.load_model()</a> method. A full supported list can be checked from this <a href="https://www.mlflow.org/docs/latest/models.html#built-in-model-flavors">link</a>.</p><p>However, there are still tools that are not yet supported by MLflow, for example, FastText. To cope with this request, MLflow also supports a generic filesystem <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#pyfunc-filesystem-format">model format</a> for Python models and provides utilities for saving and loading models to and from this format: Python Function.</p><p>Python Function model flavor is self-contained in the sense that it includes all the information necessary to load and use a model. Dependencies are stored either directly with the model or referenced via Conda environment.</p><h3>Custom Python Models</h3><p>The <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#module-mlflow.pyfunc">mlflow.pyfunc</a> module provides <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#mlflow.pyfunc.save_model">save_model()</a> and <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#mlflow.pyfunc.log_model">log_model()</a> utilities for creating MLflow Models with the python_function flavor that contains user-specified code and <em>artifact</em> (file) dependencies. These artifact dependencies may include serialized models produced by any Python ML library.</p><p>Because these custom models contain the python_function flavor, they can be deployed to any of MLflow’s supported production environments, such as SageMaker, AzureML, or local REST endpoints.</p><p><strong>Construct and return a pyfunc-compatible model wrapper</strong></p><p>Given a set of artifact URIs, <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#mlflow.pyfunc.save_model">save_model()</a> and <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#mlflow.pyfunc.log_model">log_model()</a> can automatically download artifacts from their URIs and create an MLflow model directory.</p><p>In this case, you must define a Python class which inherits from <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#mlflow.pyfunc.PythonModel">PythonModel</a>, defining predict() and, optionally, load_context()</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4748e09729060c8ffbd91e9df662e71/href">https://medium.com/media/a4748e09729060c8ffbd91e9df662e71/href</a></iframe><p><strong>To save the model</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e93d55b65fb9f84030a3989f9f3b731/href">https://medium.com/media/9e93d55b65fb9f84030a3989f9f3b731/href</a></iframe><p>We used mlflow.pyfunc.log_model to save the FastText trained model (in binary format) to be understood by MLflow:</p><ul><li><strong>artifact_path</strong>: The run-relative artifact path to which to log the Python model.</li><li><strong>python_model</strong>: Represents a generic Python model that evaluates inputs and produces API-compatible outputs. Here we refer to the wrapper defined above.</li><li><strong>code_path</strong>: A list of local filesystem paths to Python file dependencies (or directories containing file dependencies).</li><li><strong>artifacts</strong>: A dictionary containing &lt;name, artifact_uri&gt; entries. python_model can reference these resolved entries as the artifacts property of the context parameter in <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#mlflow.pyfunc.PythonModel.load_context">PythonModel.load_context()</a> and <a href="https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html#mlflow.pyfunc.PythonModel.predict">PythonModel.predict()</a>.</li></ul><p><strong>To load the model</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/833a2deef07016d3cd2a368cfa68d9a8/href">https://medium.com/media/833a2deef07016d3cd2a368cfa68d9a8/href</a></iframe><p><strong>Potential improvement</strong></p><p>The predict function defined in the FastTextWrapper is not a real prediction function, it is only used to return the saved model. This can be improved by implementing a real predict function that takes model input and returns prediction results.</p><h3><strong>Wrap-up:</strong></h3><ul><li>we went through the key concepts of MLflow in this article</li><li>we introduced a solution to wrap FastText model in MLflow Models format which are beyond the built-in flavors</li><li>We discussed the potential improvement of this solution</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37e4d6017bf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airflow Hello-World Tutorial: Build Your First Dag Locally]]></title>
            <link>https://medium.com/@pennyqxr/build-your-first-end-2-end-dag-in-airflow-locally-d4d9dba2d542?source=rss-cfd77288e590------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4d9dba2d542</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[orchestration]]></category>
            <dc:creator><![CDATA[Penny Qian]]></dc:creator>
            <pubDate>Thu, 05 Aug 2021 08:56:35 GMT</pubDate>
            <atom:updated>2021-11-02T12:40:51.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QXK00vMil4ekYO5V" /><figcaption>Photo by <a href="https://unsplash.com/@rodlong?utm_source=medium&amp;utm_medium=referral">Rod Long</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><em>“Airflow is a platform to programmatically author, schedule and monitor workflows.”</em></blockquote><p>So Airflow serves as a role to automate scripts, with the power to visualize the progress and status. Sounds like a good solution for multiple and complex tasks, also save time and effort from engineers.</p><p>How does Airflow achieve it? Airflow organizes workflows as DAGs.</p><blockquote><a href="https://airflow.apache.org/docs/stable/concepts.html"><strong><em>A DAG is a collection of all the tasks you want to run, organized in a way that reflects their relationships and dependencies.</em></strong></a></blockquote><p>In a simple word, the tasks are connected with directed lines, so their relationships and dependencies can be visualized.</p><p>To start with building your first DAG, requires are to get the Airflow environment ready.</p><p>Airflow official site provides the instruction script for automatic installation on <a href="https://airflow.apache.org/docs/apache-airflow/stable/installation.html">https://airflow.apache.org/docs/apache-airflow/stable/installation.html</a></p><p>Once you downloaded Airflow successfully, go to your airflow.cfg and change the pipeline folder path, this is where the Dag definitions will be used by Airflow, and there is the folder where you start write your first DAG.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*u0YQZuowUiHTYHxWIgqy2Q.png" /></figure><ol><li><strong>Import packages</strong></li></ol><p>Airflow is Python-based, the pipelines are defined in Python. To use Airflow, several packages need to be imported first.</p><pre>from airflow import DAG </pre><pre>from airflow.operators.python import PythonOperator, BranchPythonOperator</pre><pre>from airflow.operators.bash import BashOperator</pre><ul><li>The Dag object is used to instantiate a DAG.</li><li>The Operators are used to operate the tasks.</li><li>PythonOperator: execute a Python callable. (similar for BashOperator to execute a Bash command)</li><li>BranchPythonOperator: allows a workflow to “branch” .</li><li>Airflow also provides a collection of example dags and defined operators on <a href="https://github.com/github/incubator-airflow/tree/gh-1.10.9/airflow/example_dags">https://github.com/github/incubator-airflow/tree/gh-1.10.9/airflow/example_dags</a></li></ul><p><strong>2. Define Dag</strong></p><p>A DAG is defined in a Python script, which represents the DAGs structure (tasks and their dependencies) as code. The DAG name, run start date, schedule interval can all be defined when initiating a DAG instance.</p><pre>with DAG(“stock_dag”, start_date=datetime(2021, 1, 1), description=’An e2e stock filter flow’, schedule_interval=”@daily”, catchup=False) as dag:</pre><pre>    task1<br>    task2<br>    …<br>    dependency</pre><p><strong>3. Write tasks</strong></p><p>A Task defines a unit of work within a DAG; it is represented as a node in the DAG graph, and it is written in Python.</p><p>Each task is an implementation of an Operator, there are different types of operators defined in Airflow. And customized operators can also be made by users.</p><p>For our stock filter flow, our first task is to download stocks data. Our download code is using yfinance.</p><pre><strong>def</strong> download_yf():<br>  import yfinance as yf<br>  data = yf.download(“SPY TSLA”, start=”2020–01–01&quot;, end=”2021–01– 01&quot;, group=”tickers”)<br>  return data</pre><p>For the task download_yf we specify the task_id, and tells it which Python function to call.</p><p><strong>data returned here will defaultly create a XCom(cross-communication) and be able to be passed to other tasks.</strong> XCom allows to exchange messages or small amount of data between tasks, there is one argument that ALL OPERATORS SHARE ( BashOperator, PythonOperator etc. ) which is do_xcom_push set to True.</p><p>Then we define a PythonOperator to execute download_yf as task download_yf as below:</p><pre>download_yf = PythonOperator(<br>  task_id=”download_yf”,<br>  python_callable=download_yf<br>)</pre><p>Similar steps occur for defining other tasks choose_stock , spy , and tsla</p><p><strong>4. Define dependencies</strong></p><p><em>Dependencies are logic between tasks, the “directed” in directed acyclic graph (DAG). “</em>Dependencies are one of Airflow’s most powerful and popular features — they allow for previously long, brittle jobs to be broken down into granular parts that are safer, more modular, and reusable.<em>”</em></p><p><em>The logic can be set in three ways:</em></p><p>d1.set_downstream(d2)</p><p>d1.set_upstream(d2)</p><p>d1 &gt;&gt; d2</p><p>All these three express the same dependency meaning, with the best practice as long as it is written consistently in one DAG.</p><p>In our example, we can do:</p><pre>download_yf &gt;&gt; choose_stock &gt;&gt; [spy, tsla]</pre><p>Recall that we used operator instances here for building the dependency, while the type of operator does not matter here, tasks are identified by their task_id and associated DAG object - not by the type of operator.</p><p><strong>5. Trigger the DAG</strong></p><p>So far we have the full DAG ready, the full DAG can be extracted from <a href="https://gist.github.com/PennyQ/e7047f5aed188b2b538724a03beacd61">https://gist.github.com/PennyQ/e7047f5aed188b2b538724a03beacd61</a> Now we are going to schedule/trigger it using local Airflow.</p><p>To start the airflow locally, you can simply start the webserver using airflow webserver --port 8080 and start the airflow scheduler airflow scheduler -D (-D is daemon mode) The initiation takes about 1 min, and once the server is successfully initiated, the Airflow UI can be accessed from localhost:8080</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-dkRTJwTNAmdHdH20A-uA.png" /></figure><p>To load the new DAG to Airflow or update an existing one, use command airflow db init The DAG will then show up in the above DAGs list.</p><p>After the workflow is triggered, the status will show up on the views. For example, the graph view, which allows to visualize your DAG’s dependencies and their current status for a specific run. A successful run of our example can be like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*lW2fG9H3OmJtC5WwWkneYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*E5cHIJIqGYUz9UMSWS2rmw.png" /></figure><p>For more types of UI views, refer to <a href="https://airflow.apache.org/docs/apache-airflow/stable/ui.html">https://airflow.apache.org/docs/apache-airflow/stable/ui.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4d9dba2d542" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>