<?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[CodeShake - Medium]]></title>
        <description><![CDATA[Learnings and insights from SFEIR community. - Medium]]></description>
        <link>https://medium.com/codeshake?source=rss----10099c88703e---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>CodeShake - Medium</title>
            <link>https://medium.com/codeshake?source=rss----10099c88703e---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 07:25:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/codeshake" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Protecting Sensitive Data: Securing Data Pipelines on Google Cloud (part 3)]]></title>
            <link>https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-3-cb0190cf717?source=rss----10099c88703e---4</link>
            <guid isPermaLink="false">https://medium.com/p/cb0190cf717</guid>
            <category><![CDATA[opsec]]></category>
            <category><![CDATA[vpc-service-control]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Jérôme NAHELOU]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 08:36:05 GMT</pubDate>
            <atom:updated>2023-03-08T08:36:05.690Z</atom:updated>
            <content:encoded><![CDATA[<p>This series of stories will help you to design and secure workload on GCP with different levels of protection.</p><ul><li><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-1-14dda7e7163c">Part 1: Authentication &amp; Authorization</a></li><li><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-2-435bb0aba75f">Part 2: VPC Service Control, Private Service Connect</a></li><li><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-3-cb0190cf717">Part 3: Firewall rules, Firewall policies and Cloud Armor</a></li></ul><p>The last article of this story consists to add:<br>- Ingress traffic filtering at level 7 using Cloud Armor<br>- Egress traffic filtering at level 4 using firewall rules or firewall policies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YeFAklQk_2T3fjkvjdv4Pg.png" /></figure><h3>Incoming traffic</h3><p>VPC Service control provides effective protection against data exfiltration but vulnerabilities can be stored in applications themselves. Cloud Armor provides a web application firewall at load balancer level.</p><p>For my use case, I added my Cloud Run in a <a href="https://cloud.google.com/load-balancing/docs/negs/serverless-neg-concepts">Serverless Network Endpoint Group</a>. This feature allows you to add load balancing features (DDOS protection, WAF, CDN, IAP, etc.) on serverless services like Cloud Run, Cloud Functions or AppEngine.<br>Once the NEG is created, you can use it to configure backend service in your load balancer.</p><p>I’ve attached a basic Cloud Armor Security Policy with preconfigured WAF rules and a rule to allow traffic only from home.</p><p>Don’t forget to switch Cloud Run ingress traffic from <strong>Internal</strong> to <strong>Internal and Load balancing</strong>.</p><h3>Outgoing traffic</h3><p>First create a Private Service Connect to create a private IP that you can use to join Google APIs.</p><p><a href="https://cloud.google.com/vpc/docs/private-service-connect#benefits-apis">Private Service Connect | VPC | Google Cloud</a></p><p>Then use firewall rules to deny all outgoing traffic except traffic to PSC. The serverless connector is a set of instances managed by Google but deployed on the network. Instances are subject to firewall rules using the special tag <strong>vpc-connector</strong> or <strong>vpc-connector-REGION-CONNECTOR_NAME.<br></strong>As described <a href="https://cloud.google.com/vpc/docs/configure-serverless-vpc-access#restrict-by-egress">in the Google documentation</a>, rules lower than 1000 (higher priority) can be used to limit access from the connector.</p><p>Now only outgoing traffic is limited to the PSC IP.</p><h3>Conclusion</h3><p>I hope this architecture pattern will help you to improve the security of your cloud environments. Quick wins you can make:</p><p>When designing the project:</p><ul><li>Consider complexity and costs versus risk by having a solid data categorization that helps you choose the best architecture.</li><li>Avoid service account keys to deploy terraform code, consider workload identity federation</li><li>Create one service account per service and assign appropriate permissions</li><li>Identify network flows to configure ingress and egress traffic</li><li>Leveraging encryption (not covered in this story)</li></ul><p>When deploying the project:</p><ul><li>Create Cloud Logging alerts based on VPC SC or Cloud Armor entries</li><li>Monitor infrastructure changes (policies, firewall rules, IAM, or others configuration updates)</li><li>Limit administrators access to resources (enforce Infra as Code + review process)</li><li>Use <a href="https://cloud.google.com/security-command-center/docs/how-to-remediate-security-health-analytics-findings">Google Cloud Security Health Analytics</a> to detect misconfigurations</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb0190cf717" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-3-cb0190cf717">Protecting Sensitive Data: Securing Data Pipelines on Google Cloud (part 3)</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protecting Sensitive Data: Securing Data Pipelines on Google Cloud (part 2)]]></title>
            <link>https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-2-435bb0aba75f?source=rss----10099c88703e---4</link>
            <guid isPermaLink="false">https://medium.com/p/435bb0aba75f</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[vpc-service-control]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[opsec]]></category>
            <dc:creator><![CDATA[Jérôme NAHELOU]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 08:35:47 GMT</pubDate>
            <atom:updated>2023-03-08T08:35:47.866Z</atom:updated>
            <content:encoded><![CDATA[<p>This series of stories will help you to design and secure workload on GCP with different levels of protection.</p><ul><li><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-1-14dda7e7163c">Part 1: Authentication &amp; Authorization</a></li><li><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-2-435bb0aba75f">Part 2: VPC Service Control, Private Service Connect</a></li><li><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-3-cb0190cf717">Part 3: Firewall rules, Firewall policies and Cloud Armor</a></li></ul><p>A well-known security concept called security-in-depth or defense-in-depth involves adding multiple layers of security. In addition to authentication, VPC Service Control protects Google Cloud services for a set of projects (called perimeter). You will be able to control incoming and outgoing traffic for most Google Services based on user context (location, device, IP address, etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vn01l8iy01uWSPrG.png" /></figure><p>Lets dive into the classic use case we saw in part 1.</p><h3>VPC Service Control</h3><p>IAM provides authentication and authorization, but anyone with leaked service account keys can abuse it. To protect service account key usage only from trust devices or locations, VPC SC will help.</p><p><em>Keep in mind that VPC service control introduces complexity and should be considered as early as possible in the design process.</em></p><p>The concepts behind VPC Service controls are simple: control ingress and egress of managed services within a single perimeter (you cannot attach a project to multiple perimeters).</p><ol><li>Create access level (optional): rules to include out of scope devices in the perimeter (IP, Users, Devices, etc.)</li><li>Create a perimeter</li><li>Select projects within the perimeter</li><li>Select Google Services you want to protect</li><li>Set ingress rules</li><li>Set egress rules</li></ol><h3>Theory versus Practice</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*ODubdP-Lut0euu2LFmamqw.png" /></figure><p>A VPC SC Perimeter now includes my GCP project. I added restrictions to Cloud Run, Pub/Sub and Datastore.</p><p>Cloud Run services have been switched to Internal ingress only, a GCP feature to only accept network traffic from my project or project within the perimeter (see <a href="https://cloud.google.com/run/docs/securing/ingress">https://cloud.google.com/run/docs/securing/ingress</a>).</p><p>At this stage, even if my personal user is allowed to invoke the cloud run service, the VPC service control denies requests from outside.</p><pre>(cloud shell) $ curl -v -H &quot;Authorization: Bearer $(gcloud auth print-identity-token)&quot; https://endpoint.a.run.app/submit<br>&lt;html&gt;&lt;head&gt;<br>&lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html;charset=utf-8&quot;&gt;<br>&lt;title&gt;403 Forbidden&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body text=#000000 bgcolor=#ffffff&gt;<br>&lt;h1&gt;Error: Forbidden&lt;/h1&gt;<br>&lt;h2&gt;Access is forbidden.&lt;/h2&gt;<br>&lt;h2&gt;&lt;/h2&gt;<br>&lt;/body&gt;&lt;/html&gt;</pre><p>You can easily find the cloud logging entry:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*R2GXtGmYSae82LAVKKe3zw.png" /></figure><p>Without ingress rules, front and back cannot be used. Let’s add an ingress rule to allow all sources within my project to use protected services.<br><em>Note: Push subscription does not support custom domains (</em><a href="https://cloud.google.com/pubsub/docs/push#push_subscription_and"><em>https://cloud.google.com/pubsub/docs/push#push_subscription_and</em></a><em>)</em></p><pre>Ingress Rule 1<br>From:<br>  Identities: ANY_IDENTITY<br>  Source &gt; Projects = iac-jnu-arf<br>To:<br>  Projects = All projects<br>  Services = All services</pre><p>I also set an Access Level with:<br>- my public IPv4 address to invoke the front service from my laptop<br>- my IPv6 address to use Cloud console from my browser</p><p>The same curl command now works as expected, my house is now in the perimeter (it may take a few seconds to take effect).</p><p><strong>But cloud run is still not able to use managed services (here Pub/Sub and Datastore).</strong></p><p>RTFM hits me… <a href="https://cloud.google.com/run/docs/securing/using-vpc-service-controls#deploy-compliant-services">https://cloud.google.com/run/docs/securing/using-vpc-service-controls#deploy-compliant-services</a></p><p>To be considered in the VPC SC perimeter, Cloud run egress traffic must pass through a VPC in the perimeter. That’s why I have:<br>- Added one connector<br>- Forced traffic through the connector<br>- Enabled private google access on the connector subnet<br>- Replaced *.googleapis.com with restricted.googleapis.com</p><p>And now, the messages are saved successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*2NhEPnvyUYgl9TnWP38cKA.png" /></figure><h4>Pros:</h4><ul><li>Fine ingress and egress control for managed services.</li><li>Dry-run mode</li><li>Native Cloud Logging support</li></ul><h4>Cons:</h4><ul><li>Introduce complexity.</li><li>The serverless connector is not serverless…</li><li>Advanced access level functionalities are limited without BeyondCorp Enterprise premium.</li><li>Configuration only at organization level</li></ul><p><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-3-cb0190cf717">In the next part</a>, we will see how to filter network traffic using Cloud Armor and Firewall rules/policies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=435bb0aba75f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-2-435bb0aba75f">Protecting Sensitive Data: Securing Data Pipelines on Google Cloud (part 2)</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protecting Sensitive Data: Securing Data Pipelines on Google Cloud (part 1)]]></title>
            <link>https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-1-14dda7e7163c?source=rss----10099c88703e---4</link>
            <guid isPermaLink="false">https://medium.com/p/14dda7e7163c</guid>
            <category><![CDATA[cloudrun]]></category>
            <category><![CDATA[opsec]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[vpc-service-control]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Jérôme NAHELOU]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 08:35:32 GMT</pubDate>
            <atom:updated>2023-03-08T09:17:37.822Z</atom:updated>
            <content:encoded><![CDATA[<p>This series of stories will help you to design and secure workload on GCP with different levels of protection.</p><ul><li><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-1-14dda7e7163c">Part 1: Authentication &amp; Authorization</a></li><li><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-2-435bb0aba75f">Part 2: VPC Service Control, Private Service Connect</a></li><li><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-3-cb0190cf717">Part 3: Firewall rules, Firewall policies and Cloud Armor</a></li></ul><p>For this series, I choose a simple architecture within one GCP project composed by:</p><ul><li>A front application hosted on Cloud Run</li><li>A Pub/Sub topic with a Push Subscription to the backend</li><li>A backend layer composed by a storage service hosted on cloud run and a datastore table</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*8xpoqS6w-o1K_MWwFGYU9Q.png" /></figure><p>Most of the code can be found on GitHub.</p><p><a href="https://github.com/jnahelou/medium-14dda7e7163c">GitHub - jnahelou/medium-14dda7e7163c</a></p><h3>Authentication within Google Cloud</h3><p>First of all, a good identity and access management is the top priority to protect sensitive data.</p><p>If you are running on GCP, you can access to an ephemeral identity or access token using metadata service:</p><pre>curl -H &quot;Metadata-Flavor: Google&quot; \<br> &quot;http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=AUDIENCE&quot;<br>curl -H &quot;Metadata-Flavor: Google&quot; \<br> &quot;http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token&quot; </pre><p>Most of Google libraries automatically obtain identity from the metadata service and the only thing you need is set the good level a privileges for services account.</p><p>The identity provided by the metadata server is inherited from the Service Account used by the resource. <br>Resources like Cloud Run accept a user service account that helps you to assign an identity for each part of the application and then define the good level of permissions.</p><h3>Authentication outside of Google Cloud</h3><p>If your applications aren’t running on Google Cloud, you’ll need to provide credentials.</p><p>In addition to least privilege (authorization), authentication will be a challenge. Fixed service account keys credentials may result in a security breach. <br>For example, if your key is found on github, it will take very little time for people to misuse the stolen credentials.<br>This is why you should avoid static keys and consider workload identity federation<strong> as the first choice.</strong></p><p><a href="https://cloud.google.com/iam/docs/workload-identity-federation">Workload Identity Federation | IAM Documentation | Google Cloud</a></p><p>Workload Identity Federation provides OAuth2.0 based authentication workflows for using a third-party identity in Google Cloud. Products like github, gitlab or others cloud service providers are good use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*1wOSQ1JZ5IjwH8cDV92tTw.png" /></figure><p>To avoid errors, you can restrict the creation of service account keys using the organisation policy <strong>constraints/iam.disableServiceAccountKeyCreation</strong> at project, folder or organisation level.</p><p><strong>As a second choice</strong>, you can adopt short-lived service account keys using solutions like Hashicorp Vault. With the GCP secret backend, Vault helps you to dynamically create and revoke credentials. You are free to configure the duration of the lease.</p><p><strong>If none of the above solutions</strong> works for your case, static credentials is the last option. You are strongly encouraged to enforce a network level protection to prevent data exfiltration or mining (the next part).</p><p>Keep in mind that service accounts are only required by applications. Users can use their own identity using gcloud.</p><pre>$ gcloud auth application-default login<br>$ gcloud auth login</pre><h3>Authorization layer</h3><p>Setting the right level a privileges for service accounts is called least privilege: only give permissions you need to run it, no more. <br>Basic (or primitive) roles like Owner or Editor are strongly discouraged and predefined roles may be too large for applications (but a good compromise for your users). <br>Custom roles are exactly what we want to do by adding only permissions the application needs.</p><p>If you want to dig deeper in restrictions, IAM binding can be subject to conditions. Conditions are boolean expressions to limit credential permission based on resource or request context (resource name, request time, etc.). Refet to IAM conditions documentation to list services that support conditions.</p><p><a href="https://cloud.google.com/iam/docs/conditions-overview">Overview of IAM Conditions | IAM Documentation | Google Cloud</a></p><p><a href="https://cloud.google.com/resource-manager/docs/organization-policy/org-policy-constraints">Organization policies</a> and<a href="https://cloud.google.com/iam/docs/deny-access"> IAM deny access</a> can also be very useful in restricting users and service account permissions.</p><h3>Theory versus Practice</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*8xpoqS6w-o1K_MWwFGYU9Q.png" /></figure><ul><li>My front Cloud Run service is IAM protected and only my user is allowed as <strong>roles/run.invoker</strong> on this service</li><li>Service account used by the “front” Cloud Run is granted as <strong>roles/pubsub.publisher</strong> on the Pub/Sub topic</li><li>Service account used by Pub/Sub subscription is grant as <strong>roles/run.invoker</strong> on the “back” service</li><li>Finally the “back” service is grant as <strong>roles/datastore.user</strong> on my project</li></ul><p>I also added default logging and monitoring permissions on service accounts used by my cloud run services.</p><h4>Pros:</h4><ul><li>Service account keys in Google Cloud are managed by Google</li><li>Malicious use of managed service usage is limited by permissions set for each layers</li></ul><h4>Cons:</h4><ul><li>No egress traffic filtering on compute resources, code injection mau result in data exfiltration</li><li>Internet exposure without ingress filtering</li><li>A bad actor can use a service account keys stolen</li></ul><p><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-2-435bb0aba75f">In the next part</a>, we will see how to improve ingress and egress traffic filtering using VPC Service Control.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14dda7e7163c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/protecting-sensitive-data-securing-data-pipelines-on-google-cloud-part-1-14dda7e7163c">Protecting Sensitive Data: Securing Data Pipelines on Google Cloud (part 1)</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning from P.O.C to Production — Part 4]]></title>
            <link>https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-part-4-ecf25d24a452?source=rss----10099c88703e---4</link>
            <guid isPermaLink="false">https://medium.com/p/ecf25d24a452</guid>
            <category><![CDATA[machine-learning-engineer]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[industrialization]]></category>
            <dc:creator><![CDATA[Florian DEZE]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 13:38:07 GMT</pubDate>
            <atom:updated>2023-02-16T13:37:52.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning from P.O.C to Production — Part 4</h3><h4>Stable ML Models from ML Engineer point of view</h4><p>Previously we had seen the roles of a Data Engineer (<a href="https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-6f31e7e97d54">part 2</a>) and Data Scientist (<a href="https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-part-3-9ac6daf21b80">part 3)</a>. Now the last role of these series, the ML Engineer.</p><p>Performance in ML projects comes from two essential parts, the features and the model. The main problem in production is potential instabilities within the features at the calculation time due to the previous data pipeline step, internal or external factors.</p><p>Also, when updating the ML model, you might compare your new solution with the previous one but how can you compare it fairly?</p><h3>Features instabilities</h3><h4><strong><em>Instability introduced by company collecting systems</em></strong></h4><p>A data always has a source, which is not always known by its consumers. Thus, small changes in the collecting systems can introduce bias, change in distribution, lack of information into the final exploited data. A classic example should be in a customer form. At first, most of the fields are mandatory and it takes some time to fill it. So, most clients choose to not fill a form at all. To increase the fidelity and encourage customers to register, some fields are put as optional (or pre-filled) to reduce time in filling the form. As a consequence, if you have a product, based on specific information about customers which became optional, you might have a decrease of performance due to lack of information. The same will happen with pre-filled information which will change the distribution of information.</p><h4><strong><em>Instability introduced by company business rules</em></strong></h4><p>This case can be summarised by one sentence “y<em>ou are a consumer, not a producer</em>”. This implies you are subject to change on the data sources without knowing. It can introduce bias, inconsistencies or change the logic of information behind your features.</p><p>Most of the time, we think about table schema, access path etc… but a more tricky one is a change in the way of creating the data and the modification of the business rules behind it.</p><p>Here’s an example from a previous experience: I had a ML product which optimised control over delivery. One of the key information was to know, for each delivery, if it was controlled or not (to build historical features and check performance over time in production). The business app producing this data did not have a field “control / no control”, they told us to use fields like control_duration (in second). If the field was 0, then no control has been done, else people took time to count the delivery content. Thus far no problem. We saw that around 20% of delivery was controlled, which corresponds to previous information the business had given us. Then one day, 99.8% of no-control. After a long investigation, one product, between the original one and us, introduced a rule which truncates the control_duration at a minute level. Since most of the control duration was less than 60 seconds, it truncates to 0.</p><h4><strong><em>Instability introduced by external environment</em></strong></h4><p>External environments or events can have a significant impact on data distribution. Since your model is based on past data, using the hypothesis where data should be the same in the future, your model can generalise the problem and respond correctly over time. You will only need some retraining to compensate for small evolution. But what if your data evolve so much in a short period of time, that your model will not be able to respond correctly.</p><p>One simple example is data over price. Let’s hypothetically think a situation like a pandemic, economic crisis or even a war can create a big inflation of product price. But this data is used by your model, which will lead to behaviour change in predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cwGSBR1Ll0CCsp1Cf7VRXQ.png" /></figure><p>This graph represents a change in price repartitions. The blue one corresponds to prices before inflation and the orange one is after inflation.</p><p>In case of a classification problem, your model might have learned that all prices inferior to 30$ should be of category A and others are more likely of category B. But with inflation, this threshold is not pertinent anymore.</p><p>Guessing your next question: Why not just retrain the model on new data?</p><p>Well, if the change is too sudden you might not have enough volume of historical data for your model with those new changes. It will be diluted within the historical data.</p><p>Here an example if we show the same repartition without scaling the density between [0, 1]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZVOe9FMk6VHV03st8P5POQ.png" /></figure><p>As you can see, the orange points (new prices) are few compared to older ones. It will be difficult to re-train a model to take this inflation into account.</p><p>What a ML engineer needs to be aware of during production?</p><blockquote>Everything is about distribution of today</blockquote><p>In a <a href="https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-part-3-9ac6daf21b80">previous article</a>, describing the role of the data scientist in stability, I summarised his problem by “everything is about distribution”. On the ML engineer side, it will be close to it. The data scientist has to check its distributions over large historical data (and possibly with more features in the experimentation phase). For the ML engineer, it will be monitoring the distribution over time in production: “What is the distribution of today new features compared to past ones?”. It will also be the simulation of new groups of features, re-training and deploying systems, to reduce time to market.</p><h3>Models comparison and reproducibility</h3><p>When you use an ML product, it might not be the only component to formulate the final result (estimation of price, decision in a process, transformation of an image, etc..). If you wish to change your ML model or statistical method, you will compare it with the previous method. But how will you compare it, if you can’t reproduce the exact same conditions of result?</p><p><strong>Use case 1</strong>: Compare the performance of the whole decision process</p><p>You have an ML model which analyses the colour of a food product. If the colour is abnormal, the food might be contaminated and will be analysed manually.<br>- First decision step: your ML model returns a probability of contamination. If the probability is higher than a predefined threshold, the food will be controlled.<br>- Second decision step: a random decision, based on a uniform statistical law, which decide to control food for X percent of the time. It will help to detect false negative (when the model gives a low probability but the food was contaminated)</p><p><strong>The problem</strong>: the confidence in measuring performance. If you re-run all previous cases with the same ML model, you won’t obtain the same results because the random choices won’t be the same. If the X percent of random is 5 or 10%, you might have some different performance in the simulation with the same model, so thinking about comparing with a new ML model is even more problematic when you want to confirm which model is better (unless the performance is drastically different).</p><p><strong>Solution</strong>: Do not use random functions, but pseudo-random like hashing and modulo. Whether it is a unique id, the input image or anything which identify your individual in your dataset, you can decide with the following process:<br>hash(id of the individual) mod 100 &lt; X<em>, with X the percentage of pseudo-random cases you want to add in your process</em></p><blockquote>NOTE: Be aware that some hashing methods use SEED, so you won’t have the same results, depending on the instance running your app. You can take a look at farmfingerprint hashing methods, like farmhash of GOOGLE, which are stable and create the same hash every time.</blockquote><p><strong>Use case 2</strong>: Compare the performance of ML models only</p><p>Like explained in the previous article (from a data scientist point of view), you need to split your data between train, test, validation sets. You want to compare the ML model currently in production with a new model.</p><p><strong>Problem</strong>: Performance can change depending of the splitting you use, if you want to compare two ML models, you need to have the same splitting for a valid comparison. Also, the training and performance comparison session might not occur at the same time for each model. You have created one ML model 3 months ago, and today you need to re-create one. So if you want to compare performance with the same data, you need to remember the splitting used before or re-test your previous model with the new splitting.</p><p><strong>Solution</strong>: Again, you need to use a pseudo-random splitting method and not a random one (like train_test_split of Scikit-learn). The same set will be used for training and the other ones for validation and tests. Also if you use cross-validation to have multiple performance tests and obtain a mean, the result will be more meaningful if the splitting is exactly the same.</p><p>In an ideal ML project, past data will reflect futures data. Everything is delivered on due time and external events don’t affect your data. Well, that’s too bad for us in our imperfect world. If you want to minimise risks in your project, you should answer yes to these following requirements:</p><p><strong>For the pipeline execution:</strong></p><ul><li>I define/execute tests in the pipeline (unit tests, integration tests, coherence tests)</li><li>I define/use precise version of the tools used</li><li>I have a retry policy for the pipeline</li><li>I monitor and have an alert system on my pipeline</li><li>I have a scalable pipeline</li><li>All transformations and predictions are reproducible</li></ul><p><strong>For data quality:</strong></p><ul><li>I have defined quality metrics for each field (range of values, uniqueness, distribution, etc…)</li><li>I have defined thresholds for each couple metrics — data when necessary</li><li>I have a threshold estimation process</li><li>I have documented thresholds estimation process</li><li>I can re-run regularly, the estimation process to compare with previous ones</li><li>I can re-adjust threshold if needed</li><li>I have documented a workflow of decision based on my metrics results (alerting, stopping the pipeline, partially stopping, over-writing or appending data)</li><li>I can track and explain distribution drift</li><li>I can explain/link each drop of performance in my model inference to my distribution shift when it’s the cause</li><li>I can simulate all my previous app use and obtain the same results</li><li>I can compare ML models over time on the exact same data</li></ul><p>Now that we have seen roles responsibilities in a project, we will take a closer look to modules which will compose your project app. Next part will be about Feature Store and Feature Pipeline.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecf25d24a452" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-part-4-ecf25d24a452">Machine Learning from P.O.C to Production — Part 4</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Large datasets at Scale Part 1]]></title>
            <link>https://medium.com/codeshake/exploring-large-datasets-at-scale-part-1-d0a81e9b5edb?source=rss----10099c88703e---4</link>
            <guid isPermaLink="false">https://medium.com/p/d0a81e9b5edb</guid>
            <category><![CDATA[vaex]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ziyad Mestour]]></dc:creator>
            <pubDate>Wed, 15 Feb 2023 13:51:19 GMT</pubDate>
            <atom:updated>2023-02-15T13:51:18.951Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Have you ever worked with Pandas and found it not at all optimized for large datasets ? Well if that’s the case you’re in the right place.</em></p><p>This is a first part of a series of exploring data @ Scale. Fasten your seatbelt and enjoy the reading !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JnErxmEeWY0GkvZHsOInyw.jpeg" /></figure><p><a href="https://vaex.io/"><strong>Vaex</strong></a> is a library similar to Pandas for <strong>EDA</strong> (Exploratory Data Analysis) in Python. It’s an equivalent of <strong>Modin</strong>. I came across this library in 2019 when a colleague of mine shared it.</p><p><strong>Why use Vaex ?</strong></p><p>Well Vaex does something interesting which is<strong> in-memory mapping</strong>. It means that instead of loading a dataset into your RAM, it only points to the dataset which is already on your storage (SSD/HDD). Now this is the part where it gets interesting, this means that you can analyze a 1TB dataset in your 8G RAM computer.</p><p>Aside from that, Vaex can integrate with <strong>GCP Cloud Storage</strong> and <strong>AWS S3</strong>. The advantage of it is, you are able to analyze large datasets without having to provision a large notebook.</p><p>Other benefits include using<strong> multiprocessing</strong>, <strong>lazy evaluation </strong>and amazing <strong>visualizations. </strong>On the other hand Pandas does not indeed leverage your cores.</p><p>Last but not least, you can perform some <strong>Machine Learning</strong> on your exploration and this is very powerful. Meaning you can explore the usability of your dataset and check if your data is potentially interesting to train a model on it!</p><h4>Vaex features</h4><p>Vaex has 4 major components:</p><blockquote><strong>Vaex-Core: </strong>DataFrame and core algorithms, takes numpy arrays as input columns.</blockquote><blockquote><strong>Vaex-Hdf5</strong>: memory mapped numpy arrays to a DataFrame.</blockquote><blockquote><strong>Vaex-Jupyter</strong>: Interactive visualization based on Jupyter widgets / ipywidgets, bqplot, ipyvolume and ipyleaflet.</blockquote><blockquote><strong>Vaex-</strong>Ml: machine learning</blockquote><h4>Vaex in action</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*GgSQ6taUnbsoKHw51BK3HQ.jpeg" /></figure><p>In the next lines you’ll see examples of reading large datasets ~11 million lines on a personal computer and performing basic filters on it. Now this would be a nightmare in Pandas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pu2rBulQEh-CU7l5ylkD6w.png" /><figcaption>11 million lines in the order of micro seconds</figcaption></figure><p>Again here Vaex only points to the dataset, no loading into memory. Which explains the blazing fast data reading speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zDjPi8mCt7Xu3jTxduPEQ.png" /><figcaption>Performing some filters on the whole dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xBvzwcyk25psS2I5OuBwpw.png" /><figcaption>Cool visualization of taxi pick ups in NYC</figcaption></figure><p>In this first series I’ve only touched upon the surface of what can be done with Vaex, in the next tutorial I’ll go in more details.</p><h4>Limitations</h4><p>Well in my opinion Vaex doesn’t cover all of the Pandas API. I would think of Vaex as an exploration tool rather than a production one.</p><p>Other limitations include the <strong>Vaex-ml API</strong>, for the moment it supports only a limited number of models compared to the <strong>Sklearn API</strong>.</p><h4>Conclusion</h4><p>That’s it folks for this first part of analyzing datasets at scale series. Next time I’ll be performing EDA on a dataset and training a Machine Learning model with Vaex with complete code samples :)</p><p>Please don’t hesitate to like or comment, this encourages me to keep on writing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0a81e9b5edb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/exploring-large-datasets-at-scale-part-1-d0a81e9b5edb">Exploring Large datasets at Scale Part 1</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning from P.O.C to Production — Part 3]]></title>
            <link>https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-part-3-9ac6daf21b80?source=rss----10099c88703e---4</link>
            <guid isPermaLink="false">https://medium.com/p/9ac6daf21b80</guid>
            <category><![CDATA[industrialization]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Florian DEZE]]></dc:creator>
            <pubDate>Thu, 09 Feb 2023 11:09:39 GMT</pubDate>
            <atom:updated>2023-02-09T11:09:11.548Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning from P.O.C to Production — Part 3</h3><h4>Stable ML models from a Data Scientist point of view</h4><p>In <a href="https://medium.com/p/6f31e7e97d54">part 2</a> we saw the responsibilities of a Data Engineer, to ensure a good quality of data. Now let’s study the responsibilities of a Data Scientist. This article will not talk about all the aspects of the work of a Data Scientist but only the technics used to prevent instability in production and reduce risks over time.</p><figure><img alt="Source: https://www.kdnuggets.com/2017/08/37-reasons-neural-network-not-working.html" src="https://cdn-images-1.medium.com/max/900/1*_MT9zX64RLphkkztsR-Okg.png" /><figcaption>Source: <a href="https://www.kdnuggets.com/2017/08/37-reasons-neural-network-not-working.html">https://www.kdnuggets.com/2017/08/37-reasons-neural-network-not-working.html</a></figcaption></figure><blockquote><strong><em>Everything is about “Distribution”</em></strong></blockquote><p>This sentence resumes the main problem a Data Scientist will encounter to ensure a stable model.</p><p>When you build a model, you feed it with information based on the hypothesis of “<em>similarities</em>” between past and future information. One used case could be creating an image recognition model of humans, where you assume that humans nowadays will be the same tomorrow or the next few months and years. But this hypothesis is not always true: we call that distribution shift (or drift) and it will lead to performance decline over time. You can simply visualise it with data about prices. There are often things like inflation or other market behaviour which will drastically change prices, making past information obsolete.</p><h3>Distribution problems in Production by types</h3><h4>Covariate Shift</h4><p>For supervised ML training (having features and labels), you might encounter a covariate shift. It consists of a change in distribution of one or more features, while having labels unchanged. An illustration could be the creation of a credit score on a bank for loan. You take the salary and other revenue (and other features) to determine the risks of a new credit for the customer. Let’s say the algorithm determined that a revenue less than 1600€ increases the risk. If high inflation occurs, one of the measures is often to grant a promotion at the same rate, which will increase the number of people over 1600€, but the wealth and risks of credit should not change (because daily life is more expensive). The model will more likely be favorable to giving credit than before inflation.</p><p><strong>How to detect and prevent it ?</strong></p><ul><li>Rule 1: Remove features with high unpredictable shift</li></ul><p>If a feature has too many shift occurrences over time or too drastic, you should consider not including it, unless you have high confidence in your CI/CD/CT and monitoring for detection.</p><blockquote>NOTE: the definition of ‘too drastic’ is quite arbitrary. It’s hard to efficiently judge what threshold of shift is tolerable. You can do simulations by adding artificial shifts and measuring the variation of performance, but if you have many features to test, it can be time and resource-consuming. What you can do to reduce the number of tests/combinations is to measure the <strong>feature importance</strong> for your model and focus only on ones with a big impact on the decision.</blockquote><ul><li>Rule 2: Re-training the model with fresh data</li></ul><p>Re-training the model might help if the shift is smooth over a long period of time. You will have accumulated enough recent data for your model to take into account that shift. You can also use “<a href="https://en.wikipedia.org/wiki/Data_augmentation"><em>Data Augmentation</em></a>” methods to increase recent data samples. Be aware that a drastic shift reduces the possibility of using this technique (not enough recent data).</p><ul><li>Rule 3: Prepare for removing features</li></ul><p>If you decide to not follow rule 1 (drop of performance too high compared to the risk of feature shifts) and you predict a risk with rule 2, you need to at least train a model without the problematic features, to ensure you can build a model with a performance higher than the threshold decided with the business.</p><p>If you can’t, it means the days the shifts happen, you won’t have a backup plan.</p><h4>Label shift (or Prior probability shift)</h4><p>For supervised ML, it’s when the distribution of the label changes but the features do not (the exact opposite of Covariate Shift).</p><p>For example, in case of an economic crisis, people tend to buy fewer houses, which drops the price of the markets. If you have an algorithm which estimates the price of the house, then for the same features (house size, number of bedrooms, etc…) the price will change.</p><p><strong>How to detect and prevent it ?</strong></p><p>The detection is quite simple, you can plot multiple distribution diagram of your label, chunk by time period (or between train / test) and see if there is any change. It’s a graphical approach, but you can use a statistical approach if you want (in python: <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html">scipy.stats.ttest_ind</a>)</p><p>The correction of this use case can be quite a headache, because you can’t remove the Label compared to Covariate shift when you removed the problematic feature.</p><ul><li>Rule 1: reduce history</li></ul><p>Most Label shifts occur over temporal reasons (house prices change over time). Taking the last 10 years of house transactions is less pertinent than taking only the last year of transactions</p><ul><li>Rule 2: Remove anormal distribution</li></ul><p>If the label shift is correlated with time, you can remove the training data which does have different distribution than your test set</p><ul><li>Rule 3: Last resort</li></ul><p>You can adjust past label data values by estimating shifts on newer data and apply it on old data. We can illustrate it with an house price use case: You can regroup “similar” houses in characteristics (apply an unsupervised classifier). Then, for each group, calculate a mean ratio between old prices and new ones. Re-write old data prices by applying this ratio. This will make old prices similar to the new ones and reduce distribution shifts.</p><blockquote>NOTE: It can be hard or even not possible to automate these kinds of analyses and re-adjustments. At least, you need to monitor and measure these behaviours carefully. This will reduce your team’s analysis and correction time.</blockquote><h4>Concept shift</h4><p>This drift is a change in definition of your labels. You can see it in ML projects like determining what is fashionable or a job title which can be interpreted differently from countries, regions of experience, etc…<br>It is the hardest type of problem to solve and the resolution method, if it exists and applicable, will depend on the situation.</p><ul><li>method 1: Periodically re-train</li><li>method 2: Weighting data. Put more weight on “representative” data or recent data</li><li>method 3: Data augmentation on newer or “representative” sample</li><li>method 4: Creating a new model. If the concept drift is too sudden (due to an important event like COVID, war, economic crisis, etc.), completely re-creating your model can be the only solution (change algorithm, hyper parameters, train/validation/test sample)</li></ul><blockquote>NOTE: “Representative” is not defined precisely because it will depend on the problem and your knowledge about your data. “Representative” can be the contrary of outliers, or more recent data.</blockquote><h3>Distribution problems in Training: Overfitting and Underfitting</h3><p>Those problems are also related to distribution. Overfitting is about over-training your model on data which disables the ability to generalise the problems when used in production. This problem can be reformulated by having distribution in your training set, not the same as in real life. You can do the same reflection with under-fitting where your data distribution is not enough to represent the whole cases.</p><p><strong>How to detect and prevent it?</strong></p><ul><li>Rule 1: A good splitting</li></ul><p>When you create your dataset for training and testing you can create this kind of repartition: <br> - training set: used for training the model<br> - validation set: used to test the performance of your trained models between each change of hyper-parameters<br> - test set: used to test the performance of your final model</p><p>Most overfitting comes from hyper-parameterisation, when you choose some parameters for your algorithm before training and change it back to see if you perform better (most of the time, using <a href="https://en.wikipedia.org/wiki/Hyperparameter_optimization">gridSearch or Bayesian Optimisation</a>).<br>The problem: “is the performance better in general or only on your test set?”. To prevent it, we introduced a validation set, which will be used to compare performance in each model / simulation. Once we choose the best one, we measure the performance again with a test set. If the performance does not drop, it means you have a lower risk of overfitting.</p><ul><li>Rule 2: Ensure good repartition of labels</li></ul><p>If you take human face recognition use cases, you might have seen some problems in the <a href="https://nypost.com/2017/12/21/chinese-users-claim-iphone-x-face-recognition-cant-tell-them-apart/">media</a>. Some people couldn’t be recognised by their smartphones and it happened more frequently to women and people issued from a minority (from USA and European point of view). The main reason is the database of images which contains mainly white men (more than 50%), and others which were under-represented in the database. So, the model couldn’t train well for those people. But why was it not detected beforehand ? That’s simple, the score was highly performant in global, so it was not detected at first, until the social media reaction over the number of complaints.</p><ul><li>Rule 3: A good repartition of features</li></ul><p>After splitting your different datasets, you can check if there is any covariate shift between them. The method is simple:<br> - Step 1: add a new label (0 for training set, 1 for testing set)<br> - Step 2: concatenate and shuffle those two datasets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sgSPi7Hu5gR-fgGuTTVq9Q.png" /></figure><p>- Step 3: train a classifier to determine if the data are from the train or test set<br> - Step 4: if the score is high, it means your distribution is not the same between train and test. Redo your splitting</p><ul><li>Rule 4: add training difficulty to your model</li></ul><p>If you want to generalise a problem and prevent your model to fit too much on your train dataset, you can give some difficulty to your model to learn from those specific data.<br>Some non-exhaustive techniques:<br> - Adding noise: add some small random value to your features (ex: a value of Feature 1 will pass from 0.34 to 0.343). It will add approximation to the data<br> - Constraints (L1/L2 regularisation): Constraint weights associated with features to be in a certain range of values<br> - Dropout (for Neural Networks): Deactivate some neurons randomly at each step of the training. It creates approximation in the optimisation process</p><ul><li>Rule 5: Cross Validation (CV)</li></ul><p>Cross validation regroups methodologies to measure the variation of performance between test sets and see if it is stable or not. You train /test your model on different sets of data (with same hyper-parameters and SEED) and check the variation of performance. It is also useful when we have few data. It consists on training and testing the performance of the model multiple times and assert a stable performance or get a mean performance. The difference between each cross validation methods are the splitting of train / validation / test sets. A list of non exhaustive methods are K-Fold, TimeSeries Split, Blocked CV (and Blocked Time Series CV)</p><p>To conclude, a Data Scientist has to guaranty a good distribution of its features and labels, the study of risks for each of them and the use over-fitting/under-fitting prevention methods.</p><p>In the next part, we will see the responsibilities of a ML Engineer once the model is created.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ac6daf21b80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-part-3-9ac6daf21b80">Machine Learning from P.O.C to Production — Part 3</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 illustrated uses of VIM for DevOps]]></title>
            <link>https://medium.com/codeshake/5-illustrated-uses-of-vim-for-devops-e734e6e56c44?source=rss----10099c88703e---4</link>
            <guid isPermaLink="false">https://medium.com/p/e734e6e56c44</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Jérôme NAHELOU]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 07:59:42 GMT</pubDate>
            <atom:updated>2023-01-03T08:07:26.022Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will share with you my 5 best tricks to become more efficient when editing your manifest (Terraform, YAML, …) using VIM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*j4kund5cFoG1ukz8590t7A.png" /></figure><h3>1. Focus on Top/Middle/Bottom</h3><p>Manifest files can contain hundreds of lines. When you edit them, you can lose seconds, losing your focus or move cursor position while using your mouse to scroll up/down.</p><p>With zt, zz, zb, you can easily update your windows to move the line on top, center or bottom.</p><p>To remind you, it’s quite simple: z&lt;top&gt;, z&lt;bottom&gt;, zz to center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*KOpftgcpHuV7XhPyeUqeaw.gif" /></figure><h3>2. Macros</h3><p>Visual blocks are powerful when working on consecutive rows. But using them on a set of blocks can be repetitive.</p><p>In this scenario, you should look at macros.</p><p>Using macros can be tricky, but always follow the sequence:</p><ol><li>Start recording on a dedicated key using q&lt;key&gt;</li><li>Execute commands you want to reproduce (move, replace, append, …)</li><li>Stop recording using q</li><li>Replay as needed using @&lt;key&gt;</li></ol><p>In the following example, I used macros to quickly declare Terraform variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Nbefe9VvDjUYuwjOaZyegw.gif" /></figure><h3>3. Registers (clipboards)</h3><p>VIM provides 26 registers that you can use to copy/cut/paste content.</p><p>By default, when you copy or cut text, vim saves it in the &quot;”(unnamed) register. But registers can be bound from a to z to be reused easily even if you copy or cut afterwards.</p><p>To do this, press &quot; followed by the key to map and the action to be taken (y to copy, d to cut). Example: &quot;ayy to copy and save the content to a register.</p><p>To paste the content, press &quot;&lt;key&gt;p</p><p>You can use :reg to display the content of the registers.</p><p>Registers 2 through 9 are used by VIM to hold deleted content. Very useful during code refactoring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*pfQyEB8y5NFfovVE3sTc1A.gif" /></figure><h3>4. Sort blocks</h3><p>I like to sort my Terraform variables. But sorting multiple blocks is quite difficult.</p><p>In the following demo, I share with you a very effective trick<a href="https://superuser.com/questions/752032/how-do-i-sort-multiple-blocks-of-text-by-the-first-line-in-each-block-in-vim"> I found to sort blocks</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*88XUAdHpExs5SeP13jOJLg.gif" /></figure><h3>5. Marks</h3><p>Marks are a good alternative to zt, zz, zb we saw earlier. You can bind any key to jump from a location to the mark.</p><p>Set a mark using m&lt;key&gt;, then return to mark using `&lt;key&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*Th_h_2m3nuHnaXAjoMZ-7g.gif" /></figure><h3>6. (extra) Cuc, right, left, &gt; and &lt;</h3><p>Editing YAML is a nightmare, using cuc you can draw a vertical line to ensure you are at the correct indent.</p><p>Then select the block you want to indent and play with &gt; or &lt;. Repeat with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*vwEZchnrOb0cI8cAnfgXlQ.gif" /></figure><h3>References</h3><ul><li><a href="https://quickref.me/vim">https://quickref.me/vim</a></li><li><a href="https://vimtricks.com/p/category/tips-and-tricks">https://vimtricks.com</a> and <a href="https://twitter.com/vim_tricks">https://twitter.com/vim_tricks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e734e6e56c44" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/5-illustrated-uses-of-vim-for-devops-e734e6e56c44">5 illustrated uses of VIM for DevOps</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning from P.O.C to Production — Part 2]]></title>
            <link>https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-6f31e7e97d54?source=rss----10099c88703e---4</link>
            <guid isPermaLink="false">https://medium.com/p/6f31e7e97d54</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Florian DEZE]]></dc:creator>
            <pubDate>Thu, 24 Nov 2022 08:43:25 GMT</pubDate>
            <atom:updated>2023-02-03T10:25:05.879Z</atom:updated>
            <content:encoded><![CDATA[<h4>Stable ML Models from Data Engineer point of view</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*Eh0H0AounrbOpBjQGNgp9A.jpeg" /><figcaption>source: <a href="https://airbyte.com/blog/etl-framework-vs-etl-script">https://airbyte.com/blog/etl-framework-vs-etl-script</a></figcaption></figure><p>In <a href="https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-171a9e51d80">part 1</a>, we had introduced concepts, roles and vocabulary necessary to understand the basics of an ML project.</p><p>Performance in ML projects comes from two essential parts, the features and the model. So why does a Data Engineer have a responsibility for it ? The main problem in production is potential instability within the features at calculation time or from data source during data pipeline processes. We will see in this article why instability exists, how to prevent it and what are the responsibilities of a Data Engineer?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-TNj66q1-yqQoSCabhesw.png" /></figure><p>A Data Engineer should always secure its pipeline’s proper execution. You can have four level of security and quality over these executions:</p><h3>Level 1 Orchestration, monitoring and retry</h3><p>This is the basic level of construction of pipelines. Your pipeline should not be executed by simple sequential script, but by a proper orchestration tool, which will:</p><ul><li>Be triggered by scheduler or events</li><li>Orchestrate tasks: monitor status of each task, wait between tasks</li><li>Parallelise tasks when necessary to optimise execution time</li><li>Present status execution of each steps</li><li>Enable relaunching/retry of a task or the whole pipeline</li><li>Log tasks status (success, failure, retry, etc…)</li></ul><p>This orchestration tool will be combined with monitoring and alerting applications to ingest logs and create alerts or performance metrics.</p><h3>Level 2 Reproducibility and Re-writing history</h3><p>When your pipeline does not execute correctly, you will need to relaunch it. But it can be more tricky than just clicking on a button.</p><p>Let’s illustrate it with a use case<em>:</em></p><blockquote><em>You construct a pipeline executing</em><strong><em> once every day</em></strong><em>. This pipeline will execute SQL requests, with </em><strong><em>dynamic injection of time</em></strong><em> parameters (like: “WHERE date_col &gt; current_date() — 31”). Those results will be appended in a table, with </em><strong><em>partition on insertion time</em></strong><em>. Your pipeline failed for some reason (network or service interruption).</em></blockquote><p><strong>Problem</strong>: You need to relaunch the pipeline but you couldn’t do it during the day of failure (you missed the alert, correction was too long, etc…). You want to relaunch it the next day, but since the SQL requests are parameterised with launching day, you will not have the same result as if it was yesterday. Also, data won’t be correctly partitioned in your database.</p><p><strong>Solution</strong>: Some orchestrators offer functions or predefined variables which enable them to simulate the launch at a previous day, hour etc.… . Be aware of this feature when choosing your orchestration solution.</p><blockquote><strong><em>Special note</em></strong><em>: Systems dependent on your results might not have worked properly during the day of failure. To be able to analyse problems correctly on your whole product, you need to trace the success or failure of your pipeline and publish this information. You can do it using a database table, by adding technical columns like ‘record_creation_date’, ‘update_date’ etc.. . You can also create another table containing success, failure for each table managed by your pipeline, at table or column level.</em></blockquote><h3>Level 3 Quality test during execution</h3><p>A pipeline is composed of N steps. If your final(s) step(s) expose the result, you might want to only give the result if you are sure of the quality of the data you publish. By adding quality tests between your steps and conditioning your pipeline orchestration over the success / failure of each test, you can prevent from publishing error prone data.</p><p>Here some category and example of tests:</p><p><strong>Accuracy</strong>: Is the information reliable?</p><ul><li>Count the number of lines before and after joins between tables</li><li>Check the range of values (ex: between [0, 1], in [category_1, category_2], etc…)</li><li>Comparison of coherence between two or more fields (ex: start_date &lt; end_date)</li></ul><p><strong>Consistency:</strong> Does information stored in one place match relevant data stored elsewhere?</p><ul><li>Compare information between different sources (for same keys, having the same values for the same fields)</li></ul><p><strong>Integrity</strong>: Can you join data from different sources correctly?</p><ul><li>Count number of lines with unique keys = size of your table (if deduplicated)</li></ul><h3>Level 4 Quality test of external pipelines</h3><p>Quality depends on data sources and previous pipelines. Even if you can’t interfere with their processus, you need to take into account the possibility of failure from the source systems. There are three use cases to be aware of:</p><h4><strong><em>Instability introduced by systems</em></strong></h4><p>Your project will begin by a data pipeline which will aggregate multiple data sources, each one of them depending on other product(s) / application(s).</p><p>Eventually, those products or your data pipeline will encounter bugs, interruption or late delivery date, which will result in degraded features (inconsistent, outdated, etc.).</p><p>Let’s see an example: Most of the data you use will be updated between 1:00am and 3:00 am. You want to start your data pipeline at 3:05am daily in order to refresh your database with the last information for the next updates of features. But if you access the history of updates of those data sources, you might see some tables updated at 4:00am or even 4:00pm at random days of the year. So your pipeline will update only parts of the data and even create inconsistency later if some features are aggregation between fields in updated and outdated data sources.</p><p>That information is helpful for a data scientist when a model is defined (since the past historical data used to train/validate/test the model are by definition up to date). So you can create the following metrics in order to follow this instability over time:</p><ul><li>Mean Time to Late Publish (MTLP): mean delay duration if there is any delay.</li><li>Late Publish Ratio: number of times there is delay divided by the number of updates.</li></ul><h4><strong><em>Instability introduced by history recovery</em></strong></h4><p>When the data scientist takes historical data from the data warehouse, that data might have been updated since their first insertion. Sometimes to correct errors, sometimes for business reasons due to rules behind the product. At this point, the corrected historical data possess more accurate information than the recent data and way more than the last real time or batch data you will ingest in your ML model. Thus, it will decrease performance for production.</p><p><strong>Solutions</strong>:</p><ul><li>Enable traceability over those changes if possible. Sometimes when data is published, you can find technical dates like date of creation of record and date of update. You can count the number of times there is a mismatch between the two dates (but it will only gave you the mismatch over the table, not a particular field)</li><li>Create metrics to evaluate the quality of the system and monitor over time.</li><li>Based on the features created, check if those features are important for your model. The more important the feature, the more exigent you need to be on your metrics.</li></ul><p>Metrics you can use to evaluate proportion of re-writing:</p><ul><li>Mean Time to Correct (MTC): mean duration before correction/update of information</li><li>Correction Ratio by Line: number of lines corrected divide by the number of lines</li><li>Correction Ratio by Day: number of days with correction divided by number of days</li></ul><h4><strong><em>Instability introduced by structures</em></strong></h4><p>Most ML projects consume data you don’t own. Producers are the ones which define their structure, availability and life cycle. Which means your table or fields inside your table can disappear. Structures (table schemas) can change drastically.</p><p>The prevention should be made at the company level, by introducing a rule or a system which disables drastic changes in schema, apply alerting and transition duration for consumer’s adaptation.</p><p>To conclude, if you want to have a stable project, you need to implement the following features:</p><p><strong><em>For the pipelines execution:</em></strong></p><p>✔️ I define/execute tests on the pipeline data (accuracy, consistency, etc…)</p><p>✔️ I define/execute tests on my pipeline code (unit tests, integration tests)</p><p>✔️ I define/use precise version of the tools used</p><p>✔️ I have a retry policy for the pipeline</p><p>✔️ I monitor and have an alert system on my pipelines</p><p>✔️ I have scalable pipelines</p><p>✔️ I trace all status/events of my pipeline (success, late delivery, failure, etc…)</p><p>✔️ I trace all the status of my data source (update, partial update, not updated, etc…)</p><p>✔️ I trace all the status of my raw data results (update, partial update, not updated, etc…)</p><p><strong><em>For data quality:</em></strong></p><p>✔️ I measure the quality of my pipeline (delayed, partial update, etc…)</p><p>✔️ I measure the quality of my data source (range values, ratio of nulls, etc…)</p><p>✔️ I measure the quality of my raw tables (range values, ratio of nulls, etc…)</p><p>✔️ I review at fix periods the errors and quality problems and try to improve my process (or external process with other team)</p><p>The next part will introduce the role of a data scientist in the stability of an ML project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f31e7e97d54" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-6f31e7e97d54">Machine Learning from P.O.C to Production — Part 2</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning from P.O.C to Production — Part1]]></title>
            <link>https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-171a9e51d80?source=rss----10099c88703e---4</link>
            <guid isPermaLink="false">https://medium.com/p/171a9e51d80</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[industrialisation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[ml-engineering]]></category>
            <dc:creator><![CDATA[Florian DEZE]]></dc:creator>
            <pubDate>Wed, 16 Nov 2022 10:57:45 GMT</pubDate>
            <atom:updated>2023-02-03T10:24:41.250Z</atom:updated>
            <content:encoded><![CDATA[<h4>ML product global architecture and definitions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*_FVq_c4Jq96m_ZuLi8VQIQ.jpeg" /><figcaption>source: <a href="https://www.flagship.io/test-in-production-memes/">https://www.flagship.io/test-in-production-memes/</a></figcaption></figure><p>ML based products are increasing over the years but they need to begin by a Proof of Concept (P.O.C) phase to display their feasibility, impact on customer life or increase of incomes. Once the project has proven its usefulness, you will enter the tiresome journey of industrialisation. Many companies stopped ML projects at this step, either by underestimating the effort necessary to obtain a steady product or by the deception of decrease in performance (compared to theoretical performances offered by the P.O.C).</p><p>Within these series of articles you will find the explanation of the causes of this decline, the solution and prevention you can apply, whether by concepts, methods or roles in your project.</p><p>This first article is an introduction to concepts and vocabulary before entering the next parts which will detail the problems and solutions over production life cycle.</p><h3>Some definitions</h3><ul><li><strong>Features</strong>: transformed raw data into more meaningful information to feed the prediction model. It can be aggregation of one or more fields from one or more tables in a database. <em>Example: the mean price of products over the last 3 months, with inflation correction</em></li><li><strong>Label</strong>: the information we want to predict (used for supervised training, we will not enter into details for other fields like unsupervised or semi-supervised training). <em>Example: the risk over a bank loan</em></li></ul><p>You can represent these information in a table like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvagsgVr579pbC2p1fl88w.png" /><figcaption><strong><em>Note</em></strong><em>: you can also have the same idea with images or natural language processing (NLP) where an image or a sentence is associated with one label.</em></figcaption></figure><ul><li><strong>Feature importance</strong>: An ML model will associate weight(s) to each feature (that’s the training part). Depending on the weight associated, each feature will have more or less importance to the model. This can be measured most of the time and it is used for the explicability of the model (<em>“why did it make this decision ?”</em>)</li><li><strong>Product</strong>: the name of the app/project or service you expose to your customer(s)</li><li><strong>ETL / ELT</strong>: “Extract Transform Load” or “Extract Load Transform“ are the definition of steps in the data pipeline to transfer data from one source to another with transformation during the process</li><li><strong>Inference</strong>: Result of an ML model. Based on features, the model will return one or more results (probabilities, quantity, etc…)</li></ul><h3>Global Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEyw-raCZPK-lcWoTktltA.png" /></figure><p>When you create a new ML product, you can cut it into four parts:</p><ul><li><strong>Data Pipeline</strong>: aggregate data from multiple sources, whether it’s batch, streaming, internal or external sources and expose it into a data warehouse.</li><li><strong>Feature Store</strong>: Entity which concerns everything about the features (feature pipeline, storage and serving of features). The feature pipeline takes the output of the data pipeline which takes data from a data warehouse and return calculate features, stored into a storage system (realtime or not)</li><li><strong>Model Service</strong>: Entity which will be used to (re)train, deploy, serve your model and monitor its performance</li><li><strong>Your product</strong>: An API (maybe with a frontend) used to call your model, either for real time prediction or for triggering batch prediction</li></ul><p>Basically, when you create a product, you will expose a service (API or Front) for your users. Your product might be more complete and does not only expose ML services, but concerning those ML services you can encounter three types:</p><ul><li><strong>on demand prediction/ real time inference</strong>: the user will send an information which will trigger the API to return a prediction, in real time. For example, on a commercial website with an estimation of delivery date.</li><li><strong>batch prediction</strong>: the user will trigger a job, which might take a few minutes or hours to make inferences on multiple cases and save it in a data warehouse. This type of use case is more often in internal products of a company, like marketing projects when you estimate a customer’s score. Your marketing team triggers the job and gets the result from the front / dashboard, connected to a data warehouse containing the output of the job.</li><li><strong>A combination of batch / on-demand</strong>: sometimes, you can do batch inference of a scheduled date and publish the result in a real time database. The final users will only send information (like a customer id) to get the specific information they need in real time. It’s helpful when you want realtime results with a high performance in response time, but you need all the data beforehand.</li></ul><h3>Roles in the project (with impact on ML parts):</h3><ul><li><strong>Data Scientist</strong>: conception of the P.O.C by evaluating the feasibility, studying the data useful for the project, their quality and propose one or more algorithms (or statistical methods) to answer the problem. One of his main tasks will be to search and converse with the business to understand the subtleties behind the data to obtain a proper dataset to train/validate and test a model.<br> <em>- Identify data sources and study their quality<br> - Define one or more algorithm to use<br> - Train and decide with business people the thresholds of performance<br> - Study shift / drift of features to re-train or change the model</em></li><li><strong>Data Engineer</strong>: The data engineer will orchestrate the recuperation of raw data from one or more data sources (database, messaging, etc…) to constitute a reliable work base for the ML engineer. It will also test the quality of raw data.<br> <em>- Collect data identified by the data scientist and apply filters<br> - Orchestrate the data pipelines (most of the time to a data warehouse)<br> - Maintenance and documentation of the structures (schemas, data lineage, etc…)<br> - Responsible for raw data quality metrics<br> - Manage </em><a href="https://www.redhat.com/en/topics/devops/what-is-ci-cd"><em>CI/CD</em></a><em> of the data pipelines</em></li><li><strong>ML Engineer</strong>: Also called MLOps, it will be the wildcard on the ML industrialisation.<br> <em>- Creating and orchestrating ML pipelines as defined by the data scientist.<br> - Ensure scalability, reusability, composability and portability of the solution.<br> - Manage CI/CD/CT of the ML pipelines and the monitoring of the solution<br> - Responsible for the quality of the features and the monitoring of the model<br> - Ensure the maintenance and documentation of those tasks</em></li></ul><p>The next part will explain the responsibilities of a Data Engineer inside ML projects. Why Data Engineer you may ask? Well, an ML product is more than just a model in production. Data are the main reason for performance stability and a Data Engineer’s work has an impact on it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=171a9e51d80" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/machine-learning-from-p-o-c-to-production-171a9e51d80">Machine Learning from P.O.C to Production — Part1</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitorer, c’est important pour diminuer sa consommation de ressources]]></title>
            <link>https://medium.com/codeshake/monitorer-cest-important-pour-diminuer-sa-consommation-de-ressources-ae5e46c3793a?source=rss----10099c88703e---4</link>
            <guid isPermaLink="false">https://medium.com/p/ae5e46c3793a</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[numérique-responsable]]></category>
            <category><![CDATA[green-it]]></category>
            <dc:creator><![CDATA[Célia Doolaeghe]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 09:09:14 GMT</pubDate>
            <atom:updated>2022-11-08T09:10:13.502Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3MPdJzMPAMBYkvYU_U-pA.png" /></figure><p>Depuis quelques années, je me suis investie personnellement dans une démarche de réduction de mon empreinte environnementale. Mon ambition est de porter la même attention à mon impact professionnel, en tant que développeuse.</p><p>Quand je suis arrivée chez Adeo / Leroy Merlin en 2020, j’ai tout de suite rejoint un petit groupe de motivés qui partageaient cette même ambition, et nous avons monté ensemble un atelier régulier pour proposer des initiatives dans le but de réduire l’empreinte des services que nous développions. Une tâche assez difficile en réalité, car très peu de professionnels de l’informatique sont sensibilisés à cette problématique aujourd’hui.</p><p>Parmi toutes les initiatives que nous avons portées, la plus ambitieuse a été de mettre en place un OKR (Objective and Key Results) sur la consommation de ressources de notre domaine : toutes les équipes étaient challengées pour ajuster la taille de leurs serveurs chez notre hébergeur cloud GCP (Google Cloud Platform). Cela concerne les services travaillant sur Opus, la solution de merchandising pour le site Leroy Merlin. Je fais personnellement partie de l’équipe Search, responsable du moteur de recherche du site.</p><h3>Bénéfices attendus</h3><p>Quel est l’intérêt de monitorer notre consommation ? Pourquoi réduire la taille des serveurs dans le cloud ? Quels bénéfices cela apportera-t-il ?</p><p>Dans le secteur numérique, les data centers représentent environ 15% des émissions de gaz à effet de serre (<a href="https://www.greenit.fr/wp-content/uploads/2019/10/2019-10-GREENIT-etude_EENM-rapport-accessible.VF_.pdf">source</a> p.14), dont la majeure partie est liée à notre utilisation. Il n’est donc pas négligeable de réduire notre consommation cloud. En la monitorant, il est possible de suivre son évolution dans le temps et de se rendre compte si celle-ci augmente. L’intérêt d’ajuster la taille, c’est aussi de limiter la croissance possible des services. On peut évidemment remonter le niveau demandé si besoin, mais il faut idéalement se poser la question suivante : est-ce normal que je doive augmenter la taille de mes serveurs ? Pourquoi ma consommation a-t-elle augmenté ?</p><p>Plus nous prendrons le réflexe de surveiller, moins nous aurons tendance à surconsommer quand nous pouvons l’éviter. D’autant plus que la facturation se fait sur les ressources allouées, c’est donc aussi un moyen de faire des économies de frais sur nos serveurs, qui est bénéfique financièrement.</p><h3>Première étape : les préconisations</h3><p>Il a d’abord fallu qu’on se pose certaines questions : qu’est-ce qu’une utilisation optimale d’un serveur ? Nos services sont déployés sur le cloud pour profiter de l’auto-scaling, c’est-à-dire la capacité à répliquer le service pour tenir la charge. Le but n’est pas d’utiliser 100% du CPU ou de la mémoire de la machine, il faut conserver une marge pour scaler sereinement en cas de pic de trafic, car nous devons conserver la latence la plus faible possible.</p><p>Nos services sont écrits en NodeJS, dont la consommation en CPU varie plus fortement que la consommation de mémoire. Nous avons donc opté pour les niveaux optimums suivants :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*_sF4wGsciCs6Uh_2ZPej7Q.png" /></figure><p>Cela signifie concrètement que nos services, lorsqu’ils tournent au quotidien, seront bien ajustés si la consommation de CPU tourne autour de 60% et celle de la mémoire autour de 80%. On conserve des deux côtés une marge de sécurité pour la scalabilité.</p><p>Pour schématiser, si on représente en rouge la consommation réelle de notre service et en gris la machine qui est réservée pour faire tourner le service, alors le but est bien d’ajuster la machine réservée pour qu’elle corresponde à nos besoins réels :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*9LZk8HAWle6Y4Egm" /></figure><p>Attention, il ne s’agit pas d’augmenter notre consommation, ici les deux cercles rouges font la même taille. C’est seulement le cercle gris qui diminue, donc c’est seulement la quantité de ressources allouées qui évolue.</p><h3>Deuxième étape : le dashboard</h3><p>Une fois les préconisations faites, nous nous sommes chargés de fournir un dashboard dans Datadog pour que les équipes puissent connaître leur consommation actuelle de CPU et mémoire, et sachent quelles actions mettre en place pour ajuster les machines dans GCP. C’est mon collègue ops Sylvain Lefranc qui s’en est chargé.</p><p>Dans ce dashboard, nous calculons un score sur 100 qui correspond à la consommation actuelle sur celle demandée, avec un score maximal sur les niveaux préconisés. Pour faciliter la compréhension, nous avons décidé de mettre des notes de A à E pour le CPU et pour la mémoire, et d’en faire une moyenne pour obtenir une note globale du service.</p><p>L’OKR pour les équipes consistait à monter sa note globale à un minimum de C pour tous les services associés à un périmètre. Nous l’avons appelé “Score Back” pour le différencier d’un autre OKR spécifique au Front (mais qui ne sera pas abordé ici).</p><p>Voici les résultats des périmètres pour mars 2022, au moment où nous commencions à avoir des données, par équipe et pour tous les environnements :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*v7kI4NzNIYldVfq3" /></figure><p>Nous avons fait adopter cet OKR au sein du domaine, et l’avons annoncé aux équipes concernées. Nous avons fait plusieurs communications à ce sujet, et les réactions étaient plutôt positives et enthousiastes, d’autant plus qu’on fournissait les outils nécessaires pour monitorer et que l’équipe d’ops du projet se tenait disponible pour accompagner et aider les équipes.</p><h3>Troisième étape : le travail des équipes</h3><p>Chaque équipe a donc pris le sujet de son côté, j’ai moi-même mis cela en place sur les produits dans mon périmètre. Voici le dashboard que nous avons à disposition. Une fois qu’on a sélectionné son périmètre et le(s) environnement(s) concerné(s), on obtient le score global, le score pour le CPU et celui pour la mémoire. Le score global est la moyenne des deux autres. Nous avions donc initialement une note de D en avril 2022.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*B5N-F-jNbAWF739q" /></figure><p>En termes de temps consacré à cette tâche, j’ai personnellement effectué ce travail sur 4 services, et il m’a fallu environ une journée pour modifier les valeurs et vérifier à chaque fois le comportement des serveurs dans le temps, et deux heures en commun avec un autre collègue.</p><p>Il était important de jouer nos tests de performance avec cette nouvelle configuration pour vérifier que le service tiendra la charge sans latence supplémentaire, ce qui est bien le cas pour nous.</p><p>Voici notre score de périmètre à l’heure actuelle :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SRmJ-k9jRR_eOqRB" /></figure><p>Comme vous pouvez le voir, nous sommes passés de D à A ! Niveau mémoire, nous tournons bien autour des 80%, ce qui était l’objectif. Par contre niveau CPU, nous ne sommes pas à 60%, et nous ne pourrons pas vraiment faire mieux : certains de nos services sont si peu consommateurs que les réduire davantage en ferait des services sous-taillés qui scalent au moindre appel ! Si on diminue la taille mais qu’on augmente le nombre de pods, c’est contre-productif en termes d’impact au final car on va multiplier une taille plus faible par un nombre plus important de services, et potentiellement allouer encore plus de ressources qu’avant !</p><p>Heureusement, nous affichons aussi dans le dashboard le nombre de pods et la latence, pour vérifier la tendance dans le temps. Elle doit être la même qu’avant le resizing, ce qui est le cas chez nous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TH1WSi4h0Tab46E_" /></figure><p>Voici les notes globales des équipes du domaine en octobre 2022 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/0*dAv2gczT-sTCC30P" /></figure><p>Sur le domaine global, nous avons gagné seulement 1 point et sommes encore en D. Mais quand on y regarde de plus près, certaines équipes ont fait des progrès très impressionnants ! Notamment une équipe qui est passée de 19 à 79 ! Mais certaines équipes n’ont pas participé, et leurs notes se sont même dégradées pour certaines. On est loin de respecter notre OKR qui était de passer toutes les équipes en C minimum.</p><p>Pour ceux qui se demandent pourquoi mon périmètre (Opus Search) n’a pas un A comme sur mon dashboard, c’est parce que nous sommes divisés en deux produits, et que je n’interviens que sur un seul des deux. Or le deuxième produit a un score de D qui fait grandement descendre notre moyenne. Il y a donc encore du travail à faire pour une partie de mon équipe ! Car ça ne doit pas être un acte ponctuel, mais une habitude à prendre et une surveillance qui se met en place dans le temps.</p><p>Malgré tout, notre grande fierté a été de voir des équipes qui ne faisaient pas partie de notre atelier et qui pourtant ont été convaincus par la démarche ! Ils se sont montrés moteurs et ont bien contribué sur leurs services.</p><h3>Conclusion</h3><p>Il est très dur de motiver des collègues (qu’ils soient développeurs, ops ou PO) à travailler et passer du temps sur ce sujet quand ils n’ont pas été préalablement sensibilisés à la question environnementale. J’ai donc pris conscience qu’avant de mettre en place des actions concrètes comme celles-ci, il faut d’abord préparer le terrain et sensibiliser les collègues.</p><p>C’est pourquoi j’ai décidé de monter chez SFEIR une communauté autour du Numérique Responsable, pour transmettre une autre vision de l’informatique, qui soit soutenable dans le temps. À l’heure où tous les secteurs doivent faire un effort pour diminuer leur impact, le numérique est au contraire en progression exponentielle, alors qu’il pourrait largement contribuer à réduire les émissions de gaz à effet de serre à hauteur de 20% (<a href="https://www.ipcc.ch/report/ar6/wg3/downloads/report/IPCC_AR6_WGIII_Full_Report.pdf">source GIEC</a> p.196 et <a href="https://systemtransformation-sdg.gesi.org/environmental-protection">source GeSI</a>). A nous de nous investir pour cette cause !</p><p>Je remercie aussi particulièrement Sylvain Lefranc, Etienne Adriansen et tous les collègues d’Adeo / Leroy Merlin qui ont participé avec moi à cette initiative !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae5e46c3793a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeshake/monitorer-cest-important-pour-diminuer-sa-consommation-de-ressources-ae5e46c3793a">Monitorer, c’est important pour diminuer sa consommation de ressources</a> was originally published in <a href="https://medium.com/codeshake">CodeShake</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>