<?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 Alex Burlacu on Medium]]></title>
        <description><![CDATA[Stories by Alex Burlacu on Medium]]></description>
        <link>https://medium.com/@alexburlacu1996?source=rss-dbb1c78b5aba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_3sH6VBD3nNJTpeN.jpg</url>
            <title>Stories by Alex Burlacu on Medium</title>
            <link>https://medium.com/@alexburlacu1996?source=rss-dbb1c78b5aba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:39:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexburlacu1996/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MLOps for independent research]]></title>
            <link>https://medium.com/@alexburlacu1996/mlops-for-independent-research-650c503b03b6?source=rss-dbb1c78b5aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/650c503b03b6</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Alex Burlacu]]></dc:creator>
            <pubDate>Thu, 12 Jan 2023 21:00:03 GMT</pubDate>
            <atom:updated>2023-01-31T11:57:38.938Z</atom:updated>
            <content:encoded><![CDATA[<p>On December 5th, I was presenting online at the <a href="https://www.meetup.com/mlops-belgium/events/289639571/">Belgium MLOps meetup in Ghent</a>. I thought more people would benefit from the content of that presentation and my experience in general. So, I decided also to have it as an article on my blog. Also, while working on that presentation, I found a few unexpected things, but later about it.</p><p>Oh, by the way, one of the best alternative titles was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iY7l8iZ5gjwUrWeByTIHaw.png" /><figcaption><em>I went with food | Image based on the slides by the author</em></figcaption></figure><h3>Prologue — Some context</h3><p>I believe it’s important to outline my main research driver:</p><blockquote><strong>I’m searching for methods to train strong neural networks from scratch with minimum annotated data. Ideally, with minimum data.</strong></blockquote><p>Why? Throughout my career, I had cases when data was scarce and expensive to acquire, and even a pre-trained model couldn’t help. So I had to create small bespoke models to tackle my problems. It was a huge pain, and I want to never go through that hell again and wish no one else would have to either.</p><p>Besides, sometimes, using a pre-trained model can be restrictive, depending on its license. Currently, the most relevant type of restrictive license for AI is <a href="https://bigscience.huggingface.co/blog/the-bigscience-rail-license">RAIL</a>. If you wonder why such licenses are restrictive and don’t want to dive into the legal aspects, here are a few good links.</p><ul><li><a href="https://blog.tidelift.com/evaluating-the-rail-license-family">Evaluating the RAIL license family</a></li><li><a href="https://www.reddit.com/r/StableDiffusion/comments/z8x4k3/the_changes_between_the_creativeml_open_railm/">A Reddit discussion about various RAIL variants and their implications</a></li><li><a href="https://www.youtube.com/watch?v=W5M-dvzpzSQ">The New AI Model Licenses have a Legal Loophole | Yannic Kilcher</a></li></ul><p>To form a more nuanced view of ML and licensing, see the two-part essay <a href="https://thegradient.pub/machine-learning-ethics-and-open-source-licensing/">by Christopher Moran on The Gradient</a>. We won’t dive any deeper in this rabbit hole, otherwise we’ll stray waaaaay too far from this blog’s scope.</p><p>So anyway, in the summer of 2021, I had a research internship at Université Paris Sorbonne Nord. I had my own research agenda, and my supervisor was super cool about it. My research project was about searching for more sample-efficient self-supervised learning techniques (SSL). I was working with images, but the method should be modality-agnostic.</p><p>The only downside, stemming from my not wanting to work on some existing, grant-covered project, was that I had no access to the necessary hardware.</p><p>But that’s alright. It is, isn’t it?</p><h3>You want to do some independent research</h3><p>How do you proceed?</p><h3>Solution: You buy a GPU.</h3><p>🪄🪄 Or better yet, you buy many GPUs. 🪄🪄</p><p>Problem solved.</p><p>Bye.</p><p>Hold on, seriously. How do you proceed? A good GPU machine will set you back a few thousand USD, even with the crypto boom somewhat behind.</p><p>Besides, my project was pretty short-term, so such an investment would be a net loss. And I’m not even counting the time I could spend on it playing games instead of training nets.</p><p>And if that wasn’t enough, depending on where you live and the quality of your electric wiring, such a machine will bring more pain and expenses than joy. Have you ever had your personal computer/workstation randomly shutdown due to excesive power consumption, maybe even taking down all your desk appliances with it too? I have.</p><h3>Free solution: Google Colab</h3><p>A popular alternative would be to use Google Colab. But not so fast. There are some limitations worth mentioning. Colab’s free tier will only allow you one GPU per account, you have to be mindful of the daily GPU quota (about 8 hours within 24h), and you can’t even run the same notebook in parallel even if it uses the CPU runtime.</p><p>What about Colab Pro/Pro+?</p><ol><li>You are not guaranteed any specific GPU. It could be a P100, a T4, or, once in a blue moon, a V100.</li><li>It’s still a single notebook. What if I want multiple?</li><li>What are “compute units”, and how much each GPU costs?</li></ol><p>If I am to pay for a service, I’d like to understand what I am paying for and how I’m billed. The opacity of Colab Pro and Pro+ is something I’m not sure I’d be willing to accept.</p><h3>The first (not so) good solution</h3><p>Given all that, I decided for my first variant to rely on Colab because it has free access to some GPU resources. With the saved money, I indulged myself with over 20 different kinds of cheese and too many macaron flavors to count. Vive le France!</p><p>To run more experiments and somehow circumvent the limited access to GPUs, I was using multiple Google accounts. Each account had a copy of the same Colab notebook and only had to change hyperparameters. If you wonder whether managing these identical-but-not-quite notebooks was a mess, I’ll answer you — it was an absolute mess.</p><p>As for my storage solution — I was storing model checkpoints in a shared Google Drive, and given that a blob’s storage consumption is associated with the account that created it and not where it’s stored, in practice, the amount of available Google Drive storage is doubled.</p><p>What about experiment tracking? — Google Sheets. Yes, it started to become a mess after the 3rd change of the experiment setup.</p><h3>Towards a better solution</h3><p>Of course, it was unsustainable and slow. And painful. And annoying. And somewhat challenging to replicate. So, I needed another solution, and by this time had outlined some constraints:</p><ul><li><strong>Constraint One</strong>: Messy environment, mainly Jupyter, with relatively limited code refactoring</li><li><strong>Constraint Two</strong>: Ideally, I wanted numerically replicable experiments</li><li><strong>Constraint Three</strong>: Also, experiments take a long time, so I want to run many at the same time</li><li><strong>Constraint Four</strong>: Cost is a big issue because the research is self-funded</li></ul><p>Based on these constraints, I had my core requirements: <strong>Cost-efficiency</strong>, <strong>Flexibility</strong>, and <strong>Reproducibility</strong>. I had some ideas in mind to accomplish these requirements, but I needed computing resources, so my next stop was to use a public cloud.</p><p>I picked GCP because I’m most familiar with it. I know about alternative GPU clouds like Paperspace or Linode, but <em>I felt</em> that they might be more expensive. Plus, again, I am most familiar with GCP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ozgNRrJaZn_qaR66.gif" /><figcaption><em>If you look long enough, you’ll hear the song | Image based on the slides by the author</em></figcaption></figure><p>Initially, I was provisioning stuff from the Web console. But it was tedious and error-prone, I like CLIs better, and I had Terraform and Ansible on my radar for a while.</p><h3>Core requirements: Cost-efficiency</h3><p>Based on this requirement, here are some decisions that stemmed from it.</p><ol><li>I needed the cheapest powerful machines — Preemptible VMs with GPUs</li><li>I also needed a simple way to quickly spin machines up and down so that I don’t forget anything running and I don’t waste time while setting up the environment — Terraform FTW, and Ansible too</li><li>I had a hunch that by using the most powerful machine and maximizing its usage, I would have the best price-performance ratio — thus, I chose A100 GPUs. To be absolutely honest, another driver for this decision was the coolness factor</li><li>I was running multiple experiments in parallel, as fast as possible — used Papermill for the hands-off launch of multiple notebook-based experiments. Occasionally was using tmux from the Jupyterlab terminal window, but it was a total pain.</li><li>Best cost-optimization is not to run things at all — so I used HPO to select what configurations to run. For HPO, I used Optuna.</li></ol><p>Of all the HPO tools out there, why did I choose Optuna, you may ask?</p><ul><li>I like their API. It integrates nicely with Python control structures, like for-loops, or if-elif-else.</li><li>Optuna uses a Bayesian HPO approach. Bayesian methods are pretty accurate and more hands-off than random search, allowing me to launch the hyperparameter search sweep and not think about narrowing down the search space.</li><li>A downside of Bayesian Optimization methods is that they are slow-ish / not very parallelizable. But that’s ok, my degree of parallelization is 2–5 parallel runs, and I didn’t intend to go multi-node.</li></ul><p>These decisions converged in the following architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADUG6J2hsBWQ8RsfoIuoaQ.png" /><figcaption><em>I’d get spanked by any half-decent security consultant for this architecture | Image based on the slides by the author</em></figcaption></figure><p>So, a lot of stuff going on here. Let me explain. On the left side, you’ll see the configuration files on the local machine, which are used to instantiate the infrastructure on the right side. Basically, it starts with terraform apply, which reads and executes all terraform files in the project, like this snippet below.</p><pre>terraform {<br>  required_providers {<br>    google = {<br>      source  = &quot;hashicorp/google&quot;<br>      version = &quot;3.5.0&quot;<br>    }<br>  }<br>}<br><br>provider &quot;google&quot; {<br>  credentials = file(&quot;project-name-some-id.json&quot;)<br><br>  project = &quot;project-name&quot;<br>  region  = &quot;${var.region}&quot;<br>  zone    = &quot;${var.region}-a&quot;<br>}<br><br><br>resource &quot;google_compute_instance&quot; &quot;vm_instance_worker&quot; {<br>  name         = &quot;gcp-vm-instance-worker&quot;<br>  machine_type = &quot;a2-highgpu-1g&quot;<br><br>  boot_disk {<br>    initialize_params {<br>      image = &quot;deeplearning-platform-release/pytorch-latest-cu110&quot;<br>      type  = &quot;pd-ssd&quot;<br>      size  = 150<br>    }<br>  }<br><br>  metadata = {<br>    ssh-keys              = &quot;username:${file(&quot;~/.ssh/sshkey.pub&quot;)}&quot;<br>    install-nvidia-driver = true<br>    proxy-mode            = &quot;project_editors&quot;<br>  }<br><br>  scheduling {<br>    automatic_restart   = false<br>    on_host_maintenance = &quot;TERMINATE&quot;<br>    preemptible         = true<br>  }<br>}<br><br>resource &quot;null_resource&quot; &quot;provision_worker&quot; {<br>  provisioner &quot;local-exec&quot; {<br>    command = &lt;&lt;EOF<br>                ANSIBLE_HOST_KEY_CHECKING=False ansible-playbook \<br>                -u username \<br>                -i &quot;${google_compute_instance.vm_instance_worker.network_interface.0.access_config.0.nat_ip},&quot; \<br>                --extra-vars &quot;tracker_uri=${google_compute_instance.vm_instance_tracker.network_interface.0.access_config.0.nat_ip}&quot; \<br>                ./config-compute.yml<br>            EOF<br>  }<br>}</pre><p>The .tf files use the GCP provisioner, and as such, they need a service account key ( credentials in provider &quot;google&quot;) to be able to provision resources like VMs, buckets, and networks.</p><p>Once the infrastructure provisioning part is done, the local-exec provisioner is triggered, which is responsible for running the Ansible playbook and configuring each provisioned VM. It installs drivers, sets env vars, and launches MLFlow or Jupyterlab as background processes. See an example Ansible playbook below.</p><pre>---<br>- hosts: all<br>  name: jupyter-install<br>  become: username<br><br>  tasks:<br>    - name: install nvidia drivers<br>      shell: sudo /opt/deeplearning/install-driver.sh<br><br>    - name: test nvidia drivers<br>      shell: /opt/conda/bin/python -c &#39;import torch; print(torch.cuda.is_available())&#39;<br>      register: nvidia_test<br><br>    - debug: msg=&quot;{{ nvidia_test.stdout }}&quot;<br><br>    - name: install mlflow<br>      shell: /opt/conda/bin/pip install mlflow==1.20.2 google-cloud-storage==1.42.3 optuna==2.10.0 papermill==2.3.3<br><br>    - name: launch jupyterlab<br>      environment:<br>        MLFLOW_TRACKING_URI: &#39;http://{{ tracker_uri }}:5000&#39;<br>        MLFLOW_S3_ENDPOINT_URL: gs://some_bucket_address<br>        PATH: /opt/conda/bin:{{ ansible_env.PATH}}<br>      shell: &quot;nohup /opt/conda/bin/jupyter lab --NotebookApp.token=some_token --ip 0.0.0.0 --no-browser &amp;&quot;</pre><p>I am provisioning two VMs, one for the experiment tracker and one for running experiments. I also need a firewall to allow TCP traffic on select ports, specifically 5000 (MLFlow), 8888 (JupyterLab), and 22 (SSH). Finally, I have a GCS bucket as the artifact repository for MLFlow.</p><p>Notice that my VMs receive a copy of my SSH public key. It’s necessary to allow SSH connections from my local machine because Ansible uses SSH to connect to its targets.</p><h3>Core requirements: Flexibility and Parallelism</h3><p>Research is quite messy. I try to fix the mess by extracting common code, maybe writing some utils, but sometimes I prioritize running experiments. As mentioned, I was using Jupyter and Optuna. To make them work nicely together, I used Papermill.</p><p>Papermill allows for parametrized, programmatic execution of Jupyter notebooks. Let me explain with a table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sS-LK8C2i55UMqaXEKWSsA.png" /></figure><p>So, in my setup a Python CLI program with Optuna and Papermill is used to launch multiple parallel experiments, something like this:</p><p>Or, if you prefer a diagram to a code snippet, here’s one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*ynA5aducn_58s4iCskBwkA.png" /><figcaption><em>I’d get spanked by any half-decent UML afficionado for this diagram | Image based on the slides by the author</em></figcaption></figure><h3>Core requirements: Reproducibility</h3><p>I have suffered enough in the industry from unreplicable training runs, so I needed to eliminate this issue in my research.</p><p>I needed <strong>tracking</strong> and <strong>determinism</strong>.</p><p>I won’t dive deep into the matter of running reproducible experiments. But I’ll allow myself to repeat some stuff. You can find a more detailed overview <a href="https://alexandruburlacu.github.io/posts/2022-11-22-mlops-fable">here</a>, in the The takeaways &gt; Replicable experiments part.</p><p>The deterministic experiments checklist (for PyTorch):</p><ul><li>The most important thing you can do is to seed your pseudo-random number generators (Python, Numpy, PyTorch, CUDA), aka PRNGs.</li><li>Be reasonable about (non-)determinism: Calling torch.use_deterministic_algorithms() is a Nope for me because <a href="https://pytorch.org/docs/stable/notes/randomness.html#avoiding-nondeterministic-algorithms">it will throw erros</a> when calling .backward() for some layers. On the other hand, setting torch.backends.cudnn.{benchmark,deterministic} properties is fine; they won&#39;t throw errors.</li><li>Special considerations about parallel data loaders, specifically for PyTorch users, don’t forget to also seed them in each of your DataLoader workers, like this:</li></ul><pre>def seed_worker(worker_id):<br>    worker_seed = torch.initial_seed() % 2**32<br>    np.random.seed(worker_seed)<br>    random.seed(worker_seed)<br><br>g = torch.Generator()<br>g.manual_seed(0) <br>dl = DataLoader(train_dataset, batch_size=batch_size, num_workers=num_workers, <br>                worker_init_fn=seed_worker, generator=g)</pre><p>That’s kind of it with the determinism part. How should I handle my experiment tracking infra?</p><ul><li>I need a minimal, dedicated, non-preemptible VM (n1-standard-2 works fine) because I don&#39;t want my tracking server preempted without first having a DB backup on my laptop, and implementing a half-decent backup script wasn&#39;t something I wanted to do</li><li>The experiment tracking server is a self-hosted MLFlow; I am quite familiar with it</li><li>The tracking database is SQLite. SQLite, being basically a single file, allows me to scp it to my local machine when done working and load it with Terraform file-provisioner on startup</li><li>All my artifacts are checkpointed to GCS, or rather, I’m using GCS as an artifact repository for MLFlow</li></ul><p>My tracking strategy:</p><ul><li>Track all modifiable hyper-parameters</li><li>During fine-tuning, track loss, top-1 and top-5 accuracy on both training and validation splits</li><li>During pre-training, only track loss</li><li>No need to track data because I use standard datasets like CIFAR100 or STL10</li><li>Based on my previous experience, I find it quite annoying working with nested runs, so I don’t use those</li><li>I created a new experiment on qualitative/untracked change (a different dataset, changed pre-processing code, a different SSL pre-training method)</li></ul><p>Some of it is also explained in detail in that same article referenced above ( <a href="https://alexandruburlacu.github.io/posts/2022-11-22-mlops-fable">here it is</a>, for your convenience), in the The takeaways &gt; Experiment tracking part.</p><p>Tracking all this stuff with MLFlow, also allows me to compare runs with parallel coordinate plots, which is the best way to look at your hyperparameter optimization runs, IMO!</p><p>By the way, if you’re not familiar with MLFlow, <a href="https://mlflow.org/docs/latest/quickstart.html">here’s a link</a>.</p><h3>Was it all worth it?</h3><p><strong>TL;DR:</strong> Yes, let me show you why.</p><p>First, let’s assume the following setup: ResNet50, pre-training (PT) + fine-tuning (FT), for 10 epochs, with batch sizes 512 (PT) and 4096 (FT).</p><p>Let’s first do some benchmarks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1tdftTXwd3w3NuwcwZZ3TA.png" /></figure><p>Let’s do some simple math with the same setup.</p><p>A model takes 7.2GB of VRAM. Except for A100, <strong>it uses 8.4GB</strong> for the same setup. No idea why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9mKxDAvPLHrfb94QpHrDg.png" /></figure><p>Let’s do some more math.</p><p>GCP billed my A2 instance for 44h. Meaning I was running experiments for almost 44h. Of course, I was launching those experiments manually with my script, and there was some idle time, but it was minimal. Anyway, 44 billed hours on A2. For the same volume of work with a T4 GPU, I’d get billed for…</p><p>44h x (5 runs / 2 runs) x 2.2 speedup == 240h w/ T4</p><p>… for 240 hours. That is a lot more, even if T4 GPUs are considerably cheaper!</p><p>Hold on, 5 parallel runs on A100 are possible when using 448 batch size, not 512. That’s almost a 10% smaller batch size, so the training should take roughly 10% more time in this setting. Well, based on a few experiments, changing the batch size from 512 to 448 results in just 3–5% pre-training slowdown, plus there’s the fine-tuning part, which we don’t alter, so all in all, it’s still going to be roughly 2.2x faster than T4.</p><p>Anyway, <strong>for that 44h I paid 48 USD</strong>.</p><p>Before we move forward, let’s make one thing clear: based on the information we have so far, <strong>Colab Pro/Pro+ is not worth it</strong>, compared with my setup, at least.</p><p>Colab Pro+ is 43 EUR/month. It does not guarantee the accelerator type, uses opaque “compute units” payment, and 200+h on T4 will consume those units in no time.</p><p>Let’s do some more math. How much would I have to pay for 240h of using a T4 GPU, with a decent VM instance, like an n1-standard-8?</p><p>240h x 3.15 USD/h / 17.381h = 43.5 USD</p><p>Based on these calculations, I paid a <strong>~5 USD premium for a ~6x speedup</strong>. Totally worth it.</p><p>In fact, I would have paid more than 43 USD for 240h on T4. Because it seems the <strong>network is 1.8–2x slower</strong> on N1 instances, resulting in a long time to download the necessary dataset after each provisioning. A few test runs of A2 and N1-standard-8 instances averaged 9m 30s and 19m, respectively, to download the CIFAR100. On a side note, I could have kept copies of the datasets in a GCS bucket, but I didn’t. Maybe I thought it would cost a little too much for its worth, and I’d be annoyed by it. But what’s done is done. Given that I would need to run a T4 instance for considerably longer to do the same amount of work, I’d also have to provision my infrastructure more often, leading to more times I have to wait until my CIFAR100 or STL10 datasets are downloaded. That would definitely result in more than 43 USD.</p><p>So A2 is both faster <strong>and</strong> cheaper in my setup. I wish my gut feeling would always work this well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*n5TOMZJeGvULnGVqBd7HIQ.png" /><figcaption><em>It might not seem like it, but A100 is the better deal | Image based on the slides by the author</em></figcaption></figure><p>So, I hope you can see that using the most expensive single GPU setup on GCP turned out to be the best decision. It costs roughly the same or even less than using the seemingly most cost-efficient one while being soooooo much faster. Even if running an A2 instance was 2x more expensive than N1 with T4 GPU, I’d still take that expense to be able to do 240+h of work in 44h.</p><h3>Future directions</h3><p>It may seem like I have my setup optimized to the limit. But it has room for improvement. I’d say the room is the size of a nice large kitchen with an isle in the middle and a terrace for summer dining.</p><p>The most impactful missed opportunity is using Mixed Precision. Surprisingly, I wasn’t using it. Maybe because of my old trauma installing APEX from scratch. But now <a href="https://pytorch.org/blog/accelerating-training-on-nvidia-gpus-with-pytorch-automatic-mixed-precision/">it’s pretty easy</a>, or so <a href="https://discuss.pytorch.org/t/torch-cuda-amp-vs-nvidia-apex/74994/9">they say</a>. Thankfully A100 GPUs have a magic trick, which seems to be enabled by default on PyTorch. This trick is called the TF32 float number representation. It’s a reduced-precision floating point number representation, which can be run on Nvidia’s Tensor Cores and allow for a transparent and easy switch to FP32 when necessary.</p><p>A trickier thing I’d like to do is to optimize the data loading. CPUs are underutilized in my setup. Given that my datasets are all standard, I’m considering using <a href="https://ffcv.io/">FFCV</a>.</p><p>A few more niche things, with lower priority than the stuff described above:</p><ul><li>Threaded checkpoint saving because it’s in the same thread as training and takes a few seconds at the end of each epoch.</li><li>Try MosaicML for additional gains. I’m thinking to specifically the <a href="https://docs.mosaicml.com/en/latest/method_cards/channels_last.html">ChannelsLast</a> and <a href="https://docs.mosaicml.com/en/latest/method_cards/progressive_resizing.html">ProgressiveResizing</a>, but also PyTorch’s <a href="https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.OneCycleLR.html">OneCycleLR</a>.</li><li>Automatic restart from checkpoints (GCP MIGs + startup scripts) for longer training runs.</li></ul><h3>Not my case, for now:</h3><ul><li>Model/Tensor/Pipeline parallelism — largest model is ResNet101</li><li>Huge datasets — I’m not even planning to use ImageNet</li><li>Collaboration — I was the only one working on it and only discussed the results with my supervisor</li></ul><h3>A few takeaways</h3><ol><li><strong><em>Automate stuff</em></strong> — I’m sure you’ll be glad you did when you can spin up a complete work setup in minutes with a single click. And shut it down with the same ease. Not to mention leaving an instance running will be a thing of the past.</li><li><strong><em>Track your experiments</em></strong> — If you want to reproduce your excellent results or figure out what other tricks to try, keeping a log of what you did and how it went is essential.</li><li><strong><em>Invest in maximizing resource utilization</em></strong> — Having powerful hardware means nothing if it stays idle or is underutilized. Make sure you feed it enough work, so your investment breaks even faster.</li><li><strong><em>Most powerful hardware can be the most cost-effective</em></strong> — That said, using the newest, most advanced, and most powerful hardware can be not only fun but also cost-effective. And finally,</li><li><strong><em>Moving faster costs money</em></strong> — but it’s worth it.</li></ol><h3>P.S.</h3><p>“Eventually I will buy a GPU”, from the Director of “I will stop binge-playing PS5” and “I promise I’ll go to the gym consistently”.</p><p><em>Originally published at </em><a href="https://alexandruburlacu.github.io/posts/2023-01-12-mlops-for-independent-research"><em>https://alexandruburlacu.github.io</em></a><em> on January 12, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=650c503b03b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A fable about MLOps… and broken dreams]]></title>
            <link>https://medium.com/@alexburlacu1996/a-fable-about-mlops-and-broken-dreams-6e8e72652936?source=rss-dbb1c78b5aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e8e72652936</guid>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Alex Burlacu]]></dc:creator>
            <pubDate>Mon, 21 Nov 2022 22:12:34 GMT</pubDate>
            <atom:updated>2022-11-28T12:53:43.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LjUFiiwhOdoBaAoZx64PAg.png" /><figcaption><em>I’m sure you can figure out this reference | Image based on the slides by the author</em></figcaption></figure><p><em>Originally published at </em><a href="https://alexandruburlacu.github.io/posts/2022-11-22-mlops-fable"><em>https://alexandruburlacu.github.io</em></a><em> on November 21, 2022.</em></p><p>For a while, I was considering presenting more often at conferences and meetups. I was postponing it for quite some time, but this summer, I thought, “No more!” and applied to be a speaker at the <a href="https://mdc.md/">Moldova Developer Conference</a>. And I was accepted with a talk about MLOps! I thought I’d make the talk a kind of fairytale/fable story with blackjack and easter eggs. Fast forward a few weeks ago, in the first half of November, I was presenting at the conference, and because not everyone could attend it, I also decided to make a blog post on the topic I was presenting.</p><h3>Intro</h3><p>This article is divided into two parts, <em>The Story</em> and <em>The Takeaways</em>. Let’s start with the story.</p><h3>The fable about MLOps…</h3><p>Note that all the characters in the story are fictional. So is the setting in which the story happens. They are not inspired by concrete people or organizations but rather distilled from my many experiences and a few industry stories. Alright, story time.</p><h3>Act 1: We need a PoC to prove ML is a good investment</h3><p>In an alternate reality, or maybe just another time and place, there was a company — <strong>Lupine Corp.</strong> Lupine Corp. is a logistics company with a very long history, dating back since the revolution. However, no one remembers which one, could be the French, or the Bolshevik. Like any respectable company, they have a set of values and principles they abide by. One of their core tenets is to be <em>cost-efficient</em>. The other one is — <em>no unnecessary risks</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMjNvgy73wS-sSyYi_7PtQ.png" /><figcaption><em>They were hyped by Hadoop, in 2020. I mean… | Image based on the slides by the author</em></figcaption></figure><p>Lupine Corp. are also reputable for doing their due diligence. So they knew that before launching their ML initiative, they needed to have their prerequisites in place.</p><ol><li>They made sure to know their success metrics, meaning they established some KPIs and a way to report and track those.</li><li>They also had their data easily accessible and discoverable, not just existing somewhere in their databases. They knew this would be very important for the data scientists they will hire.</li><li>Finally, the leadership knew that Data Science and ML are much more unpredictable than traditional software engineering, and they adjusted their expectations accordingly.</li></ol><blockquote><em>Side note: With only these 3 points, Lupine Corp. were so much better prepared for ML than the majority of the companies out there.</em></blockquote><p>Lupine Corp. imposed some budget limitations because of the unpredictable nature of ML projects, so they only hired two people:</p><ul><li><strong>Nifel Nifenson</strong> (image below, left), who previously worked for two years as a lone Data Scientist in a small company</li><li><strong>Nafaela Nafarri, PhD</strong> (image below, right), a Senior Data Scientist with six years of experience</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2jtkEMW2FMLNSC5t_H3vQ.png" /><figcaption><em>Dream team. Left — Alexander the Great in the Battle of Issus Mosaic. Right — Pallas Athena by Rembrandt | Image based on the slides by the author</em></figcaption></figure><p>Nifel Nifenson is a very results-oriented guy. One could say he’s the (rough) embodiment of the Lean Startup philosophy. Nafaela Nafari has a strong analytical mind. When Lupine Corp. asked them to deliver some results ASAP, they did just that and then some more. The results were very promising and done in record time. Senior management was ecstatic, and more use cases were in discussion.</p><h3>Act 2: Expanding the team. Signs of trouble.</h3><p>As all things in business and life, with larger scale, cracks became more apparent.</p><p>Nifel, Nafaela, and the new team members got along very well. It was a very nice team to work with. Everyone was professional and friendly. Yet somehow, the team’s velocity (as per Scrum, or “throughput” as per Kanban) wasn’t scaling as expected. It even started to go down after a few months. More people and more time were required to complete the same work Nifel and Nafaela had done a few months before. But why was this happening?</p><p>There are many reasons why. For example, many promising experiments couldn’t be replicated, even with all the notes the team took. Also, they observed increased complaints from some of the users of their deployed models. The first few weeks after the models were put in production, everyone was happy, but in time more and more bad feedback was received.</p><p>And if all that wasn’t enough, some of those productionized use cases started to receive a lot of traffic, sometimes up to two thousand concurrent users. They decided to horizontally scale their existing docker containers to serve them all. It wasn’t resource-efficient. It was hard to manage. And the latency SLAs were thrown out of the window with worrying regularity…</p><h3>Act 3: Bringing the big guns</h3><p>Lupine Corp. was upset with the prospect of their ML initiative imploding, so they hired <strong>Nuf Nufelman</strong> as the new Head of Data Science.</p><p>Previously he worked as a lead data scientist at a big non-FAANG company, similar in structure to Lupine Corp. but quite different culturally. His previous employer was basically a “throw money at the problem” type of company, and Nuf was shaped by this mentality too. Nuf was also a great DevOps believer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O85Saz8Yyx8B5ES9FTJ-7Q.png" /><figcaption><em>Nuf was born and raised in Odessa, but lost his way, a bit | Zeus’ statue at Versaille | Image based on the slides by the author</em></figcaption></figure><p>He understood that the problem Nifel’s and Nafaela’s team faced was a replicability problem.</p><p>… and a retraining problem.</p><p>….. and a scalability problem.</p><p>They needed a well-structured process to research, develop, evaluate and productionize their work consistently.</p><p>In a meeting with the higher-ups, Nuf told them that if Lupine Corp. was serious about their ML intentions, they had to adopt MLOps, <em>wholly and without question</em>. They accepted.</p><p>To streamline adoption, Nuf suggested they don’t develop all the tools in-house but instead pay for an ML-platform-as-a-service (MLPaaS) by All-You-Need-And-A-Kitchen-Sink ($AYN). All-You-Need-And-A-Kitchen-Sink is a recently IPO-ed startup that <em>“solves all the MLOps pains”</em>.</p><p>Surprisingly, it worked.</p><p>Most of the past problems went away.</p><p>But a lot of the internal processes still needed adjustments. Because it was quite a generic tool, a lot of glue code had to be written. Also, people didn’t like using it. The learning curve was steep. And some of the API design choices and documentation could have been more pleasant to work with.</p><p>And did I mention the Enterprise tier was a-seed-investment-grant-per-month expensive? If you ever complain about AWS bills, this one was probably even worse, but I digress.</p><h3>Act 4: Burning cash and its consequences</h3><p>The ML and Data Science initiative continued to grow at Lupine Corp. They hired more people and sometimes heard more complaints about their ML platform. It was slightly annoying but not that important for the upper management. They had different pains.</p><p>How could they ever be content when this new MLPaaS gizmo was burning cash like crazy? And recall their main tenets. Increasing their operational efficiency was a recurring topic during their meetings.</p><p>But as anything in old, large corporations, it was a lot of talking and not so much doing.</p><p>And then, the earnings call day came…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mDC2H2ea9ldXRWJb2tF5mg.png" /><figcaption><em>That day rang both the telephones and hell’s bells | Christ in Limbo by a Follower of Jheronimus Bosch</em></figcaption></figure><p>Financials showed Lupine was burning a lot more cash than its competitors. They were no startup or scaleup. This was showing financial recklessness. Shareholders didn’t like it. Neither did the stock market. Their stock plummeted 20% in a week. Something between Meta and Netflix.</p><p>To alleviate the issue, Lupine Corp. decided to optimize its operations. Now for real.</p><p>They laid off many employees working on non-critical aspects of the business. Whether possible, they terminated said initiatives too.</p><p>It was clear one of the main reasons they were burning money was their ML platform. Obviously, the ML initiative was impacted. Nafaela and Nuf stayed, but Nifel was laid off. Layoff decisions were based on tenure and seniority.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yw4dTnUq8PlQaz6XW8-Gww.png" /><figcaption><em>Poor Nifel | Image based on the slides by the author</em></figcaption></figure><p>Cutting costs worked. But it wasn’t a good long-term strategy, and Lupine Corp. knew this all too well. They needed to optimize their OpEx. So now, Lupine Corp. was looking for someone who could help. And they found someone. Someone,</p><p>Meet <strong>Nahum Nahreba</strong>.</p><p>He’s a platform engineer. He is known for thinking from first principles and building nimble, scalable solutions. He’s something of a Jeff Dean, although he might not be able <a href="http://www.neohope.com/2014/04/24/jeff-dean-facts/">to shift bits from one computer to the other</a>. He helped scale a few startups. It wasn’t the first time he had to work on ML platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-v7U2yTgGY7uBkxJR13kg.png" /><figcaption><em>Trully a legend | Image based on the slides by the author</em></figcaption></figure><p><strong>TL;DR:</strong> He came. He saw. He solved the mess.</p><p>He persuaded Lupine Corp. to greenlight a major refactoring of the ML platform, pruning it of many unnecessary features, reducing the bill, and implementing a few features and tools internally, with a specific focus on developer experience and integration with the rest of the company’s infrastructure. It’s a fable, not a technical report, so I won’t dive deep into how he did it.</p><p>And so they lived relatively happily until Lupine Corp. management discovered IoT…</p><p>The end.</p><h3>The takeaways</h3><p>So, how could Lupine Corp. avoid this mess? And how can other companies like them avoid it too?</p><p>First things first, we need to give credit where credit’s due. This fictional company did a lot of stuff others don’t, so their success chances were already pretty high. They knew what success looked like for them, they had their data available and discoverable, and they had a correct mindset about this initiative. In my practice, most companies don’t have that.</p><p>I would argue one of the reasons Lupine Corp. had such fun hard times was a well-known quote:</p><blockquote>“Premature optimization is the root of all evil”<em> — Donald Knuth</em></blockquote><p>… as cited by Nifel Nifelson, and most SWEs. Nifel, in this story, had somewhat more software engineering experience, and it was his responsibility to use an SWE mindset when starting their ML journey. He knew by heart the quote above, the KISS principle, and many others. But he also, like most of us, didn’t quite understand the nuances behind said quotes. Nifel treated MLOps as overengineering. Under management’s tight deadline and pressure to show good results and prove himself a specialist, he created good ML models but not-so-good ML systems.</p><p>By the way, the “fuller” quote sounds like this:</p><blockquote>“We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.”</blockquote><p>If only Nifel knew it like this… <strong>So the takeaway #1: Start early with MLOps</strong>.</p><p>Nifel’s (counter-)example shows we must consider adopting MLOps practices early on. But it’s not so simple either.</p><p>Software and data people are an enthusiastic bunch. We want to use many tools to solve many problems. We’re very prone to over-engineering. If we were rockstars, I think this tendency towards abuse would have manifested a bit differently. Thankfully we aren’t rockstars.</p><blockquote><em>By the way, it’s not my first piece on picking tools, so you’d like to check out the </em><a href="https://alexandruburlacu.github.io/posts/2022-06-18-choosing-a-tool"><em>other article about it</em></a><em>.</em></blockquote><p>When starting with MLOps, we can be overwhelmed by multiple tools, terms, concepts, and practices. We’ll hear from every corner how crucial it is to have pipeline orchestration, 17 types of ML and data tests, three types of observability, feature stores, model stores, metadata stores, stores to store stores… alright, I’m exaggerating now, but you got the idea.</p><p>You don’t need all this tooling, not from the start, even if it comes all bundled together, like AWS, GCP, or Azure offerings.</p><p>Using a fully-featured MLOps solution from the beginning usually doesn’t work.</p><p>Either because it’s too generic. And/or there are too many upfront costs. Also, it takes a lot of work to onboard your users.</p><p>Going head-first into MLOps is a bad idea for most of the same reasons.</p><p>What you do need in the beginning is to…</p><ul><li>quickly find and access your data</li><li>seed that model training code</li><li>record your experiment configuration</li></ul><p>Then make sure to</p><ul><li>easily deploy your models</li><li>have some tests</li></ul><p>The rest will come after. <strong>All that said, the takeaway #2: Start small with MLOps</strong>.</p><p>Now onto more technical advice.</p><h3>Simple data collection and discovery</h3><p>Lupine Corp had this, but I’m sure you don’t. So, what should you do? First, you need to understand <em>The Why?</em> We’re past the Big Data hype by almost ten years. Organizations now have lots of data… but it takes a lot of work to use it properly. It wouldn’t be an exaggeration to say that for the absolute majority of the projects I worked on, accessing datasets was my second most annoying problem. The first one was the lack of a baseline and success metrics. As I said, Lupine Corp. was in fact really good. Your company probably isn’t.</p><p>Alright, we know what “data collection” is. ETL pipelines and all that. Or a few scripts running as CRON jobs, dumping files into an S3 bucket. But what about data discovery?</p><p>A short googling session will reveal terms and technologies like data governance, data lineage, Amundsen from Lyft, Apache Atlas, Google Data Catalog… yeah, no. Not yet.</p><p>Have a shared spreadsheet. In it, each row is about a dataset. Name, short description, update frequency, contact person, and location in the object store. That’s it, at least in the beginning.</p><p>Do this, and your data scientists and ML engineers will be happy as hell. You’ll get recruits just by word of mouth.</p><p>Here’s a wacky architectural diagram for what you need for <strong>simple</strong> data collection and discovery.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjUMNEcbnCmhAcH9a8GbFA.png" /><figcaption><em>A few backup and automation scripts running on a schedule, S3 or something similar, a spreadsheet. If you can’t do this, please don’t hire ML engineers, you’ll just waste money. | Image based on the slides by the author</em></figcaption></figure><p><strong>Pro tip:</strong> when you dump your raw data into those buckets, don’t override your old data. You’ll see why later.</p><h3>Replicable experiments</h3><p>This one requires a few steps, but they’re relatively straightforward. First, you need to seed your pseudo-random number generators, aka PRNGs.</p><p>Not everyone knows this, or maybe not explicitly, but ML code is full of randomness. We need to initialize the parameters of our ML models — we use some random distributions. We also need to shuffle our data — also randomness. This is trivial for a machine learning practitioner. What is less trivial is how this randomness is “created”. You see, randomness in computers is not entirely random.</p><p><strong>(Optional Paragraph)</strong> We use <a href="https://www.cryptosys.net/rng_algorithms.html">special algorithms</a>, based on stuff like chaos theory, which given an initial state, or a seed, and a set of usually recurrent rules, will generate a sequence of values. The rules are fixed, so the algorithm is deterministic, but the values are chaotic, meaning there’s no discernable pattern. Now, the seed value, the initial state used in these PRNGs is usually a genuinely random number, it can be the exact current temperature of the CPU, the clock drift between multiple CPU cores, or some other value that is naturally random. But you can manually provide the initial state, and thus when running the same sequence of operations multiple times, get the same sequence of values.</p><p>Back to our business. We can seed, or manually provide the initial states for our PRNGs so that running the same code will give us the same results — same models, same performance.</p><p>This is super important because if we can get the same results, we can properly validate and compare ML models and pick the best ones.</p><p>Python ML code has multiple sources of randomness, which can, and should, be seeded. This is because most numerical libraries in Python are written in C/C++/Fortran, and Python is a convenient wrapper to access these routines.</p><p>But there are a few more things between you and numerically replicable experiments besides PRNGs.</p><p>cuDNN is also standing in the way. cuDNN is NVidia’s low-level set of primitives for deep learning. It has multiple GPU-optimized implementations for convolutions, pooling, linear layers, various activation functions, and so on. Now, cuDNN has a clever way of achieving maximum performance on different hardware for various scenarios. It tests multiple implementations of the same algorithm <em>at the start of the program</em> and picks the fastest one. <a href="https://discuss.pytorch.org/t/what-is-the-differenc-between-cudnn-deterministic-and-cudnn-benchmark/38054/2">This selection <em>can</em> be non-deterministic (read random)</a>. Why? I am not sure, but as far as I understood, its heuristics might behave differently if there’s anything else running on the GPU. To disable this behavior, one has to set the torch.backends.cudnn.benchmark = False. To my knowledge, there are also a <a href="https://docs.nvidia.com/deeplearning/cudnn/developer-guide/index.html#reproducibility">few other sources of randomness in cuDNN</a>, and you can disable (some) these by setting torch.backends.cudnn.deterministic = True. And if you&#39;re interested in finding out more on how to run replicable PyTorch experiments, <a href="https://pytorch.org/docs/stable/notes/randomness.html">check out this page from the docs</a>. And if you&#39;re not, search if there are similar behaviors in your favorite framework.</p><p>Finally, most of the time, ML algorithms will try to take advantage of modern multi-core CPUs, and when designing replicable experiments, one has to think about it too.</p><pre>import random, os<br>import numpy as np<br>import torch<br><br>random.seed(seed)<br>np.random.seed(seed)<br>torch.manual_seed(seed)<br>torch.cuda.manual_seed(seed)<br>torch.backends.cudnn.deterministic = True<br>torch.backends.cudnn.benchmark = False<br><br>def seed_worker(worker_id):<br>    worker_seed = torch.initial_seed() % 2**32<br>    np.random.seed(worker_seed)<br>    random.seed(worker_seed)<br><br>g = torch.Generator()<br>g.manual_seed(0) <br>dl = DataLoader(train_dataset, batch_size=batch_size, num_workers=num_workers, <br>                worker_init_fn=seed_worker, generator=g)</pre><p><strong>Pro tip:</strong> when testing a machine learning model configuration, run it multiple times using different seed values. It will reduce the chance that you’re just lucky.</p><p>But to replicate experiments, one needs to know all their parameters, which brings us to the next part…</p><h3>Experiment tracking</h3><p>Just try to track as much as possible. I do. And it helped me a great deal. If you are ok with managing your infra, use <a href="https://alexandruburlacu.github.io/posts/mlflow.org">MLFlow</a>. If you would rather pay for a good managed solution, <a href="https://alexandruburlacu.github.io/posts/neptune.ai">Neptune.ai</a> and <a href="https://alexandruburlacu.github.io/posts/wandb.ai">Weights and Biases</a> are very nice.</p><pre>import mlflow<br>from mlflow.models.signature import infer_signature<br><br>with mlflow.start_run():<br>    mlflow.log_param(&quot;batch_size&quot;, 32)<br>    # Metrics can be updated throughout the run<br>    mlflow.log_metric(&quot;accuracy&quot;, 0.973)<br>    mlflow.log_metric(&quot;accuracy&quot;, 0.981)<br><br>    with open(&quot;outputs/test.txt&quot;, &quot;w&quot;) as f:<br>        f.write(&quot;hello world!&quot;)<br><br>    mlflow.log_artifacts(&quot;outputs&quot;)<br><br>    model_signature = infer_signature(example_inputs, model.predict(example_inputs))<br>    mlflow.sklearn.log_model(model, artifact_path=&quot;./sklearn-model&quot;, <br>                             registered_model_name=&quot;sklearn-rf-reg-model&quot;,<br>                             signature=model_signature)</pre><p><strong>Pro tip 1:</strong> For maximum benefit, group similar algorithms together. It will make it easier to compare those with stuff like <a href="https://ai.facebook.com/blog/hiplot-high-dimensional-interactive-plots-made-easy/">parallel coordinate plots</a>.</p><p><strong>Pro tip 2:</strong> Also, try to track and version all your data. Either with DVC or something else. That’s why you shouldn’t override the raw data in the buckets. Because if you do override it, you won’t be able to replicate the results of your experiments.</p><p>So you have a trained ML model. You can also fully replicate it. Now what?</p><h3>ML Serving</h3><p>You need to deploy and serve it somehow! How? Use docker and an app server! Consider Ray Serve, BentoML, or Seldon if you care about SLAs. These are specialized solutions that provide impactful features like adaptive batching, model pooling, and so on. If you care much about SLAs, try Triton Inference Server from NVidia. If you want to dive deeper into details, <a href="https://alexandruburlacu.github.io/posts/2022-09-25-neptuneai-ml-serving">read my blog post on the topic</a>.</p><h3>ML Tests</h3><p>What about tests? ML code is still code. So it needs tests. ML testing is a big and hairy problem. I promise I will eventually write some article about it, but for now, think about this problem like this:</p><p>You need to have two types of tests,</p><ul><li>Behavioral tests, which will measure predictions. These can become your regression suite, where you add various edge cases on which you don’t want to fail ever again</li><li>Unit/Integration tests, which will measure training, serving, and preprocessing code correctness. Stuff like “The model should reduce its loss after one iteration” or “The shape of the output should be [x,y,z] given that the input shape was [x,m,n]” and so on. These will spot bugs in your implementation.</li></ul><p>Depending on your application domain, here are a few links to help you with ML testing.</p><ul><li><a href="https://docs.deepchecks.com/stable/getting-started/welcome.html">Deepchecks library</a></li><li><a href="https://neptune.ai/blog/ml-model-testing-teams-share-how-they-test-models">ML Model Testing: 4 Teams Share How They Test Their Models | Neptune.ai Blog</a></li><li><a href="https://applyingml.com/resources/testing-ml/">Machine Learning in Production — Testing | ApplyingML</a></li><li><a href="https://madewithml.com/courses/mlops/testing/#models">Made With ML Testing Machine Learning Systems: Code, Data and Models</a></li><li><a href="https://www.jeremyjordan.me/testing-ml/">Effective testing for machine learning systems | By Jeremy Jordan</a></li></ul><h3>CI/CD</h3><p>If you have done everything until this point, having CI/CD should be easy. Kudos for triggering conditional steps for retraining if the training/model code changes. The conditional build behavior can be implemented with either something like dvc repro + some caching between runs or clever git diff manipulations.</p><pre># not the most production ready hack, but maybe it will help you<br>...<br>jobs:<br>  check:<br>    runs-on: ubuntu-20.04<br>    outputs:<br>      DIFFS: $<br>    steps:<br>      - uses: actions/checkout@v3<br>        with:<br>          fetch-depth: 0 # actually will need some adjustments<br>          # fetch only as many as necessary: https://github.com/actions/checkout/issues/438<br>      - name: Last good run commit<br>        run: |<br>          curl -s \<br>          -H &quot;Accept: application/vnd.github+json&quot; \<br>          -H &quot;Authorization: token ${{ secrets.GITHUB_TOKEN }}&quot; \<br>          https://api.github.com/repos/{{ USER }}/{{ REPO_NAME }}/actions/workflows/training-trigger.yml/runs?status=success | jq \<br>          -r &quot;.workflow_runs[0].head_commit.id&quot; &gt; last_good_commit.txt<br>      - name: Show and set DIFFS<br>        id: diffs<br>        run: |<br>          DIFFS=$(git diff HEAD $(cat last_good_commit.txt) --name-only | tr &#39;\n&#39; &#39; &#39;)<br>          echo &quot;::set-output name=DIFFS::$DIFFS&quot;<br>          echo $DIFFS<br><br>  train:<br>    needs: check<br>    if: contains(needs.check.outputs.DIFFS, &#39;train.py&#39;)<br>    uses: {{ USER }}/{{ REPO_NAME }}/.github/workflows/training.yml@master</pre><p>One important thing to note is somewhat related to CI. ML projects tend to have a naturally tight relation between EDA, data processing, training, and serving code. As a result, I highly recommend designing ML projects as monorepos and adopting monorepo-related practices and patterns for building, versioning, and code compatibility.</p><h3>Epilogue</h3><p>All the advice above is focused on simplicity. You must understand that the solutions I suggest have a very clear scope. These are solutions you should only consider at <strong>the beginning</strong> of your MLOps journey.</p><p>Let me make it simpler with a table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmIgr_9SBhP-THPw1HGN5w.png" /><figcaption>Table by author</figcaption></figure><p>These recipes are <strong>Maximum ROI — Minimum Effort</strong> solutions to get you started. Eventually, you will discover that they don’t quite suit you. Only then switch to something else. You’ll make a better-informed decision then.</p><h3>P.S.</h3><p>I was serious about presenting more often at conferences and meetups. And that’s why I will also be presenting at the Belgium MLOps meetup on 5th December 2022. So if you’d like to learn about my MLOps adventures in setting up my research environment, please join us via <a href="https://www.meetup.com/mlops-belgium/events/289639571/">this link</a>.</p><h3>P.P.S.</h3><p>The story is based on the “Three Little Pigs” one in its Romanian/Russian variant, where the piglets are named Nif-Nif, Naf-Naf, Nuf-Nuf. Now, the local, russian-speaking population has a joke about the 4th piglet, which I’ll let you guess his name. Special kudos to those who also get the meaning/connotation of the fourth piglet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e8e72652936" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interviewing for a Senior ML Engineer position]]></title>
            <link>https://medium.com/@alexburlacu1996/interviewing-for-a-senior-ml-engineer-position-73ec621fb529?source=rss-dbb1c78b5aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/73ec621fb529</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alex Burlacu]]></dc:creator>
            <pubDate>Sat, 23 Jul 2022 01:00:00 GMT</pubDate>
            <atom:updated>2022-07-25T16:53:56.870Z</atom:updated>
            <content:encoded><![CDATA[<p>Interviewing is always a tiring and sometimes awkward process. Thankfully there are lots of resources online to help you prepare. But what if you need more specific advice for a more niche position?</p><p>This post is based on my personal experience going through the interviewing process at 5 not-FAANG companies. I also had some experience interviewing for not-senior ML Engineering roles at another 3 companies last year. So, I will also do a comparative analysis.</p><h3>Before we begin…</h3><p>Let me start with a short prologue to explain why I’m writing this piece. In January 2022, I decided, again, it was time to search for another job outside of my home country. But this time, I decided to be sneaky/smart about it, so I changed my LinkedIn address to show that I’m in London. I also groomed a bit more my LinkedIn page to show some highlights of my recent experience. And then magic happened. For weeks I had recruiters invite me to interviews. I didn’t even have to apply myself to anything, only to accept or reject opportunities arriving from recruiters. What surprised me was that the majority of options were senior or even lead roles. So, I felt like an imposter, but I still accepted a few of these and started the process. And then I searched for tips on how to nail senior ML engineering interviews… and found almost nothing. Sh*t. And that’s how I met your mother decided to write this blog post.</p><p>I brushed up my interviewing skills through mock interviews. I was also searching for technical questions for Senior ML roles. Surprisingly, I couldn’t find anything. All the info was only for MLE roles. It seemed a bit strange. In retrospect, it all makes sense now.</p><p>I know you are eager to find out why, so I’ll just give the TL;DR right away — <strong>ML and Senior ML have more or less the same complexity/hardness for technical questions</strong>. Surprise!</p><p>I bet you didn’t expect that. I know I didn’t. But then, what <strong>is different</strong>? And how does the interviewing process works for Senior ML Engineers?</p><h3>Senior vs non-senior ML interviews</h3><p>Based on my experience, I haven’t noticed much difference between senior ML and ML engineering interviews at the technical level.</p><p>What I did notice is the focus on soft skills for senior positions, and I don’t necessarily mean communication skills. Instead, how a candidate handled failures, team-level conflicts, cross-team communication, how they solved their most challenging problems, or how they handled a poor decision.</p><p>I recall the first technical interview for a Senior ML role I had. I was anxious about what kind of questions will I receive. It wasn’t so bad, I had tougher questions than that, but the focus was undoubtedly higher on how I handled some scenarios or how I would do it now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wm3f2D5q7228tanVeSCNw.png" /><figcaption>TL;DR: the difference between Senior MLE and MLE interviews. Image by author.</figcaption></figure><p>One position for which I did notice some big differences when it comes to the technical questions is <strong>Research Engineer</strong>. I’m talking questions like <a href="https://www.image-engineering.de/library/technotes/745-how-does-the-jpeg-compression-work">how does JPEG compresses</a> images, how to compute <a href="https://baioc.github.io/blog/fibonacci/#fft-the-fast-fibonacci-transform">nth Fibonacci in O(log n) time</a>, or <a href="https://drscotthawley.github.io/blog/2019/12/21/PCA-From-Scratch.html">how to compute PCA from scratch</a>. Now, for a research engineering position, these kinds of questions do make sense because of the innovative and research-oriented nature of the projects they have to work on. These frequently can involve a lot of <em>convert-math-to-code</em> or <em>let’s-break-it-down-and-then-improve</em> type of tasks.</p><p>Anyway, to give you a more detailed view, let’s see what is the general interviewing process when it comes to these kinds of roles.</p><h3>The general interviewing flow</h3><p>First, let’s go over the main steps in the process. Generally, there are at least 4 steps:</p><ol><li>You have the first call with a recruiter or hiring manager. You get to know each other, go over your CV in general, discuss what makes you search for jobs, or accept invitations to interview, what you know about the company, what you are searching for, and so on. A pretty simple step if you ask me. Then, suppose the hiring manager thinks your goals and interests align with what the company seeks. In that case, you will be invited to the second, <strong>technical</strong> step. The dreaded one.</li><li>I call this step just technical for a reason. Some companies split it into 2, a take-home assignment and then a discussion based on it. Others have the typical coding interview. And others yet just have a technical discussion. The technical discussion usually covers ML theory and some specifics, like what is transfer learning, or what transformer architectures are. It might also be a pen-and-paper exercise where you can be asked to infer how PCA works. The latter is more common for more research-oriented roles.</li><li>Most of the time, there are two technical interviews, the second being more focused on system design interview. Or maybe some more technical challenges and discussions, YMMV, because this is very company- and team- specific.</li><li>Finally, the last round of interviews is usually reserved for everything else that wasn’t covered in the previous steps, usually the behavior interview. Some companies have three rounds, combining the 3rd step with the 4th.</li></ol><p>Now, let’s dive into details.</p><h3>1st interview</h3><p>Pretty simple. Make sure to learn about the company, even if you were invited to interview with them. At this point, the company searching for candidates has a few objectives:</p><ul><li>to understand how interested you are in the company/position</li><li>are there any legal constraints that need to be acknowledged, like visa status</li><li>or personal constraints, like the necessity to work remotely Also, at this stage, the recruiter is looking whether you’d be a good fit based on your career aspirations, personal opinions, and past experiences.</li></ul><p>But don’t be fooled, there’s a probability of failure even at this stage. For example, if the recruiter feels you’re not interested in the position or if your career plans don’t align with the responsibilities of this position.</p><h3>2nd/3rd interview</h3><p>As mentioned, different companies do this stage differently. I found three types. Given that we have two steps here, most companies do a mix of these three methods.</p><h3>The “take-home-assignment tribe”</h3><p>Take home — either an ML serving solution or EDA + modeling. No one will expect you to deliver a robust, production-ready solution for the ML serving project, nor will anyone complain that your Jupyter notebook doesn’t contain a SotA ML model for a given dataset. The focus is on code quality, the presence of tests and features, ease of running the code for the former, and reproducibility and soundness of the solution for the latter.</p><p>Focus on quality over quantity. A good way to show professionalism is to follow up with clarifying questions once you receive the task. And please, read it carefully. Too often have I seen people doing it all wrong and not even bothering to check the exact constraints for the homework.</p><h3>The “coding challengers”</h3><p>Too much was said about it. One point I consider worth reiterating is how important it is to actually talk through your problem-solving process and ask clarifying questions. I would argue that this could be even more important than solving the problem. Also, don’t forget about:</p><ul><li>Asking about possible edge cases and then covering them.</li><li>Explaining the time and space complexity of your solution.</li><li>If you have the time, extra points for going through your code “debugger-style”. That is, step-by-step while telling what the current values of all your variables are.</li></ul><h3>The “technical discussionists”</h3><p>Discussion with a team of engineers. It usually goes like this: Technical/ML Trivia + NotSoOptional[ML System Design] + Optional[Behavioral]. ML questions are mostly one of:</p><ul><li>“How would you handle X scenario”</li><li>“What is Y? How does this work?”</li><li>Occasionally, for research-heavy roles — “Could you compute Z from scratch, here’s a Google Doc”, as a follow-up to the previous questions.</li></ul><p>Where <em>Y \in {BatchNorm, DropOut, SkipConnections, DataAugmentation, SGD, Transformers, Attention, et al.}</em> and<em> Z \in {PCA, Linear Regression, kNN, kMeans\}</em>.</p><p>Sometimes technical discussions take a more ML-System-Design flavor.</p><p>It’s (was) COVID, so system design is usually only verbal unless you can also text-draw a solution while sharing your screen. Pseudo-code also helps. ML System Design seems not to be any different. It’s still one of “Design a Search Engine for X”, or “How are you going to design an X-which-is-actually-a-recommender-system”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DK-ZxtQZSb9jL3j6fcUtcA.png" /><figcaption>Image by author</figcaption></figure><p>Extra points for talking through efficiency/budget/business considerations at this step. For example, proposing to split the application in two, with ML logic on a GPU-enabled machine and business logic on a more conventional server. Or thinking out loud about a buy vs. build decision about some sub-component.</p><h3>Some personal opinions</h3><p>I prefer take-home projects + technical discussions. This combination makes for a more meaningful technical discussion. It allows the candidate to express their ideas about how a proper production system should be designed based on the take-home assignment. Plus, a good take-home project can highlight candidates’ abilities to write code and how they handle logging, testing, documentation, and deployment. I would argue it’s much better than just solving leetcode problems.</p><p>I even used take-home assignments to filter candidates when we were hiring for my team. I know the main cons of it, but I believe that a well-defined problem can be solved in one or two evenings, a couple hours each. Not great, but I feel much more relaxed than doing a 45m coding interview. Speaking of the devil…</p><p>I don’t like coding challenges. IMO, it’s usually just lazy bs. These kinds of practices can be understandable for FAANG ( <a href="https://www.reddit.com/r/csMajors/comments/qhtqre/faang_manga/">well, more like MANGA nowadays</a>) companies because of their scale*. But, when coding challenges are done by small companies, I mostly find this as just bad taste.</p><blockquote><em>Disclaimer *: I don’t mean that at Google-scale, they need their devs to know very well how to sort an array or find 2 numbers that add up to something. I mean that they have to go through so many candidates that they need a standardized, time-efficient, and repeatable way to check their capabilities. It doesn’t seem realistic for companies this big to give take-home assignments and thoroughly check these without incurring significant time and productivity losses. That’s the sad reality.</em></blockquote><p>To add to the mess of coding interviews, companies are actually misusing them. Coding interviews are supposed to check for a candidate’s problem-solving <strong>and</strong> communication skills. You need to show the interviewer <em>what is your thought process</em> and <em>how are you tackling a new problem</em>. Usually, it shouldn’t matter much if the solution you implemented is optimal or not. You need to be aware of this, though. Regretfully, interviewers usually just look for the “correct” answers, like it’s an exam and not a discussion, making the whole experience miserable.</p><p>In theory, coding tests are even worse. Because there’s no way to see the candidate’s <em>thought process</em> and <em>the way they are tackling problems</em>. Thus, it becomes just a timed exam that has no actual value in assessing how good a candidate is. In practice, because most interviewers are no better, I would take a coding test over a coding interview almost any day of the week.</p><p>So, if I were to rank coding interviews, I would arrange them like this:</p><ol><li>“Discussion” coding interview</li><li>Coding test with no interviewer at all</li><li>Exam-like coding interview, without much support from the interviewer</li></ol><p>Of course, there are exceptions. One time, <a href="https://www.youtube.com/watch?v=e-ftdcWqhUs">at band camp</a> (jk), I had a fantastic experience with a no-interviewer coding challenge. It was a 3.5h HackerRank challenge, in 3 stages, for a research engineering position. The questions ranged from probability to ML model serving, numerical stability, and basic ML theory. Then, for the second stage, it was a code review exercise! I was given a piece of code and had to identify a bug and suggest an improvement. How cool is that?! The final part was an actual coding challenge to implement a graph algorithm. It was exhausting, but at least it wasn’t generic, and because it was so diverse, I felt like it enabled people to show where their true strength lies.</p><p>Alright, I’ll stop complaining and move on to the next section of this post.</p><h3>4th interview</h3><p>This one is primarily behavioral. Although I would say the candidate is always asked behavioral questions, it’s just at this stage, it is the primary focus.</p><p>I really like the questions about past experiences and how they can be improved, or if something didn’t work, why? I feel these questions correlate more with actual skill rather than generic theory questions.</p><p>A few questions that I really liked were:</p><ul><li>If I ask your manager what’s your greatest weakness, what would they tell me?</li><li>What was a situation in which you made a mistake? How would you prevent it now by having more experience?</li><li>Give me an example where you made a poor technical decision and then had to fix it. How did you do it?</li></ul><p>Generally, any question which asks to reflect on past mistakes is especially cool. Why? They help uncover how you grew since then, how humble you are, and how your critical thinking works.</p><p>I have no recollection of such questions in a non-senior ML interview, but plenty of those for senior/lead positions. So maybe think about such scenarios before your next interview.</p><h3>Some final tips to prepare</h3><p>To really nail that interview process, I like doing mock interviews. The best way to do it (that I found) is <a href="https://alexandruburlacu.github.io/posts/pramp.com">Pramp.com</a>. It’s not an advertisement, you can check the link — it has no referral code or anything. I just really find them helpful, especially for coding interviews and somewhat for system design interviews.</p><p>For ML system design, the best thing I have found so far is Chip Huyen’s booklet — <a href="https://huyenchip.com/machine-learning-systems-design/toc.html">Machine Learning Systems Design</a>. And of course, for generic system design — <a href="https://github.com/donnemartin/system-design-primer">The System Design Primer</a>.</p><p>And remember, to really prepare for the behavioral interviews. Be ready to answer questions about how you failed and what you learned from it. Focus more on behavioral questions, specifically ones highlighting your leadership potential and learning-from-mistakes type of situations. For a good list of behavioral questions, see this <a href="https://business.linkedin.com/content/dam/me/business/en-us/talent-solutions/resources/pdfs/linkedin-30-questions-to-identify-high-potential-candidates-ebook-8-7-17-uk-en.pdf">PDF from LinkedIn</a>.</p><p>Throughout the process, ask questions and show your interviewers that you are engaged in conversations with them and are interested in the role. Ask them about their technical and business priorities, how specific processes are implemented in the organization, and their current pain points. <a href="https://github.com/viraptor/reverse-interview">Here’s a good list</a> of questions you can ask.</p><p>Interested in becoming a senior engineer? You’ll need both strong ML and superior soft skills to get that senior position. Also, maybe check my post <a href="https://alexandruburlacu.github.io/posts/2022-05-23-becoming-senior"><em>Becoming a Senior Engineer</em></a>, which should help you define your own roadmap.</p><h4>A little disclaimer (last one in this post)</h4><p>These posts were almost done since February, but due to the tragic events unfolding in Ukraine, I thought it wouldn’t be nice, to say the least, to post it back then. In Moldova, there’s a saying “Satu’ arde da baba sî chiaptănă” which translates to something like “The (unreasonable) old lady is grooming while the whole village burns”. I didn’t want to be that lady, so I thought it would be better to wait until things become at least somewhat less chaotic.</p><p>#Слава Україні! #Героям слава!</p><p><em>Originally published at </em><a href="https://alexandruburlacu.github.io/posts/2022-07-23-senior-ml-interview"><em>https://alexandruburlacu.github.io</em></a><em> on July 23, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73ec621fb529" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing programming languages for real-world projects]]></title>
            <link>https://medium.com/@alexburlacu1996/choosing-programming-languages-for-real-world-projects-c53afe84388f?source=rss-dbb1c78b5aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/c53afe84388f</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Alex Burlacu]]></dc:creator>
            <pubDate>Fri, 17 Jun 2022 22:00:00 GMT</pubDate>
            <atom:updated>2022-06-19T09:03:02.324Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9h7xB1elF9zqs24AUQMh6g.jpeg" /><figcaption>Photo by Kenny Eliason: <a href="https://unsplash.com/photos/60krlMMeWxU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditShareLink">https://unsplash.com/photos/60krlMMeWxU</a></figcaption></figure><p>A few years ago, when I was in my senior year at the university, during the distributed systems lecture our professor asked us a very nice question:</p><blockquote><em>If we were to choose between a fancy new programming language, or Java/C#, for a greenfield commercial project, what would we choose and why?</em></blockquote><p>If you’re wondering what it has to do with distributed systems, I have to say — half of it was about software architecture.</p><p>The classroom was split into 2 camps, obviously. The fun and somewhat sad fact was that the Java camp won. I was part of that camp, even though I don’t like Java, to say the least. We had much better arguments. So, what were those winning arguments? Rich library and tooling ecosystem, and the relative availability of professionals in our local market, for a fair price too. Our professor deemed us project managers, not real programmers, then said we were right, and for a few seconds the atmosphere in the classroom turned sad and hopeless. Then we moved on with the lecture.</p><p><strong>TL;DR:</strong> We all want to play with the shiniest new toys, but when money is at stake, better stick to something tried and true.</p><p>So here are some questions to keep in mind when choosing a programming language, or any software tool for that matter, for a project. The focus will be on commercial projects, but some of the tips work for research projects and simple pet projects too.</p><h3>Basic level</h3><p>Initially, the decision-making process is usually guided by a very narrow understanding of the consequences of choosing a specific tool. In increasing order of maturity, here are some basic reasons to make a choice:</p><ol><li><em>I would like to learn this new tool/language/framework, people say it’s hot right now</em></li><li><em>People say this is the best tool/language for this kind of problem</em></li><li><em>I know this language/tool very well and can be very productive with it</em></li><li><em>I and my team know this language/tool quite well and we can all be productive with it</em></li></ol><p>1 and 2 are only acceptable reasons for a pet project, with a small caveat, which I’ll explain later*. Although I would recommend sometimes taking a look at more niche, possibly peculiar tools to learn. Because, you know, <a href="https://www.goodreads.com/author/quotes/1164347.Alan_J_Perlis">if a language doesn’t change the way you think, it’s not worth learning</a>.</p><p>4 is a decent reason, see Paul Graham’s post about <a href="http://www.paulgraham.com/avg.html">using LISP to build a startup</a>, but in the long run, it’s not that simple.</p><h3>Higher-level decision making</h3><p>The difference between programming and getting stuff done, and software engineering is that the latter has significantly harder constraints (See <a href="https://abseil.io/resources/swe-book/html/toc.html">Software Engineering at Google</a>). Not just any code can be developed productively by a changing team of people and maintained over time. And most commercial software isn’t one-time scripts, but code that lives on for years, if not decades. That’s why, when choosing a tool, language, or an entire stack, try to guide your decision-making with these questions, in no particular order:</p><ul><li><em>How well documented this tool/language is?</em></li><li><em>How actively used/developed is it?</em></li><li><em>How many dependencies of any sort does it have?</em></li><li><em>How stable this tool/language is?</em></li><li><em>What is the size and quality of the ecosystem for this tool/language?</em></li><li><em>How productive can someone be using this tool/language?</em></li></ul><p>More constraints, but doable.</p><h3>Business-level decision-making</h3><p>Now we reached the final frontier. Until now, it wasn’t particularly hard to make a choice, you just had to do your research. But now, we’re gonna have to enter the realm of never-ending trade-offs. Keep in mind that software is written by people, who you have to employ, pay salaries, and ideally have a positive return on investment.</p><ul><li><em>How easy is it to teach someone, or how much time does it take to make someone productive with the given tool/language?</em></li><li><em>How much reachable supply of professionals is out there for this tool/language? Is it sufficient for you?</em></li><li><em>How much do professionals who are knowledgeable with this tool/language ask for (money, perks, whatever)?</em></li><li><em>What is the quality of the supply? Are the engineers mostly newbies or seasoned professionals?</em></li><li><em>How many people would like to work with the chosen tool/language? How excited are they?</em></li></ul><p>Rarely the raw performance of a tool or language is a big issue. Some domains are indeed interested in that characteristic too, like scientific computing, low-latency systems, and maybe embedded systems. More recently, how energy-efficient, or “green” a language or tool is, is of greater importance. Yes, <a href="https://docente.ifsc.edu.br/mello/livros/java/paperSLE.pdf">I’m not kidding</a>. For example <a href="https://aws.amazon.com/blogs/opensource/sustainability-with-rust/">Amazon cares</a> about such things, although like all things at this level, it’s <a href="https://news.ycombinator.com/item?id=30441771">not so simple</a>.</p><h3>An example of picking a language</h3><p>Let’s do a “demo”. We will assume that we’re a remote-first startup and we want to build a snowman a serverless platform. How do we pick the programming stack? Well, at least the programming language. We will assume that the technical founders are capable of writing any language. No, they are not <a href="https://en.wikipedia.org/wiki/Spherical_cow">spherical</a>.</p><p>An important technical constraint for our project is that serverless technology is especially effective when the startup time of a serverless function is quick. If it’s not, why bother? Optionally, we might want to dive into serverless edge computing, meaning we need a programming language that can work even on resource-constrained devices. Maybe not microcontrollers, but something like a newer Raspberry Pi shouldn’t be considered unrealistic.</p><p>We are also budget-constrained because we’re a startup. We need to execute fast, or else we might not reach escape velocity, and no one will bother.</p><p>With that said, let’s prune some candidates. Because of our startup latency constraint, we can’t afford to run anything which needs a VM-like runtime. So no Java, C#, and even Erlang or Elixir. Although Erlang and Elixir have less substantial problems with VM cold start, they have another downside of having a smaller talent pool. On yet another hand, this talent pool is usually very enthusiastic and professional. What a shame we’re not building a messaging system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5FnS7y_m-UAyWXo1MJNvQ.png" /></figure><p>If we are planning for maximum efficiency, maybe we should use C++? Definitely no. C++ is quite dangerous. Besides, we need to keep in mind that we want to develop fast and preferably without much risk of segmentation faults, resource leaks, and other C++ surprises. Btw, a good C++ dev is quite expensive and hard to find nowadays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dG5r_YYY6TFIhQc9LdmQLQ.png" /></figure><p>We know that development speed is important. But we also want a performant language without VM cold start problems. How about Python, or JS? These are popular, fast to work with, with a considerable talent pool, and JS can be speedy too. To be fair, this wouldn’t be the worst idea. Python, specifically CPython, can be slow but with the right tooling, or by substituting it with <a href="https://www.pypy.org/">PyPy</a>, we can solve these problems. As for JS, one issue is that the language is not the most pleasant to debug, with its <a href="https://javascriptwtf.com/wtf/javascript-holy-trinity">unholy trinity of no-values</a> and subpar traceback messages. Regretfully, there are lots of not-so-good-devs out there professing these tools, so that’s and issue. Finally, these are not the best systems programming languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgkOT2Xf2RGIKqgtzKBIHw.png" /></figure><p>Ok, so I said it, systems programming languages. And we dropped C++. What do we have left? <a href="https://golangdocs.com/system-programming-in-go-1">Go</a>, <a href="https://msrc-blog.microsoft.com/2019/07/22/why-rust-for-safe-systems-programming/">Rust</a>, <a href="https://crystal-lang.org/">Crystal</a>. We drop Crystal right away due to the lack of a sizeable community, talent pool, and libraries. So, it’s Go vs Rust? Hold on, there’s another contestant — <a href="https://ocamlverse.github.io/content/systems_programming.html">OCaml</a>. So, why did it come to these 3 languages? All of these are very suitable for systems programming, that is, interacting with lower-level OS constructs, are quite efficient at working closer to hardware, and in general, are fast and resource-efficient. Of all 3, Go is the most mainstream, so it’s a plus. Also, it’s easy to onboard people to use it. On the other hand, Rust and OCaml provide nicer guarantees for the programs you write, and although less popular, the quality of developers using them is usually pretty high. OCaml and Rust are pretty close idiomatically, but Rust syntax will be much more familiar to non-hardcore FP people, aka common folk, so it’s probably 10 points to Rust. All in all, let’s see the final table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2ycQ8A0T2IiiqiYj-sBvQ.png" /></figure><p>All things considered, probably the safest choice would be to use Go. And the next best thing would be Rust. A very good option would be PyPy, IMO. It’s almost 1 to 1 equivalent to CPython, but considerably faster. If you like it more hardcore FP, you could try OCaml. You could in fact go polyglot, and pick 2 languages, but don’t escalate to more than that. There’s a reason most full-stack engineers are writing JS-only.</p><h3>*Time to discuss that caveat.</h3><p>Yes, picking a tool only because it’s <em>hot</em> or seems interesting but is risky will rarely be a good idea, except when it is. You see, a tool is usually “hot” for a reason. Maybe it’s solving a common pain in the industry, and does so elegantly. Or maybe, it boosts productivity, efficiency, or the long-term maintainability of a system. Still, this isn’t enough to make such a risky move.</p><p>On the other hand, there’s an interesting aspect here. If a tool is hot people will want to work with it. This phenomenon boosts the desire to work for your team/business because you’re using this New Hot Thing ©. Combined with the intrinsic qualities of the new tool, it might make sense to actually give it a try. It is just as risky to never take a risk. Failing to grow and innovate will leave your business hard to hire for, your talent pool shrinking, and your operational efficiency slowly dying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/0*iXsgFddt5p6tBd9Z.jpg" /><figcaption><em>Follow sage’s advice 😏 Made with: imgflip.com</em></figcaption></figure><h3>A substitute for a conclusion</h3><p>I hope I haven’t fried your brains with this many things to consider. Even I sometimes don’t do the whole process, or am being sloppy when assessing some of the aspects. Still, having a checklist of things to consider is always a good thing, so I hope you’ll benefit from this.</p><p>Maybe a bit anti-climactic, but consider this — if you picked the wrong tool, it will rarely doom your project for failure. What will is not realizing you made a bad choice, and trying to fix it. Technical stacks are problems which can be fixed with money, and that’s a good thing.</p><p>Not the ending you expected? 😏</p><h3>P.S.</h3><p>I should add a clarification about Java. Don’t get me wrong — I don’t “hate” Java, I just like pointing to its flaws, sometimes vehemently 😀. Java’s unnecessary verbosity is the main issue that I have with it. It wasn’t the only issue, but with the sped-up release cycle and a lot of ideas borrowed from other languages and communities, it’s becoming a better language. Brilliant engineers use Java for many important, actively developed projects with no plans to retire or rewrite these. Ergo, it can’t be an objectively “bad” language.</p><h4>A little disclaimer</h4><p>These posts were almost done since February, but due to the tragic events unfolding in Ukraine, I thought it wouldn’t be nice, to say the least, to post it back then. In Moldova, there’s a saying “Satu’ arde da baba sî chiaptănă” which translates to something like “The (unreasonable) old lady is grooming while the whole village burns”. I didn’t want to be that lady, so I thought it would be better to wait until things become at least somewhat less chaotic.</p><p>#Слава Україні! #Героям слава!</p><p><em>Originally published at </em><a href="https://alexandruburlacu.github.io/posts/2022-06-18-choosing-a-tool"><em>https://alexandruburlacu.github.io</em></a><em> on June 17, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c53afe84388f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Becoming a Senior Engineer]]></title>
            <link>https://medium.com/@alexburlacu1996/becoming-a-senior-engineer-5d2886fba8ac?source=rss-dbb1c78b5aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d2886fba8ac</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alex Burlacu]]></dc:creator>
            <pubDate>Mon, 23 May 2022 20:00:00 GMT</pubDate>
            <atom:updated>2022-05-24T08:04:03.202Z</atom:updated>
            <content:encoded><![CDATA[<p>Disclaimer. This post is based on frequent discussions with many of my friends and acquaintances who work in IT/Software Engineering, in a lot of different places, like outsourcing companies, product companies, big organizations with established processes, and small ones where <a href="https://www.youtube.com/watch?v=4L2ooG_MX9E">chaos reigns</a>.</p><p>Anyway, based on all this tribal wisdom, anecdotes, and my own experience and observations, there are four base properties/skills/traits which are a sure-fire way to grow into a senior/leadership position at your organization.</p><p>Depending on the organization, a mix of these four traits is necessary to take the mantle of a “senior engineer”.</p><ol><li><strong>Business acumen</strong> — You know how stuff works in your organization. You know the processes, the people, and the relations among all. You understand the vision and priorities of your company. You also have a rough idea of the company’s risk tolerance, budget, and context in which it operates. You know why certain things are done the way they are.</li><li><strong>Communication skills</strong> — You explain your thoughts crystal clear. And I can’t stress this enough! If you can’t explain your thoughts in a clear, accessible way, you will impede not only your career prospects but others’ productivity too. The better you talk and write, be better everyone will understand what needs to be done, or how to fix things, or what is the roadmap, or… you got the idea. Besides, the more senior you get, and the bigger the organization you have to work in, the more you’ll have to write and communicate with people. Especially now with all the work done remotely, you need clear writing like never before. Chats, emails, JIRA tickets, code reviews, meeting notes, post-mortems; this list can go on forever. Another subskill deserving a place here would be explaining technical stuff to non-technical people. This is especially important when you have to deal with non-technical stakeholders of your projects. They very much appreciate the effort you will put to explain to them what’s going on without much technical jargon. Imagine if nuclear physicists would explain what are they doing using their jargon. You won’t understand a thing. Been there, done that. So be empathetic, and talk to people in a way they can understand.</li><li><strong>Being a force multiplier</strong> — You have good coaching/mentorship skills. You also always think of ways to enable people to do a better job. Maybe by creating a script to automate something, or by creating a shared document explicitly telling how some process is done and why, or just being a knowledgeable and pleasant colleague to discuss issues and ideas with.</li><li><strong>Superior hard skills</strong> — You are one of the most knowledgeable people in your organization/community on some technology/practice/domain. You have superior skills, and for that, you are respected. Part of this is superior debugging skills. More often than we’d like, we have to fix code that’s not working. The quicker this can be done, the more time is left for feature development, which is so important for the business. You think beyond just lines of code and understand the architecture and the tradeoffs which lie at its foundations. You understand that sometimes DRY is not a good idea, where you should apply design patterns, and where it’s ok not to. Also, good coding skills are infectious. People will see your beautiful code and will want to do the same. In a way, you’ll be a force multiplier, by influencing others to write better code, which in turn will make the codebase a nicer environment.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*dZw3HTIuxaB6AhHE.png" /><figcaption>Author: me</figcaption></figure><h3>The A potential path to senior positions</h3><p>Let’s say you were hired as a software engineer, maybe even a junior one. You aspire to become a senior. What do you do?</p><ul><li>Learn your project.</li><li>Learn why your project is important. Who are its users? What’s the roadmap? How does it make/save money?</li><li>Learn more nuanced technical skills. Maybe read a few books. Iterate on this.</li><li>Spot inefficiencies in your team’s processes, try to ease these through explicit processes, helper tools, or any other way. Iterate on this.</li><li>Make friends with colleagues outside your team, maybe even outside your business function.</li></ul><p>Do all these, and you will certainly be allowed to lead some projects or initiatives.</p><h3>A warning note</h3><p>Everything that is in excess becomes harmful. Depending on the organizational culture of your employer, being overly interested in the hows and whys of the business might seem nosy. And if your intentions are perceived this way, you might damage your reputation, instead of growing it. The same goes for strong initiatives to help your colleagues or the business. This one is more nuanced. It might be (usually) that your manager or colleagues are not <a href="https://www.dictionary.com/browse/dicks">unpleasant, counterproductive, or trying to dismiss your genius</a>, they just know that some stuff has been tried already, or the current prerogatives do not leave space for such initiatives. Remember to be respectful, not very annoying, and if all else fails, start searching for another job.</p><h3>Some misc skills you’ll also need</h3><p>I would argue the four traits above are crucial to becoming a senior engineer in any organization. But I’d also like to include the following 3 skills too. Let’s label them as <em>very good to have</em>.</p><ul><li><strong>Attention to details</strong>. Sloppy-done tasks have a big hit on your karma. Depending on your place of employment, this could range from writing code that works well without immediately visible issues, and writing high-quality code, with good tests and without breaking the CI.</li><li><strong>Humility</strong>. You know, don’t be an <a href="https://www.dictionary.com/browse/dick">unpleasant, counterproductive, or trying to dismiss others</a> person. If no one wants to work with you, you will either be put on the worst projects in your company or straight fired from there. Note, don’t confuse <a href="https://tomhazledine.com/humility-in-tech/">humility</a> with low self-esteem.</li><li><strong>A growth mindset</strong>. If you learned something to land a job and once there, decide to sit still on your ass, I’m afraid your only chance to become senior is by having the rest of your colleagues being <a href="https://en.wikipedia.org/wiki/Bus_factor">hit by a bus</a>. Stagnation should never be an option.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aNNSo_Vu634I_T1q.png" /><figcaption>Author: me</figcaption></figure><p>Of course, there are always exceptions, people who hold senior or technical leadership positions without these skills, but they are that — exceptions. So, it’s better to also be humble, attentive, and with a growth mindset than not to be.</p><ul><li><strong>Senior engineer is the one who stayed the most with the company</strong>. This distills down to business acumen. She/he knows how things are done in the organization, and knows the codebase very well. Some communication and hard skills are also necessary. This path is prone to the “old junior” problem. “Old juniors” are a case you wouldn’t want to be in. It happens when someone stays with a company/product for too long without substantially growing their skills, but only acquiring business acumen. People in this situation remain stuck in their companies because of a growing chasm between their title and their actual skills.</li><li><strong>Team leads</strong>. They usually are strong on Communication skills/being a force multiplier, and most are pretty good on the hard skills side too, but YMMV. A good team leader is an important asset for any organization, they are like <a href="https://civilization.fandom.com/wiki/Great_General_(Civ6)">Great Generals</a> for their teams.</li><li><strong>An outsider is hired as a senior/lead right away</strong>. This does happen, and is more common in smaller organizations, in freshly established departments, or in new and specialized teams. Such people are almost always strong in hard skills and usually in communication skills. Occasionally, they may have very good business acumen because they have worked in similar industries before.</li></ul><p>Remember, you need a mix of these. Having only hard skills won’t cut it. You’ll be just a very good software engineer. Nor will just business acumen help you, it will just turn you into a mediocre manager in the best-case scenario, or the terror of the engineering team in the worst case. And if you’re only good at being a force multiplier? Have you heard about the Scrum master position?</p><ul><li>Ask questions about the business/product. Show interest in how things are done within your organization.</li><li>Level up your communication skill and help your team. Technical writing, working on enabling tasks, and mentorship are some of the most important. You can level these up by volunteering to document some nasty parts of the codebase, describing internal processes, and working on/proposing tools to increase the productivity of your team. Mentorship skills can be acquired by either asking to be the mentor for new hires, or you can try teaching outside of work, CoderDojo-like organizations being probably the best at this.</li><li>Learn hard skills. Read books. Work on pet projects, to crystalize the knowledge you got from reading. Being part of a specialized community will also help you grow your hard skills, by learning advanced concepts you won’t find by just googling, because you wouldn’t even know what to google. Reddit is pretty good at this, sometimes. Also, slack/gitter/discord groups, interested in specific technology are good too. If you use it right, Twitter and YouTube are also excellent channels for this.</li></ul><p>By the way, notice that throughout the whole post, there was no mention of years of experience. Of course, some of the traits outlined above correlate with years of experience, but the correlation is not perfect, meaning you could have 10 YoE and still be not as good as someone with 4 YoE. So focus on skills, not on mileage.</p><h3>Before I go</h3><p>Maybe someone will find this news, but being a Senior is not the end of the road. Of course, many know about the “move into management” path. But there’s another way. Becoming a Staff software engineer. How? I don’t know, yet. When I will, I’ll certainly write another blog post. Until then, I’ll leave you with <a href="https://www.reddit.com/r/ExperiencedDevs/comments/ltsoao/how_do_you_differentiate_a_staff_engineer_from_a/">this Reddit thread</a> and <a href="https://staffeng.com/book">this book</a>.</p><h4>A little disclaimer</h4><p>These posts were almost done since February, but due to the tragic events unfolding in Ukraine, I thought it wouldn’t be nice, to say the least, to post it back then. In Moldova, there’s a saying “Satu’ arde da baba sî chiaptănă” which translates to something like “The (unreasonable) old lady is grooming while the whole village burns”. I didn’t want to be that lady, so I thought it would be better to wait until things become at least somewhat less chaotic.</p><p>#Слава Україні! #Героям слава!</p><p><em>Originally published at </em><a href="https://alexandruburlacu.github.io/posts/2022-05-23-becoming-senior"><em>https://alexandruburlacu.github.io</em></a><em> on May 23, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d2886fba8ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going beyond simple error analysis of ML systems]]></title>
            <link>https://medium.com/data-science/going-beyond-simple-error-analysis-of-ml-systems-9218f9602d33?source=rss-dbb1c78b5aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9218f9602d33</guid>
            <category><![CDATA[deep-dives]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[notes-from-industry]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alex Burlacu]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 00:10:00 GMT</pubDate>
            <atom:updated>2021-07-29T15:45:05.891Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/notes-from-industry">Notes from Industry</a></h4><h4>When deploying machine learning algorithms, the stakes are much higher than in any toy problem or competition.</h4><p><em>Originally published at </em><a href="https://alexandruburlacu.github.io/posts/2021-07-26-ml-error-analysis"><em>https://alexandruburlacu.github.io</em></a><em> on July 26, 2021.</em></p><h3>First, there was a story…</h3><p>Imagine yourself working as an ML engineer… very cool my friend!</p><p>First of all, congratulations, pat yourself on the back, your family must be proud.</p><p>Second, depending on the company size, culture, and the maturity of the machine learning team, you’re most likely in for a wild ride through many computer science and software engineering domains.</p><p>Again, pat yourself on the back. Now, let’s get to the chase.</p><p>As an MLE, part of your work is to pick, tune and deploy ML models. I believe I don’t need to explain to you that this is not so trivial. You must believe that the hard part of this process is to tune the model, don’t you? Or maybe that it is the deployment of the algorithm? Although these are indeed non-trivial, especially the later one, here’s <em>The Question ©</em> for you:</p><blockquote><strong>How do you make sure you have a high-quality model in production?</strong></blockquote><p>If you’re gonna tell me that you just tested your model on a held-out dataset and that your metric of choice was something like accuracy, or the mean squared error, just run. Fast. Far away. If you didn’t run, be prepared to be questioned whether or not you:</p><ul><li>had a baseline,</li><li>balanced dataset or adjusted your metrics,</li><li>used the held-out dataset for tuning/hyperparameter search … and so on.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*PYpUH3wXZKYXx1y_.jpg" /><figcaption><em>So many questions… Made with: imgflip.com</em></figcaption></figure><p>I guess you figured out by now that a simple train/test split and a few error metrics, like accuracy or maybe even F1*, are not nearly enough to answer <em>The Question ©</em>. But what <em>would</em> be enough? Well, it depends, like all things in software engineering. You need to understand that reducing your model characteristic to only one or a few scalars will forfeit way too much information about the model.</p><p><em>*F1 score is a much better choice, btw</em></p><h3>… and then words of wisdom* followed</h3><p><em>* more like personal war stories</em></p><blockquote><em>Disclaimer, this is a long post, so maybe brew some tea/coffee, get a snack, you know, something to help you get through the whole thing. Maybe taking notes would help you to stay focused. It certainly helps me when reading a lot of technical text.</em></blockquote><p>Another little disclaimer: I had <a href="https://alexandruburlacu.github.io/posts/2021-05-09-archive-understanding-a-black-box">an older post</a> tangential to this topic, but the focus in it was on interpretability/explainability methods. In this blog post, I focus more on how to assess the errors of machine learning models. If you think these topics are pretty close to each other, somewhat overlapping, you are right. To better evaluate a model, we sometimes need to understand the “reasoning” it puts into making a prediction.</p><p>Keep in mind — depending on the domain you apply machine learning to, a subpar model could be anything from a little annoyance for your users to a complete dumpster fire that amplifies biases and makes your customers run away from your business. While it could be easy for said users to opt out from the former, the latter can ruin your business. We don’t want that. Your employer certainly doesn’t.</p><p>Ok, copy that. But how do you <em>know</em> that a machine learning model is good? Do you need to understand its predictions? Does your use case have a specific group of users that you care about the most? These questions can help you derive an evaluation strategy and in turn to make sure nothing goes south after you deploy an ML model.</p><p>You know what, let me first define a few ML evaluation maturity levels. It will be easier for me to explain and for you to follow along. For now, don’t bother about the meaning of some more advanced terms here, I will explain them right after this section.</p><ul><li><strong>Level 0 (L0)</strong>: Having a train+test split and one or two generic metrics, like MSE or Accuracy. At this level, deploying the ML model is not advised (read: irresponsible at best).</li><li><strong>Level 1(L1)</strong>: Previous level, but using cross-validation if possible, or worst-case scenario, having a big and diverse test set. You will need to have per-class metrics for classification problems or multiple metrics for regression problems. For classification use cases, metrics like ROC-AUC score, or F1 score are considerably better than accuracy, so use these. Moreover, understanding your model’s precision and recall characteristics can prove crucial for a successful ML product. In case of regression, <a href="https://medium.com/analytics-vidhya/mae-mse-rmse-coefficient-of-determination-adjusted-r-squared-which-metric-is-better-cd0326a5697e">MAPE+RMSE+Adjusted R²</a> are a good combination, you can consider using <a href="https://stats.stackexchange.com/questions/577/is-there-any-reason-to-prefer-the-aic-or-bic-over-the-other">AIC and/or BIC</a> too. For regression, try to have at least one metric robust to outliers (<a href="https://www.h2o.ai/blog/regression-metrics-guide">MAPE is robust to some types of outliers, but not the others</a>).</li><li><strong>Level 1.1 (L1.1)</strong>: Check most wrong predictions, that is, entries with high prediction confidence, but that are predicted wrong. It can help you uncover error patterns, maybe even biases.</li><li><strong>Level 2 (L2)</strong>: Perturbation analysis using counterfactuals and random alterations of input values. Usually, such an approach permits an understanding of feature importance for each entry, but that is more like a bonus you have to work to get.</li><li><strong>Level 2.1 (L2.1)</strong>: <a href="https://scikit-learn.org/stable/modules/partial_dependence.html">ICE/PDP</a>/<a href="https://christophm.github.io/interpretable-ml-book/ale.html">ALE</a> plots can be used to better understand feature importances. Keep in mind these are fairly compute power demanding.</li><li><strong>Level 2.2 (L2.2)</strong>: Surrogate local explanations (usually LIME) and/or additive feature explanations (i.e. SHAP) to understand model predictions before approving the model for deployment. Also computationally demanding.</li><li><strong>Level 3 (L3)</strong>: Cohort-based model inspection. One way to define cohorts is through <a href="https://github.com/uber/manifold">Manifold</a>-like error groupings. At this level, it’s important to acknowledge the changes in data distributions and if applicable, to evaluate on data from different periods. Believe me when I tell you this, sometimes feature and/or label distributions can change even in domains where you don’t expect them to. And not accounting for this will give you some royal headaches.</li><li><strong>(Optional) Level 4 (L4)</strong>: Adversarial examples checking. Stuff like Anchors and TCAV are at this level too. In principle, any other advanced model interpretability/explainability or security auditing is at this level.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*AlK5_QVqjlJxYUHS.jpg" /><figcaption><em>Power levels. Don’t be L0. Made with: imgflip.com</em></figcaption></figure><p>You would want to be at Level 1 when launching a model in beta, Level 2 when it’s in production, and from there grow to Level 3. Level 4 is more specific and not every use case requires it. Maybe you are using your ML algorithms internally, and there’s a low risk for some malicious agents trying to screw you, in this case, I doubt you need to examine the behavior of your model when fed adversarial examples but use your own judgment.</p><p>Note that although I mention regression use-cases, I omitted a lot of info about time-series forecasting. This is done on purpose, because the topic is huge, and this post is already a long-read. But if you have a basic understanding of what’s going on here, you can map different time-series analysis tools onto these levels.</p><h3>Methods</h3><p>Let’s roughly cluster evaluation/error analysis methods into three broad categories: (1) metrics, (2) groupings, and (3) interpretations. Metrics is kind of obvious. Groupings are probably the most abstract ones. We put here train/test splits, cross-validation, input data cohort, and error groupings in this… oh god… group (no pun intended). Finally, under the interpretation umbrella fall such things as surrogate local explanations, feature importance, and even analyzing the most wrong predictions, among other things.</p><h4>Metrics</h4><p>I won’t dive deep into metrics-based evaluations but will mention that depending on your use case you might want to consider metrics that are non-linear in their relation to how wrong the prediction is. Maybe you’re fine with a bit of error, but if the model is very wrong, or frequently wrong, you want to penalize it disproportionally more. Or, on the contrary, as there are more wrong predictions, or the total loss of the model is growing, you want to have a log-like behavior for your metric, i.e. the metric will attenuate its growth as the model is more wrong.</p><p>Furthermore, on the matter of metrics that are robust to outliers, sometimes these are nice to have if you do some outlier removal beforehand. Or there might be a necessity, in cases when you can’t or specifically don’t remove the outliers, for whatever reason. Keep that in mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*_gPmfMlApZc3GvyG.png" /><figcaption><em>Effects of outliers on model fitness. Source: </em><a href="https://scikit-image.org/"><em>https://scikit-image.org</em></a></figcaption></figure><p>Usually, in production scenarios, you will want to assess your model performance on different cohorts, and maybe even based on these cohorts to use different models. A cohort means a group of entities, with a specific grouping criterion, like an age bracket, or location-based, or maybe something else.</p><h4>Groupings</h4><p>I mentioned cohorts in the paragraph above, so it will make sense to follow up on this. Cohorts are important because your stakeholders are interested in these, sometimes you might be too, but the business is usually the number one “fan” of cohorts. Why? Well, it could be due to many reasons. Maybe they are especially interested in providing top-notch services for a special group of customers, or maybe they must comply with some regulations that ask them for a specific level of performance for all the users.</p><p>Moreover, your dataset is most certainly skewed, if it’s real-world data. Meaning, you will have underrepresented classes, all sorts of imbalances, and even different distributions for your features for each class/group of classes. For example, it wouldn’t be ok for any business to give subpar recommendations for users outside the North America region, or to predict that <a href="https://www.cnet.com/news/google-apologizes-for-algorithm-mistakenly-calling-black-people-gorillas/">a person of color is some kind of ape</a>.</p><p>We need to create cohorts, or groups, based on some characteristics, and track the performance of our machine learning systems across these. Often you will discover that the teams who are conscious about their cohorts will deploy different models for different user groups, to ensure high-quality service for everyone.</p><p>But groupings aren’t just cohorts based on input data characteristics. Sometimes for model analysis, it makes sense to create groupings based on errors. Some kind of groupings by the error profile. Maybe for some inputs your model(s) gives low errors, for other inputs some very high errors, and for yet another group the error distribution is entirely different. To uncover and understand these, you could use <a href="https://alexandruburlacu.github.io/posts/2021-06-18-kmeans-trick">K-Means</a> to cluster your losses and identify the reason your model might fail or just underperform. That’s what Manifold from Uber does, and that’s just brilliant!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4zrcPlphzqfc6SVD.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lsurBVbdw7bg4AHL.png" /><figcaption><em>(Top) 3 clusters of error distributions, and a </em>comparison<em> between 2 models. (Bottom) Once we have error groups, we’d like to find why are these happening. Visualizing differences in feature distribution between two of these clusters can help. <br> Source: The author. Inspired by: </em><a href="http://manifold.mlvis.io/"><em>http://manifold.mlvis.io/</em></a><em>.</em></figcaption></figure><p>Finally, groupings are also about how you arrange your data into training and testing splits. Or more splits, like evaluation during the training of your model. These help in noticing when the model starts to overfit or whatever. Keep in mind, special care should be taken when doing a hyperparameter search. For fast-to-train models, a technique called <a href="https://weina.me/nested-cross-validation/">nested cross validation</a> is an incredibly good way to ensure the model is really good. The nested part is necessary because doing hyperparameter optimization (HPO) you’re optimizing on the evaluation set, so your results will be “optimistic” to say the least. Having an additional split could give you a more unbiased evaluation of the final model. What about slow models? Oh, boi. Try to have a big enough dataset such that you can have big splits for all your evaluation/testing stages. You don’t have this either? Have you heard about the <a href="https://hackernoon.com/the-ai-hierarchy-of-needs-18f111fcc007">AI hierarchy of needs</a>?</p><p>Also, an often overlooked issue is the target distribution of the dataset. It might be heavily imbalanced, and as a result, special care should be taken when sampling from it for train/validation/test splits. That’s why you should almost always search for a way to have your splits <em>stratified</em> (see scikit-learn’s StratifiedKFold, also train_test_split has a stratify= parameter and for multioutput datasets check out multioutput_crossvalidation package). When a dataset is imbalanced you could try to do some sort of oversampling, a la SMOTE or ADASYN, but in my experience, it might not always work, so just experiment (a scikit-learn-like lib for this is <a href="https://imbalanced-learn.org/stable/index.html">imbalanced-learn</a>).</p><h4>Interpretations</h4><blockquote><em>Disclaimer #2, this part of the blog post is maybe one of the most overwhelming. There’s quite a body of literature about ML interpretability/explainability and I will only briefly mention some methods, for a more in-depth overview, check out </em><a href="https://christophm.github.io/interpretable-ml-book/"><em>Interpretable Machine Learning by Christoph Molnar</em></a><em>.</em></blockquote><p>This category is pretty abstract, and some might argue that these are not really related to model evaluation, but rather ML interpretability/explainability. To which I say that these methods allow uncovering hidden errors, biases. Based on these, now you can pick one model over another, thus interpretations being useful for evaluation. These tools excel in identifying the “ <strong>right answer — wrong method</strong> “ scenarios, which will pass without any issue metrics and groupings.</p><p>So, what things can you “interpret” about a model that can help you evaluate it? First, if your model/API allows for it, you could check feature importances. You might discover that a model puts too much weight on some obscure feature or one that doesn’t make sense. At this point, you should become a detective, and find out why is this the case. This kind of feature importance is called <strong><em>global feature importance</em></strong>, because it is inferred at the model level, from all training data.</p><p>The next easy thing to do is <strong><em>perturbation analysis</em></strong>, of which there are multiple categories. Perturbation analysis means altering the input and seeing what’s going to happen. We can alter the input with a different purpose to assess different aspects of the model.</p><ul><li>Counterfactuals, aka “What if I change this one feature, how will my model prediction change?”. We can check for example how sensitive is the model to changes that in principle should change the prediction intuitively. A prominent tool for this is <a href="https://www.tensorflow.org/tensorboard/what_if_tool">Tensorboard’s What-If tool</a>.</li><li>Adversarial examples, aka “Can I create such input that while similar to a normal one will result in a messed prediction”. Checking these is usually important for external user-facing systems, where an attack can have very nasty consequences, and because this kind of verification is more specific, it is usually left for later during the project.</li><li>Random alterations, to assess how robust is the model to unimportant changes, or how well it captures “common sense-ness”, also can be used for local feature importance. In the case of a sentiment analysis problem, a random alteration could be swapping synonyms for words that don’t have positive or negative semantics, aka neutral words.</li><li>Out-of-distribution data. Ok, this one isn’t really perturbation analysis, but sometimes you want to make sure the model can generalize to data that is similar but not quite. Or maybe you just want <a href="https://www.youtube.com/watch?v=yneJIxOdMX4">to have some fun</a> at work and pass german sentences to a sentiment analysis model trained on Spanish text.</li></ul><p>Another way to help you uncover error patterns is by checking the wrong predictions which have very high model confidence. In simpler terms, the royal fuck-ups. I learned this method relatively late, from the Deep Learning Book by Goodfellow et al. I’m lazy, and this method although obvious in hindsight, is new to me. I prefer doing perturbation analysis so that there’s no need for pretty printing and/or plotting with that one. But while working on my research project I am now “forcing” myself (it’s not so bad, really) to also do this step.</p><p>I would recommend defining some sort of regression tests suite made up of previously problematic input examples. This can help be sure that future versions of the ML model are indeed an improvement on the previous ones. In it can check previously wrongly classified entries or use examples from different types of perturbation analysis. You will thank yourself later for this regression suite.</p><p>Surrogate local explanations, of which the most prominent tool is LIME, are another kind of interpretability tool. Surrogate local explanations try to approximate a complex machine learning model with a simple machine learning model, but only on a subset of the input data, or maybe just for a single instance.</p><p>FINALLY (now for sure), another notable class of ML interpretability methods is additive feature explanations, and for this category one of the most prominent tools is SHAP. SHAP is especially interesting, albeit harder to understand, given it’s based on game theory and uses Shapely values to define local feature importances. One issue with this method is that Shapely values or almost any other additive feature explanation method don’t account for feature interactions, which can be a deal-breaker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*D4MjyQSdxxtWMxg6.png" /><figcaption><em>SHAP uses Shapley Values to explain the effect of each feature value on the prediction. Source: author.</em></figcaption></figure><p>There are even more advanced tools, tuned specifically for neural networks. These use different forms of saliency or activation maps. Tools like these are cool and helpful, but harder to use, and not as general. Trying to cover even a subset of these would require <a href="https://christophm.github.io/interpretable-ml-book/">an entire book</a>, so if you’re interested, you know what to do ;). In the book, you can find much more detailed explanations about modern tools like SHAP, LIME, Anchors, but also more classic approaches like PDP, ICE, and ALE plots. And even concept identification approaches like <a href="https://github.com/tensorflow/tcav">Tensorflow’s TCAV tool</a>.</p><p>One thing to keep in mind, interpretability tools are crucial for a proper model evaluation. Although not a direct mapping, you can think of these interpretation methods for a model like code review for code. And you don’t merge code without code review in a production system, now do you?</p><h3>Personal recommendations</h3><p>We’re nearing the end of this post, so I would like to give you some recommendations on how to proceed when evaluating ML models as if those maturity levels weren’t enough. These recommendations are more low-level and practical, some gotchas if you will.</p><ul><li>Of course, start with a couple of appropriate evaluation metrics. Don’t use just one. If you can, cross-validate. If doing HPO, have two testing splits. For classification, I would recommend at least some loss and some score function + scikit-learn’s classification_report and if you don&#39;t have a ton of classes, the confusion matrix is your friend. Some people use AUC and Precision-Recall curves, which are nice, but I&#39;m just not used to these. Maybe after this blog post, I will start using them. (do as I say, not as I do)</li><li>I usually do perturbation analysis (random and counterfactuals) after this. Looking for the top-k most wrong predictions helps, but I rarely do it (do as I say, not as I do, #2).</li><li>If I’m not satisfied yet, I will certainly check for error groups a la Manifold and/or surrogate local explanations (LIME-like, I mostly use the eli5 package). I prefer not to do the latter because it takes a looooot of time, especially with bigger-sized input. Regarding local explanations with surrogate models, sometimes I find it necessary to adjust the surrogate using the default might be just too simplistic. I do NLP, so both points are a real issue for me.</li></ul><p>Sometimes, especially in the early stages of development, I could do a kind of “exploratory testing” of model predictions, namely feed out-of-distribution data and look at what will happen.</p><p>For personal experiments, I can sometimes use SHAP but I find it a bit frustrating that it’s hard to export the graphics and that it works best when working from Jupyter. Moreover, it’s slow, but that’s a general issue for all surrogate explanations.</p><p>I am yet to play around with Anchors, adversarial examples, and doing stuff like “Find the most similar entry with a different class” or “Find the most similar entries to this one”. The latter two can be done using kNN in either feature, embedding, and/or prediction spaces. Microsoft Data Scientists seem to be asking these kinds of questions to assess their models.**</p><p>In the end, I am sure this amount of information is overwhelming. That’s why maybe the best recommendation I could give is to just use a simple model, one that is easy to understand. To make it performant you could also try to invest time in features that make sense. All in all, just be the data scientist your company needs you to be, not the one you want to be. Boring and rational beats hype-driven.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/0*5-iQHDY1M38lC5Ss.jpg" /><figcaption>Choose your hero wisely. Made with: imgflip.com</figcaption></figure><p>Probably this post, like no other, helped me crystalize a lot of the tacit knowledge gained through the years. Maybe you’ve heard the quote — “When one teaches, two learn” I believe something like this happened here too.</p><p>I know my posts are usually long and dense, sorry, I guess, but on the other hand, now you don’t have to bookmark 5–10 pages, just this one 😀😀😀 jk. Anyway, thank you for your perseverance in reading this article, and if you want to leave some feedback or just have a question, leave a comment. Guess it will take a while until next time.</p><pre> vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv<br>&gt; Until then, you can play around                                 &lt;<br>&gt; with most of the methods described in this blog post            &lt;<br>&gt; by checking the link below                                      &lt;<br>&gt; <a href="https://github.com/AlexandruBurlacu/error_analysis_code_samples">https://github.com/AlexandruBurlacu/error_analysis_code_samples</a> &lt;<br>  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^</pre><p><a href="https://github.com/AlexandruBurlacu/error_analysis_code_samples">You can also click on it here.</a> All examples are seeded, so it should be possible to reproduce everything. Have fun.</p><h3>Acknowledgements</h3><p>Special thanks to <a href="https://twitter.com/dgaponcic">@dgaponcic</a> for style checks and content review, thank you again <a href="https://twitter.com/anisoara_ionela">@anisoara_ionela</a> for thorough grammar checks, and thank you <a href="https://twitter.com/dianaartiom">@dianaartiom</a> for the last bits of feedback on ML. You’re all the best ❤</p><h3>A few references</h3><ul><li><a href="http://people.duke.edu/~rnau/compare.htm">A detailed overview of regression metrics</a></li><li><a href="https://christophm.github.io/interpretable-ml-book/">Interpretable Machine Learning by Christoph Molnar</a>; amazing work, a lot of info, a lot of details</li><li>**<a href="https://github.com/AlexandruBurlacu/alexandruburlacu.github.io/blob/main/_data/ml_debugging/19_gamut_chi.pdf">Gamut paper</a> to help you ask the right questions about a model</li><li><a href="https://github.com/AlexandruBurlacu/alexandruburlacu.github.io/blob/main/_data/ml_debugging/1808.00196.pdf">Manifold paper</a> and <a href="https://github.com/uber/manifold">Manifold GitHub repo</a></li><li><a href="https://neptune.ai/blog/the-ultimate-guide-to-evaluation-and-selection-of-models-in-machine-learning">A good overview on how to evaluate and select ML models</a></li></ul><p>Github repos which also contain links to their respective papers:</p><ul><li><a href="https://github.com/marcotcr/lime">LIME GitHub repo</a></li><li><a href="https://github.com/slundberg/shap">SHAP GitHub repo</a></li><li><a href="https://github.com/marcotcr/anchor">Anchors GitHub repo</a></li><li>And an <a href="https://github.com/altamiracorp/awesome-xai#critiques">Awesome GitHub repo</a> on different XAI tools and papers.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9218f9602d33" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/going-beyond-simple-error-analysis-of-ml-systems-9218f9602d33">Going beyond simple error analysis of ML systems</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Means tricks for fun and profit]]></title>
            <link>https://medium.com/data-science/k-means-tricks-for-fun-and-profit-724996864274?source=rss-dbb1c78b5aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/724996864274</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alex Burlacu]]></dc:creator>
            <pubDate>Sat, 19 Jun 2021 18:30:00 GMT</pubDate>
            <atom:updated>2021-06-20T17:22:46.370Z</atom:updated>
            <content:encoded><![CDATA[<h4>K-Means is an interesting, simple, and pretty intuitive algorithm. It turns out it can do more than just clustering.</h4><h3>Prologue</h3><p>This will be a pretty small post, but an interesting one nevertheless.</p><p>K-Means is an elegant algorithm. It’s easy to understand (make random points, move them iteratively to become centers of some existing clusters) and works well in practice. When I first learned about it, I recall being fascinated. It was elegant. But then, in time, the interest faded away, I was noticing numerous limitations, among which is the spherical cluster prior, its linear nature, and what I found especially annoying in EDA scenarios, the fact that it doesn’t find the optimal number of clusters by itself, so you need to tinker with this parameter too. And then, a couple of years ago, I found out about a few neat tricks on how to use K-Means. So here it goes.</p><h3><strong>The first trick</strong></h3><p>First, we need to establish a baseline. I’ll use mostly the breast cancer dataset, but you can play around with any other dataset.</p><pre>from sklearn.cluster import KMeans<br>from sklearn.svm import LinearSVC<br>from sklearn.datasets import load_breast_cancer<br>from sklearn.model_selection import train_test_split</pre><pre>import numpy as np</pre><pre><br>X, y = load_breast_cancer(return_X_y=True)</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=17)</pre><pre>svm = LinearSVC(random_state=17)<br>svm.fit(X_train, y_train)<br>svm.score(X_test, y_test) <strong># should be ~0.93</strong></pre><p>So, what’s this neat trick that reignited my interest in K-Means?</p><blockquote><strong>K-Means can be used as a source of new features.</strong></blockquote><p>How, you might ask? Well, K-Means is a clustering algorithm, right? You can add the inferred cluster as a new categorical feature.</p><p>Now, let’s try this.</p><pre># imports from the example above</pre><pre>svm = LinearSVC(random_state=17)<br>kmeans = KMeans(n_clusters=3, random_state=17)</pre><pre>X_clusters = kmeans.fit_predict(X_train).reshape(-1, 1)</pre><pre>svm.fit(np.hstack([X_train, X_clusters]), y_train)<br>svm.score(np.hstack([X_test, kmeans.predict(X_test) \<br>   .reshape(-1, 1)]), y_test) <strong># should be ~0.937</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/0*8R4UbDkgouaFnb6K.png" /><figcaption><em>Source: knowyourmeme.com</em></figcaption></figure><p>These features are categorical, but we can ask the model to output distances to all the centroids, thus obtaining (hopefully) more informative features.</p><pre># imports from the example above</pre><pre>svm = LinearSVC(random_state=17)<br>kmeans = KMeans(n_clusters=3, random_state=17)</pre><pre>X_clusters = kmeans.fit_transform(X_train)<br>#                       ^^^^^^^^^<br>#                       Notice the `transform` instead of `predict`<br># Scikit-learn supports this method as early as version 0.15</pre><pre>svm.fit(np.hstack([X_train, X_clusters]), y_train)<br>svm.score(np.hstack([X_test, kmeans.transform(X_test)]), y_test)<br><strong># should be ~0.727</strong></pre><p>Wait, what’s wrong? Could it be that there’s a correlation between existing features and the distances to the centroids?</p><pre>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import pandas as pd</pre><pre>columns = [&#39;mean radius&#39;, &#39;mean texture&#39;, &#39;mean perimeter&#39;, &#39;mean area&#39;, &#39;mean smoothness&#39;, &#39;mean compactness&#39;, &#39;mean concavity&#39;, &#39;mean concave points&#39;, &#39;mean symmetry&#39;, &#39;mean fractal dimension&#39;, &#39;radius error&#39;, &#39;texture error&#39;, &#39;perimeter error&#39;, &#39;area error&#39;, &#39;smoothness error&#39;, &#39;compactness error&#39;, &#39;concavity error&#39;, &#39;concave points error&#39;, &#39;symmetry error&#39;, &#39;fractal dimension error&#39;, &#39;worst radius&#39;, &#39;worst texture&#39;, &#39;worst perimeter&#39;, &#39;worst area&#39;, &#39;worst smoothness&#39;, &#39;worst compactness&#39;, &#39;worst concavity&#39;, &#39;worst concave points&#39;, &#39;worst symmetry&#39;, &#39;worst fractal dimension&#39;, <strong>&#39;distance to cluster 1&#39;, &#39;distance to cluster 2&#39;, &#39;distance to cluster 3&#39;</strong>]</pre><pre>data = pd.DataFrame.from_records(np.hstack([X_train, X_clusters]), columns=columns)</pre><pre>sns.heatmap(data.corr())<br>plt.xticks(rotation=-45)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7MjOaze1lrLSSTEE.png" /><figcaption><em>Notice the last 3 columns, especially the last one, and their color on every row. </em>Source: the author of the post, see the code snippet above to generate it.</figcaption></figure><p>You probably heard that we want the features in the dataset to be as independent as possible. The reason is that a lot of machine learning models assume this independence to have a simpler algorithm. Some more info on this topic can be found <a href="https://datascience.stackexchange.com/questions/24452/in-supervised-learning-why-is-it-bad-to-have-correlated-features">here</a> and <a href="https://towardsdatascience.com/why-exclude-highly-correlated-features-when-building-regression-model-34d77a90ea8e">here</a>, but the gist of it is that having redundant information in linear models destabilizes the model, and in turn, it is more likely to mess up. On numerous occasions, I noticed this problem, sometimes even with non-linear models, and purging the dataset from correlated features usually gives a slight increase in the model’s performance characteristic.</p><p>Back to our main topic. Given that our new features are indeed correlated with some of the existing ones, what if we use only the distances to the cluster means as features, will it work then?</p><pre># imports from the example above</pre><pre>svm = LinearSVC(random_state=17)<br>kmeans = KMeans(n_clusters=3, random_state=17)<br>X_clusters = kmeans.fit_transform(X_train)</pre><pre>svm.fit(X_clusters, y_train)<br>svm.score(kmeans.transform(X_test), y_test) <strong># should be ~0.951</strong></pre><p>Much better. With this example, you can see that we can use K-Means as a way to do dimensionality reduction. Neat.</p><p>So far so good. But the piece de resistance is yet to be shown.</p><h3><strong>The second trick</strong></h3><blockquote><strong>K-Means can be used as a substitute for the kernel trick</strong></blockquote><p>You heard me right. You can, for example, define <em>more</em> centroids for the K-Means algorithm to fit than there are features, much more.</p><pre># imports from the example above</pre><pre>svm = LinearSVC(random_state=17)<br>kmeans = KMeans(n_clusters=250, random_state=17)<br>X_clusters = kmeans.fit_transform(X_train)</pre><pre>svm.fit(X_clusters, y_train)<br>svm.score(kmeans.transform(X_test), y_test) <strong># should be ~0.944</strong></pre><p>Well, not as good, but pretty decent. In practice, the greatest benefit of this approach is when you have a lot of data. Also, predictive performance-wise your mileage may vary, I, for one, had run this method with n_clusters=1000 and it worked better than only with a few clusters.</p><p>SVMs are known to be slow to train on big datasets. Impossibly slow. Been there, done that. That’s why, for example, there are numerous techniques to approximate the kernel trick with much less computational resources.</p><p>By the way, let’s compare how this K-Means trick will do against classic SVM and some alternative kernel approximation methods.</p><p>The code below is inspired by <a href="https://scikit-learn.org/stable/auto_examples/miscellaneous/plot_kernel_approximation.html">these</a> <a href="https://scikit-learn.org/stable/auto_examples/kernel_approximation/plot_scalable_poly_kernels.html">two</a> scikit-learn examples.</p><pre>import matplotlib.pyplot as plt</pre><pre>import numpy as np</pre><pre>from time import time</pre><pre>from sklearn.datasets import load_breast_cancer</pre><pre>from sklearn.svm import LinearSVC, SVC<br>from sklearn import pipeline<br>from sklearn.kernel_approximation import RBFSampler, Nystroem, PolynomialCountSketch<br>from sklearn.preprocessing import MinMaxScaler, Normalizer<br>from sklearn.model_selection import train_test_split<br>from sklearn.cluster import MiniBatchKMeans</pre><pre><br>mm = pipeline.make_pipeline(MinMaxScaler(), Normalizer())</pre><pre>X, y = load_breast_cancer(return_X_y=True)<br>X = mm.fit_transform(X)</pre><pre>data_train, data_test, targets_train, targets_test = train_test_split(X, y, random_state=17)</pre><p>We will test 3 methods for kernel approximation available in the scikit-learn package, against the K-Means trick, and as baselines, we will have a linear SVM and an SVM that uses the kernel trick.</p><pre># Create a classifier: a support vector classifier<br>kernel_svm = SVC(gamma=.2, random_state=17)<br>linear_svm = LinearSVC(random_state=17)</pre><pre># create pipeline from kernel approximation and linear svm<br>feature_map_fourier = RBFSampler(gamma=.2, random_state=17)<br>feature_map_nystroem = Nystroem(gamma=.2, random_state=17)<br>feature_map_poly_cm = PolynomialCountSketch(degree=4, random_state=17)<br>feature_map_kmeans = MiniBatchKMeans(random_state=17)</pre><pre>fourier_approx_svm = pipeline.Pipeline([(&quot;feature_map&quot;, feature_map_fourier), (&quot;svm&quot;, LinearSVC(random_state=17))])</pre><pre>nystroem_approx_svm = pipeline.Pipeline([(&quot;feature_map&quot;, feature_map_nystroem), (&quot;svm&quot;, LinearSVC(random_state=17))])</pre><pre>poly_cm_approx_svm = pipeline.Pipeline([(&quot;feature_map&quot;, feature_map_poly_cm), (&quot;svm&quot;, LinearSVC(random_state=17))])</pre><pre>kmeans_approx_svm = pipeline.Pipeline([(&quot;feature_map&quot;, feature_map_kmeans), (&quot;svm&quot;, LinearSVC(random_state=17))])</pre><p>Let’s collect the timing and score results for each of our configurations.</p><pre># fit and predict using linear and kernel svm:<br>kernel_svm_time = time()<br>kernel_svm.fit(data_train, targets_train)<br>kernel_svm_score = kernel_svm.score(data_test, targets_test)<br>kernel_svm_time = time() - kernel_svm_time</pre><pre>linear_svm_time = time()<br>linear_svm.fit(data_train, targets_train)<br>linear_svm_score = linear_svm.score(data_test, targets_test)<br>linear_svm_time = time() - linear_svm_time</pre><pre>sample_sizes = 30 * np.arange(1, 10)<br>fourier_scores = []<br>nystroem_scores = []<br>poly_cm_scores = []<br>kmeans_scores = []</pre><pre>fourier_times = []<br>nystroem_times = []<br>poly_cm_times = []<br>kmeans_times = []</pre><pre>for D in sample_sizes:<br>    fourier_approx_svm.set_params(feature_map__n_components=D)<br>    nystroem_approx_svm.set_params(feature_map__n_components=D)<br>    poly_cm_approx_svm.set_params(feature_map__n_components=D)<br>    kmeans_approx_svm.set_params(feature_map__n_clusters=D)</pre><pre>    start = time()<br>    nystroem_approx_svm.fit(data_train, targets_train)<br>    nystroem_times.append(time() - start)</pre><pre>    start = time()<br>    fourier_approx_svm.fit(data_train, targets_train)<br>    fourier_times.append(time() - start)</pre><pre>    start = time()<br>    poly_cm_approx_svm.fit(data_train, targets_train)<br>    poly_cm_times.append(time() - start)</pre><pre>    start = time()<br>    kmeans_approx_svm.fit(data_train, targets_train<br>    kmeans_times.append(time() - start)</pre><pre>    fourier_score = fourier_approx_svm.score(data_test, targets_test)<br>    fourier_scores.append(fourier_score)</pre><pre>    nystroem_score = nystroem_approx_svm.score(data_test, targets_test)<br>    nystroem_scores.append(nystroem_score)</pre><pre>    poly_cm_score = poly_cm_approx_svm.score(data_test, targets_test)<br>    poly_cm_scores.append(poly_cm_score)</pre><pre>    kmeans_score = kmeans_approx_svm.score(data_test, targets_test)<br>    kmeans_scores.append(kmeans_score)</pre><p>Now let’s plot all the collected results.</p><pre>plt.figure(figsize=(16, 4))<br>accuracy = plt.subplot(211)<br>timescale = plt.subplot(212)</pre><pre>accuracy.plot(sample_sizes, nystroem_scores, label=&quot;Nystroem approx. kernel&quot;)<br>timescale.plot(sample_sizes, nystroem_times, &#39;--&#39;, label=&#39;Nystroem approx. kernel&#39;)<br>accuracy.plot(sample_sizes, fourier_scores, label=&quot;Fourier approx. kernel&quot;)<br>timescale.plot(sample_sizes, fourier_times, &#39;--&#39;, label=&#39;Fourier approx. kernel&#39;)<br>accuracy.plot(sample_sizes, poly_cm_scores, label=&quot;Polynomial Count-Min approx. kernel&quot;)<br>timescale.plot(sample_sizes, poly_cm_times, &#39;--&#39;, label=&#39;Polynomial Count-Min approx. kernel&#39;)<br>accuracy.plot(sample_sizes, kmeans_scores, label=&quot;K-Means approx. kernel&quot;)<br>timescale.plot(sample_sizes, kmeans_times, &#39;--&#39;, label=&#39;K-Means approx. kernel&#39;)</pre><pre># horizontal lines for exact rbf and linear kernels:<br>accuracy.plot([sample_sizes[0], sample_sizes[-1]],<br>[linear_svm_score, linear_svm_score], label=&quot;linear svm&quot;)<br>timescale.plot([sample_sizes[0], sample_sizes[-1]], [linear_svm_time, linear_svm_time], &#39;--&#39;, label=&#39;linear svm&#39;)</pre><pre>accuracy.plot([sample_sizes[0], sample_sizes[-1]],<br>[kernel_svm_score, kernel_svm_score], label=&quot;rbf svm&quot;)<br>timescale.plot([sample_sizes[0], sample_sizes[-1]], [kernel_svm_time, kernel_svm_time], &#39;--&#39;, label=&#39;rbf svm&#39;)</pre><p>And some more plot adjustments, to make it pretty.</p><pre># legends and labels<br>accuracy.set_title(&quot;Classification accuracy&quot;)<br>timescale.set_title(&quot;Training times&quot;)<br>accuracy.set_xlim(sample_sizes[0], sample_sizes[-1])<br>accuracy.set_xticks(())<br>accuracy.set_ylim(np.min(fourier_scores), 1)<br>timescale.set_xlabel(&quot;Sampling steps = transformed feature dimension&quot;)<br>accuracy.set_ylabel(&quot;Classification accuracy&quot;)<br>timescale.set_ylabel(&quot;Training time in seconds&quot;)<br>accuracy.legend(loc=&#39;best&#39;)<br>timescale.legend(loc=&#39;best&#39;)<br>plt.tight_layout()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*ol2jC7fj0ggEAKxo.png" /><figcaption><em>Meh. So was it all for nothing? Source: </em>the author of the post, see the code snippet above to generate it.</figcaption></figure><p>You know what? Not in the slightest. Even if it’s the slowest, K-Means as an approximation of the RBF Kernel is still a good option. I’m not kidding. You can use this special kind of K-Means in scikit-learn called MiniBatchKMeans which is one of the few algorithms that support the .partial_fit method. Combining this with a machine learning model that has .partial_fit too, like a PassiveAggressiveClassifier one can create a pretty interesting solution.</p><p>Note that the beauty of .partial_fit is twofold. First, it makes it possible to train algorithms in an out-of-core fashion, which is to say, with more data than fits in the RAM. Second, depending on your type of problem, if you could in principle (very-very in principle) never need to switch the model, it could be additionally trained right where it is deployed. That&#39;s called online learning, and it&#39;s super interesting. Something like this is <a href="https://huyenchip.com/2020/12/27/real-time-machine-learning.html">what some Chinese companies are doing</a> and in general can be pretty useful for <a href="https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/41159.pdf">AdTech</a>, because you can receive the info whenever your ad recommendation was right or wrong within seconds.</p><p>You know what, here’s a little example of this approach for out-of-core learning.</p><pre>from sklearn.cluster import MiniBatchKMeans<br>from sklearn.linear_model import PassiveAggressiveClassifier<br>from sklearn.model_selection import train_test_split<br>from sklearn.datasets import load_breast_cancer</pre><pre>import numpy as np</pre><pre><br>def batch(iterable, n=1):<br>    # source: <a href="https://stackoverflow.com/a/8290508/5428334">https://stackoverflow.com/a/8290508/5428334</a><br>    l = len(iterable)<br>    for ndx in range(0, l, n):<br>        yield iterable[ndx:min(ndx + n, l)]</pre><pre>X, y = load_breast_cancer(return_X_y=True)<br>X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=17)</pre><pre>kmeans = MiniBatchKMeans(n_clusters=100, random_state=17)<br># K-Means has a constraint, n_clusters &lt;= n_samples to fit<br>pac = PassiveAggressiveClassifier(random_state=17)</pre><pre>for x, y in zip(batch(X_train, n=100), batch(y_train, n=100)):<br>    kmeans.partial_fit(x, y)       # fit K-Means a bit<br>    x_dist = kmeans.transform(x)   # obtain distances<br>    pac.partial_fit(x_dist, y, classes=[0, 1])<br>    # learn a bit the classifier, we need to indicate the classes</pre><pre>    print(pac.score(kmeans.transform(X_test), y_test))<br><strong># 0.909 after 100 samples<br># 0.951 after 200 samples<br># 0.951 after 300 samples<br># 0.944 after 400 samples<br># 0.902 after 426 samples</strong></pre><pre># VS</pre><pre>kmeans = MiniBatchKMeans(n_clusters=100, random_state=17)<br>pac = PassiveAggressiveClassifier(random_state=17)</pre><pre>pac.fit(kmeans.fit_transform(X_train), y_train)<br>pac.score(kmeans.transform(X_test), y_test) <strong># should be ~0.951</strong></pre><h3>Epilogue</h3><p>So you’ve made it till the end. Hope now your ML toolset is richer. Maybe you’ve heard about the so-called “no free lunch” theorem; basically, there’s no silver bullet, in this case for ML problems. Maybe for the next project, the methods outlined in this post won’t work, but for the one that will come after that, they will. So just experiment, and see for yourself. And if you need an online learning algorithm/method, well, there’s a bigger chance that K-Means as a kernel approximation is the right tool for you.</p><p>By the way, there’s another blog post, also on ML, in the works now. What’s even nicer, among many other nice things in it, it describes a rather interesting way to use K-Means. But no spoilers for now. Stay tuned.</p><p>Finally, if you’re reading this, thank you! If you want to leave some feedback or just have a question, HMU on Twitter, or just leave a comment.</p><h4>Some links you might find interesting</h4><ul><li><a href="https://datascience.stackexchange.com/questions/24324/how-to-use-k-means-outputs-extracted-features-as-svm-inputs">A stackexchange discussion about using K-Means as a feature engineering tool</a></li><li><a href="https://jakevdp.github.io/PythonDataScienceHandbook/05.11-k-means.html">A more in-depth explanation of K-Means</a></li><li><a href="http://www.jcomputers.us/vol8/jcp0810-25.pdf">A research paper that uses K-Means for an efficient SVM</a></li></ul><h4>Acknowledgements</h4><p>Special thanks to <a href="https://twitter.com/dgaponcic">@dgaponcic</a> for style checks and content review, and thank you <a href="https://twitter.com/anisoara_ionela">@anisoara_ionela</a> for grammar checking this article more thoroughly than any AI ever could. You’re the best ❤</p><p><strong>P.S.</strong> I believe you noticed all these random_states in the code. If you&#39;re wondering why I added these, it&#39;s to make the code samples reproducible. Because frequently tutorials don&#39;t do this and it leaves space for cherry-picking, where the author presents only the best results, and when trying to replicate these, the reader either can&#39;t or it takes a lot of time. But know this, you can play around with the values of random_state and get widely different results. For example, when running the snippet with original features and distances to the 3 centroids, the one with a 0.727 score, with a random seed of 41 instead of 17, you can get the accuracy score of 0.944. So yeah, random_state or however else the random seed is called in your framework of choice is an important aspect to keep in mind, especially when doing research.</p><p><em>Originally published at </em><a href="https://alexandruburlacu.github.io/posts/2021-06-18-kmeans-trick"><em>https://alexandruburlacu.github.io</em></a><em> on June 19, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=724996864274" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/k-means-tricks-for-fun-and-profit-724996864274">K-Means tricks for fun and profit</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging, Tracing, Monitoring, et al.]]></title>
            <link>https://medium.com/data-science/logging-tracing-monitoring-et-al-2da0b50d646b?source=rss-dbb1c78b5aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/2da0b50d646b</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[distributed-tracing]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Alex Burlacu]]></dc:creator>
            <pubDate>Tue, 18 May 2021 22:10:00 GMT</pubDate>
            <atom:updated>2021-05-26T03:13:28.020Z</atom:updated>
            <content:encoded><![CDATA[<h4>So, you want to launch your code/app/system in production?</h4><p>Wait, before you do, ask yourself this question: <em>If something goes south, how will I know what </em><strong><em>exactly</em></strong><em> happened?</em></p><p>A good question, indeed.</p><p>A more seasoned engineer might say: <strong><em>I will use logs!!!</em></strong> But what if I tell you, logs are only the begging?</p><blockquote><em>[Disclaimer Time] </em>This article is not about some concrete technology, framework, or library, although it references some of these. It’s more of an overview/tips about what logging/tracing/et al. are and how to approach these when designing and operating software systems. The information here is based mostly from my own experience, but also from information available in papers and industry blog posts. You might need to google some stuff while/after reading it, especially if you’ve never operated a system running in production.</blockquote><h3>Act 1: I’ll set up logs, alright…</h3><p>So, what exactly is a log?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*waGgDsFNxEM2EM0J.gif" /><figcaption>Source: <a href="https://media.giphy.com/media/xUOxfbAOLZmR356YgM/giphy.gif">https://media.giphy.com/media/xUOxfbAOLZmR356YgM/giphy.gif</a></figcaption></figure><p>Technically, this is a log, but I want to talk about other kinds of logs.</p><blockquote><strong><em>Logs are a record about some event in a system</em></strong></blockquote><p>Pretty abstract, huh? A log is like an entry in a journal about something that happened, maybe with some context. Somewhat like the Twitter feed of an Apple-reporter during the WWDC event. You have time, you have a record of something that just happened, and maybe you have context too. Now, jokes aside, logs are necessary for a system running in production. They help you uncover what was happening moments before applications crash. Or malicious activity. Or other stuff. But how do we make <strong>good</strong> logs?</p><h3>Tenets of a good log message</h3><p>So, how should we design our logs? Here are some tenets:</p><ul><li>Thy logs must be <strong>hierarchical</strong>: we need to respect the distinction between DEBUG/INFO/WARNING/ERROR and possibly other levels. We should not crowd the system with WARNING logs when INFO or DEBUG logs are more appropriate. Crowding also refers to how much information a log contains. That said, a good idea for an ERROR log is to register as much information as possible to aid in debugging. Use DEBUG-level logs to register information about what setting the program is using, even how much time or resources some subroutine is using, but don&#39;t abuse this. As for INFO logs, anything in between. Like information about a call to a top-level route handler in an HTTP server. Also, INFO logs are the right way to use prints in a system.</li><li>Thy logs must be <strong>informative</strong>: A good rule of thumb is to log everything that might help you debug your system. If an error happens, you will want to log the traceback. Also, logging the context in which the error happened will prove to be useful. By context, I mean some surrounding variables, which might have something to do with the failure. If your system is running with multiple processes or is multithreaded, or multi-whatever, do yourself a favor and log the PIDs/Thread IDs. Finally, be very careful with how you represent time, explaining why would require an entire blog, but time in computer systems is a pain, <a href="https://www.youtube.com/watch?v=-5wpm-gesOY">see for yourself</a>.</li></ul><pre>ERROR: Error name, message, traceback, variables in scope is possible<br>WARNING: Warning name, message<br>INFO: Calls to top-level functions/handlers, like: [2021-05-17 00:06:23] INFO: GET /posts 200 OK<br>DEBUG: Program setup/initialization info, possibly memory or performance information*<br><br>*: more on that later</pre><ul><li>Thy logs must be <strong>filterable</strong>: logs are meant to be analyzed. Make them as searchable as possible. Consider formatting them as JSON documents, and don’t abuse nesting.</li></ul><p>Why not? If the JSON is too nested, it becomes hard to search/analyze, defying its purpose.</p><p>For example, Elasticsearch can’t properly index JSONs with two or more levels of nesting. That is, something like the example below can be indexed:</p><pre>{&quot;timestamp&quot;: &quot;2021-05-18T21:09:54Z&quot;, &quot;level&quot;: &quot;error&quot;, &quot;msg&quot;: &quot;bad thing happened&quot;}</pre><p>Even something like this:</p><pre>{&quot;timestamp&quot;: {&quot;date&quot;: &quot;17th May, 2021&quot;, &quot;time&quot;: &quot;11:30:30am&quot;}, &quot;level&quot;: &quot;error&quot;, &quot;msg&quot;: &quot;bad thing happened&quot;}</pre><p>But do something like this:</p><pre>{&quot;timestamp&quot;: {<br>    &quot;date&quot;: &quot;17th May, 2021&quot;,<br>    &quot;time&quot;: [11, 30, 30, 124]<br>    },<br> &quot;level&quot;: &quot;error&quot;,<br> &quot;msg&quot;: &quot;bad thing happened&quot;,<br> &quot;context&quot;: {<br>    &quot;some_key_for_multiple_values&quot;: []<br>    }<br>}</pre><p>And Elastic will treat your deeply nested elements like strings, and then good luck filtering and aggregating these logs. So keep it flat, whenever possible.</p><p>Another good format is NCSA Common log format, but if possible, choose JSON. Why? Most log analysis tools use JSON. Something like NCSA Common log format is better for smaller systems, where you can search your logs with grep and friends. Finally: <em>Whatever format you choose, be consistent across your whole system</em></p><pre>Bad log (1): [2021-05-17 12:30:30] ERROR: KeyError // JSON version would be just as bad</pre><pre>Bad log (2): {&quot;datetime&quot;: {&quot;date&quot;: &quot;17th May, 2021&quot;, &quot;time&quot;: &quot;11:30:30am&quot;}, &quot;type&quot;: &quot;ERROR&quot;, &quot;msg&quot;: &quot;A KeyError error occured in function some_function&quot;}</pre><pre>Better log: {&quot;timestamp&quot;: &quot;2021-05-18T21:09:54Z&quot;, &quot;level&quot;: &quot;error&quot;, &quot;pid&quot;: 1201, &quot;traceback&quot;: &lt;your traceback as a string&gt;, &quot;msg&quot;: &quot;KeyError: &#39;key_name&#39;&quot;}</pre><h3>Some wisdom on logging ops</h3><p>So you have well-written logs. That’s great!!</p><p>But now you have to decide how to access and analyze them. Funny thing, these decisions should also be guided by the stage and the scale of your system. In other words, I would advise against a complex infrastructure if you have one app serving a few hundred people.</p><p>Now we should dive into details.</p><p>You will roughly have three stages.</p><ul><li>Log collection/shipment</li><li>Log storage</li><li>Log processing/analytics</li></ul><p>First, log collection. We want to save our logs somewhere and not just let them print to stderr/stdout. So, now we have to think about where do we write them. It could be a file, or to Syslog, for example, or we could even write them into a TCP or UDP socket, sending them away to some logging server. To be honest, all choices are somewhat good. As long as you don’t block the thread where the action happens, you should be fine, otherwise, prepare for a performance hit.</p><p>Regarding storage, for a simple app leaving them in file format should work for a while, but eventually, a storage solution with indexing support or really anything that can help you quickly search your logs will be advised.</p><p>Once you have multiple services, you can think of a centralized logging server, something like an ELK (Elasticsearch, Logstash, Kibana) cluster, with one or a few Elastic instances in a cluster setup.</p><p>So here comes my personal opinion: you should start by logging into a file, and mandatory ensure log file rotation because you don’t want a single 10GB text file. Believe me… you don’t. At some point, you will also have to think of log compression and possibly log shipping. Log shipping means transferring the logs from where these were created to where these will be analyzed and stored for a long time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*mgwlZUSghzK9jsLm.png" /><figcaption>Source: My own drawing</figcaption></figure><p>When it comes to log shipping, I would strongly suggest using TCP or HTTP over UDP and other protocols. Why, you may ask? Because first of all, with UDP you might lose logs while transferring them due to (1) no way of retransmitting lost packets, (2) no flow control, which might be the cause of lost packets, but also because with UDP message size is limited to 65KB of data, or even less, depending on network settings, which quite frankly could be not nearly enough. Also, your company firewalls might block this kind of traffic. So, a lot of trouble.</p><p>Having a centralized logging solution, you will now absolutely need to ship the logs, and having them first written to a file will prove a very nice idea because now your logs won’t be lost in case of network outages, server failure, logging system failure or any of the above mentioned being too slow.</p><p>Nice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*P9l9rgZzFGWg_JK2.gif" /><figcaption>Source: <a href="https://media.giphy.com/media/k0hKRTq5l9HByWNP1j/giphy.gif">https://media.giphy.com/media/k0hKRTq5l9HByWNP1j/giphy.gif</a></figcaption></figure><h3>Act 1.1: Hey, I think I can make a chatbot to notify me when something blows up</h3><p>Yup, you can. And if you want to reduce MTTR you most likely should. Just take into account a few things.</p><ul><li>First and foremost, if you have the possibility, set up alerting thresholds. You don’t want to be notified when something is even slightly off every. single. time. Maybe it’s some unique (non-critical) event, no need to bother, while if the issue happens frequently, you better be notified.</li><li>Another consideration, when it comes to alerting, is the possibility to have <strong>escalation alerting</strong>. First, send an alert via email. If no action was taken, now send it to a chat group of the responsible team. Still no activity? Send it in DM to an engineer, or even to a technical manager.</li><li>Finally, just aggregate the stuff, no need for 12, or a hundred, emails/Slack messages of the same issue. Something like one log message and then some text like X occurred 25 times in the last Y seconds should be good.</li></ul><p>When it comes to what tools to use for alerting, well, you have Sentry, also to my knowledge, it is possible to set up alerting in Kibana, although I don’t know whenever this is a paid option or free, and there are of course other tools.</p><p>This is by no means a definitive guide on how to do it, only some things to keep in mind. This whole blog post isn’t a definitive guide if you haven’t noticed yet.</p><h3>Act 2: My system is slow, I guess I’ll log execution time, and # of requests, and …</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*Ha59DKUgJsvE3IwU.png" /><figcaption>Source: <a href="https://knowyourmeme.com/photos/1246726-fallout">https://knowyourmeme.com/photos/1246726-fallout</a></figcaption></figure><p>… just. Stop. Please. The fact that you <strong>can</strong> do it, doesn’t mean you should. Welcome to the world of telemetry and performance monitoring, where you will initially wonder, why not just use logs? I mean, in principle you could do this, but better to have a different infrastructure, to not mess everything up.</p><p>Mess up how? Well, if you’re like me, you might want to set up performance monitoring not just at the route controller level, to see how much requests take to be handled and responded to (assuming a hypothetical server). You will also want to track how much time queries to the database take to execute, even functions! And now you have a ton of very fine-grained info, which will for sure overload the logging infrastructure. You don’t want that. Besides, even if all runs smoothly, your read and write patterns will be different. Log analysis queries can be much more complex than analysis required for performance monitoring. Also, performance monitoring usually has smaller messages that need to be recorded with lower latency. All in all, better set up a dedicated infrastructure for this.</p><p>The easiest thing is of course to use TRACE level logging, and as said earlier, dedicated infrastructure for performance monitoring. But this works only on small scale, where frankly, you don&#39;t even need performance monitoring.</p><p>As the system scales, you might start looking towards a more restricted type of logs, maybe some binary protocols, given that you will be sending small packets of information right away, very frequently.</p><p>Performance monitoring has a bit of a different write and query patterns than log analytics (ik, said it earlier), so different storage is recommended. Queries are simpler mainly showing trends, time series, current values, or some simple aggregate values, like counts, means, medians, and percentiles, and writes are very frequent but with little data, only a few metrics, compared with logging tracebacks and contexts and stuff like that.</p><p>That’s why for example ELK stack is more common in logging infrastructure, where Elasticsearch can index and analyze even very unstructured data, and stuff like Grafana + Prometheus are more commonly used for performance monitoring. Prometheus, among other things, contains a time-series database, just the right thing to store and quickly query performance metrics.</p><p>Also, when it comes to performance analysis, you will want to monitor your system utilization, not just the stuff intrinsic to your code. If you’re using Prometheus, that’s easy to do.</p><h3>Act 3: My microservice system is slow, but I can’t figure out why</h3><p><strong>First, a likbez (crash-course) on networking and dynamic systems</strong>: Against our intuition, a computer network is a shared resource with a limited capacity. This basically means if one service is very chatty, it will influence the throughput and latency for all the rest. Also given that networks are a priori not 100% reliable and we mostly use TCP-based traffic, in the network, there will be plenty of packets (chunks of data, retransmissions, packets from administrative protocols). That’s only half the problem though. There’s more 😉</p><p>Our services are dependent upon each other and upon 3rd parties. So if one service is slow, it might influence other services, even ones that are not directly interacting with it. One metaphor to help you think of it is a spider web. When you touch it on one side, it will ripple on the other side. Kinda like a butterfly effect. And that’s not just a simple comparison, you could indeed see failure due to some other service being somewhat slower.</p><p>So, how do we monitor this?</p><p>Maybe logs? Or something like performance monitoring from the previous act?</p><p>Well, I mean, it’s a start, but only logs won’t cut it. Because we don’t see the full picture, specifically, we don’t see the interaction between services, only each individual’s performance. We need something more. Enter <strong>tracing</strong>.</p><p>First, a good mental model about tracing is that it’s like logging, but with a <a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/CorrelationIdentifier.html">correlation identifier</a>, which makes it possible to combine said logs into a “trace”. A trace like this now can show us how, for example, a single request spans multiple services, how much time does each step takes and even how much time was spent on communication. All this can help uncover bugs and performance bottlenecks which a simple performance monitoring tool, or just logs, won’t be able to do. Tracing will help you find bottleneck services, and sometimes even aid you in debugging distributed systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/0*NacCxgaqgu9ETL8x.png" /><figcaption>Source: My own drawing, inspired by Jaeger Architecture</figcaption></figure><p>Traces should be thought of as an extension to performance monitoring tools, rather than logs. Traces’ primary purpose is to uncover performance issues, also sometimes pinpoint the reason a specific operation failed. You could use them as logs, but don’t overload them with information, otherwise, your collection, storage, and analysis infrastructure will cry.</p><p>How to structure your traces? The easiest thing to do is to use tools that automagically will patch your dependencies like database clients, web servers, and HTTP/RPC clients and be done with it. Sensible defaults, you know. If you want to have more control, be prepared to write some boilerplate, especially if you want to manually control what things will be propagated between services. When it comes to adding info to your spans (the pieces which combined form a trace) don’t add your whole application context, only the most important things, for example, current configurations of your system.</p><p>Side note, sometimes it is important to correlate traces with logs, for this you can use yet another correlation identifier, for a more in-depth analysis of your system, combining traces with individual logs.</p><p>There are some existing Open Source tools with great support, like <a href="https://www.jaegertracing.io/">Jaeger</a> and <a href="https://zipkin.io/">Zipkin</a>, there are also industry initiatives like OpenTracing, OpenCensus and “their combination” OpenTelemetry, not to mention a few trace formats, like <a href="https://w3c.github.io/trace-context/">W3C Trace Context</a> and <a href="https://github.com/openzipkin/b3-propagation">Zipkin B3</a> formats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*Gq4CYPQhVHjt2mSW.png" /><figcaption>Source: My own drawing, inspired by Jaeger Architecture</figcaption></figure><p>A common architecture for tracing subsystems is a combination of a sidecar, collector, storage, and “presenter” components, not to mention the client library. When it comes to using tracing in a serverless setup it gets tricky, one solution would be to bypass the sidecar and send data directly to the collector, <a href="https://www.jaegertracing.io/docs/1.22/faq/#do-i-need-to-run-jaeger-agent">but you will lose some nice features</a>.</p><p>Tracing, in general, is huuuuge topic, and covering it would require at least one more long-read article. That’s why, for more information, I’d like to point you towards <a href="https://static.googleusercontent.com/media/research.google.com/en//archive/papers/dapper-2010-1.pdf">these</a> two <a href="https://www.pdl.cmu.edu/PDL-FTP/SelfStar/CMU-PDL-14-102.pdf">articles</a> and <a href="https://eng.uber.com/distributed-tracing/">this post from Uber</a>. In these you’ll find more “war stories” on how such systems where implemented (first article and the post from Uber) and also such important topics as trace sampling strategies and trace visualizations (second article).</p><h3>Final act: Welcome to observability!!!</h3><p>Observability, what?</p><p>Observability is the property of a system to be understood. It’s a property of how well can one infer the internal state of something from its external outputs. It’s a spectrum and depending on where your system stands, you can use monitoring and alerting more or less efficiently. In other words, if a system is observable you can understand what is happening within it from its outputs.</p><p>We need to design our systems with observability in mind. And with all the stuff outlined above, that should become a doable task.</p><p>I prefer to think of observability, with a proper incident response procedure, of course, as a way to make said system anti-fragile (see the works of Nasim Taleb), because with every failure and issue that happens, it “learns”, on the organizational level, to be better. Or one could argue that on the contrary, the system now becomes more fragile because with every fix we believe more and more that the system is now unkillable, which it never will be.</p><p>Pick for yourself, but don’t forget to use logging. At least you’ll know when and why things go south, and that’s something.</p><h3>Epilogue</h3><p>You’ve made it! Congrats! Now you have some very important knowledge of how to be prepared when manure hits the proverbial fan in production. This knowledge should help you debug even super-obscure bugs. Of course, this isn’t going to be easy, plus you now have an entire infrastructure to take care of, but hey, if this helps reducing time to solve an issue from 1 week (or more) to 1, maybe 2 days, it might be worth it.</p><p>I know for a fact that it was worth it for me, time and time again when it helped me quickly identify edge cases, stupid misconfigurations, and performance bottlenecks.</p><p>So yeah, that’s it for now. Incredibly, it didn’t take much time since my last blog post.</p><p>Finally, if you’re reading this, I’d like to thank you. Let me know what are your thoughts about it via Twitter, for now, until I plug in some form of a comment section. Your feedback is valuable for me.</p><p><em>Originally published at </em><a href="https://alexandruburlacu.github.io/posts/2021-05-20-logs-traces-how-to"><em>https://alexandruburlacu.github.io</em></a><em> on May 20, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2da0b50d646b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/logging-tracing-monitoring-et-al-2da0b50d646b">Logging, Tracing, Monitoring, et al.</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Elixir pattern matching magic]]></title>
            <link>https://medium.com/@alexburlacu1996/elixir-pattern-matching-magic-7c5019ecf7f2?source=rss-dbb1c78b5aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c5019ecf7f2</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[pattern-matching]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alex Burlacu]]></dc:creator>
            <pubDate>Sun, 09 May 2021 13:03:14 GMT</pubDate>
            <atom:updated>2021-05-09T13:03:14.469Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prologue</h3><p>So, a while ago, while preparing for an off-topic lecture about polymorphism and type systems, I recalled an interesting concept called <em>multiple dispatch</em>. I won’t go into details of what it is, so if you’re interested, check these links: <a href="http://matthewrocklin.com/blog/work/2014/02/25/Multiple-Dispatch">1</a>, <a href="https://en.wikipedia.org/wiki/Multiple_dispatch">2</a>, <a href="https://eli.thegreenplace.net/2016/a-polyglots-guide-to-multiple-dispatch/">3</a>. Anyway, while brushing up my knowledge about multiple dispatch, I found an even more powerful technique, called <a href="https://en.wikipedia.org/wiki/Predicate_dispatch"><em>predicate dispatch</em></a>.</p><p>To me, it seemed a lot like what is possible through pattern matching in functional languages. After some research, I asked on SO whenever my assumption was right, <a href="https://stackoverflow.com/q/66863443/5428334">here</a>. TL;DR: no answer as of today(2021/05/07).</p><p><strong>Why am I telling you all this? Because that’s how I decided to write an article about how cool pattern matching is, specifically in Elixir, and even if it’s not the same as predicate dispatch, it’s pretty damn powerful nevertheless.</strong></p><p>So let’s get started!</p><blockquote>The post was originally published at <a href="https://alexandruburlacu.github.io/posts/2021-05-07-elixir-pattern-matching-magic">https://alexandruburlacu.github.io/posts/2021-05-07-elixir-pattern-matching-magic</a></blockquote><h3>Basics</h3><p>I will quickly go through the basics of Elixir pattern matching, before diving into real neat stuff.</p><p>In Elixir = doesn’t just assign some value to some variable, it also matches the left-hand side of the expression with the right-hand side. So as a result, doing something like the code below is entirely possible.</p><pre>iex(0)&gt; x = 2<br>2<br>iex(1)&gt; y = 4<br>4<br>iex(2)&gt; 4 = y<br>4<br>iex(3)&gt; 2 = y<br>** (MatchError) no match of right hand side value: 4</pre><p>No big deal, right? Wrong! Because of this interesting property, we can do matching on composite data types, for example on lists.</p><h3>Lists</h3><p>In Elixir [] = [] is a valid expression. But now, we can also write something like:</p><pre>iex(0)&gt; xs = [1, 2]<br>[1, 2]<br>iex(1)&gt; [x, y] = xs<br>[1, 2]<br>iex(2)&gt; x<br>1<br>iex(3)&gt; y<br>2</pre><p>Starts to get interesting, eh? But wait, there’s more!</p><pre>iex(0)&gt; [head | tail] = [1, 2, 3, 4, 5]<br>[1, 2, 3, 4, 5]<br>iex(1)&gt; head<br>1<br>iex(2)&gt; tail<br>[2, 3, 4, 5]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*OAbd7Y9BlID7qsVr.gif" /></figure><p>Aaaaand moreeee!!!!</p><pre>iex(0)&gt; [head, next_to_it | tail] = [1, 2, 3, 4, 5]<br>[1, 2, 3, 4, 5]<br>iex(1)&gt; head<br>1<br>iex(2)&gt; next_to_it<br>2<br>iex(3)&gt; tail<br>[3, 4, 5]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*GTu0ps16gcz56CTb.gif" /></figure><p>Noice.</p><h3>Tuples</h3><p>Alright, so pattern matching can do interesting stuff. In Elixir it’s so deeply ingrained that it’s used for example to signal whenever or not we have an error. For this, pattern matching on tuples is used.</p><pre>iex(0)&gt; {:ok, value} = SomeModule.some_function()<br>{:ok, &quot;the value&quot;}<br>iex(1)&gt; # If the function returns something else than {:ok, value}<br>iex(2)&gt; {:ok, value} = SomeModule.some_function()<br>** (MatchError) no match of right hand side value: {:ok, value}</pre><p>Elixir has a special control structure to enable more flexible usage of pattern matching, it’s called case.</p><pre>iex(0)&gt; x = {:ok, &quot;is fine&quot;}<br>iex(1)&gt; case x do<br>...(1)&gt;   {:ok, v} -&gt; v<br>...(1)&gt;   _ -&gt; &quot;nothing at all&quot;<br>...(1)&gt; end<br>&quot;is fine&quot;<br>iex(2)&gt; x = {:err, &quot;not ok&quot;}<br>iex(3)&gt; case x do<br>...(3)&gt;   {:ok, v} -&gt; v<br>...(3)&gt;   _ -&gt; &quot;nothing at all&quot;<br>...(3)&gt; end<br>&quot;nothing at all&quot;</pre><p>This concludes the basics part, so now we’re gonna dive into more interesting stuff.</p><h3>Functions</h3><p>Elixir can use pattern matching even in function definitions, like in Haskell. And by the way, that’s one of the most performant options, usually.</p><pre>defmodule FactorialM do<br>    def factorial(0), do: 1<br>    def factorial(1), do: 1<br>    def factorial(x) do<br>        x * factorial(x-1)<br>    end<br>end</pre><p>Can you spot a problem with this function? Well, what if we pass a floating-point value instead of an integer? Think what would happen, and compare with the answer1 at the end of the article.</p><p>How can you fix it? Enter guards.</p><pre>defmodule FactorialM do<br>    def factorial(0), do: 1<br>    def factorial(1), do: 1<br>    def factorial(x) when is_integer(x) do<br>        x * factorial(x-1)<br>    end<br>    def factorial(_), do: raise RuntimeError, &quot;Input should be integer&quot;<br>end</pre><p>So now we can also define different paths for code execution depending on whenever or not our guard(s) are satisfied. Guards in Elixir are fairly limited, and hard-ish to extend, for safety reasons. Guards should be pure functions, and even if you try to define them using macros, the compiler still can check whenever they can be distilled down to existing guards and logical operators or not. For more information, see <a href="https://hexdocs.pm/elixir/master/patterns-and-guards.html">this documentation page</a> and <a href="https://keathley.io/blog/elixir-guard-clauses.html">this little tutorial/blog post</a> on how to write guards.</p><p>Finally, we can combine pattern matching capabilities of functions with those of tuples and lists and implement fairly interesting things. For example a map function.</p><pre>defmodule FairlyInteresting do<br>    def map([], _func), do: []<br>    def map([head | tail], func) when is_function(func) do<br>        [func.(head) | map(tail, func)]<br>    end<br>end</pre><p>Also, using pattern matching on tuples in function prototypes is the go-to way of using Elixir’s GenServer, GenStage, and other Gen-things. This pattern is inherited from Erlang’s OTP and is pretty beautiful if you ask me.</p><pre>defmodule Stack do<br>    @moduledoc &quot;&quot;&quot;Taken from: https://hexdocs.pm/elixir/master/GenServer.html&quot;&quot;&quot;<br>    use GenServer</pre><pre>    # Callbacks<br>    @impl true<br>    def init(stack) do<br>        {:ok, stack}<br>    end</pre><pre>    @impl true<br>    def handle_call(:pop, _from, [head | tail]) do<br>        {:reply, head, tail}<br>    end</pre><pre>    @impl true<br>    def handle_cast({:push, element}, state) do<br>        {:noreply, [element | state]}<br>    end<br>end</pre><h3>It’s getting more interesting</h3><p>Remember I told you pattern matching can be applied to composite data? Well, it’s not just lists, it’s also maps, and by extension structs, here:</p><pre>iex(0)&gt; kv = %{key: :value}<br>{key: :value}<br>iex(1)&gt; %{key: data} = kv<br>{key: :value}<br>iex(2)&gt; data<br>:value</pre><p>And with structs:</p><pre>iex(0)&gt; defmodule AStruct do<br>...(0)&gt;     defstruct [:state]<br>...(0)&gt; end<br># I&#39;ll omit this for brevety<br>iex(1)&gt; s = %AStruct{state: 12}<br>%AStruct{state: 12}<br>iex(3)&gt; s.state<br>12<br>iex(4)&gt; %{state: st} = s # recall, a struct is just syntactic sugar for a map<br>%AStruct{state: 12}<br>iex(5)&gt; st<br>12<br>iex(6)&gt; %AStruct{state: st} = s<br>%AStruct{state: 12}<br>iex(7)&gt; st<br>12</pre><h3>The as-pattern</h3><p>What if you need to match a function parameter with some specific structure, but you also need a reference to the entire value. Have you ever heard about <strong>as-patterns</strong>?</p><pre>defmodule FairlyInteresting do<br>    def merge([], xs), do: xs<br>    def merge(xs, []), do: xs<br>    def merge(first=[x|xs], second=[y|ys]) do<br>        if x &lt; y do<br>            [x | merge(xs, second)]<br>        else<br>            [y | merge(ys, first)]<br>        end<br>    end<br>end</pre><pre># ...</pre><pre>iex(0)&gt; FairlyInteresting.merge [1, 3, 4, 7], [2, 2, 4, 8, 9]<br>[1, 2, 2, 3, 4, 4, 7, 8, 9]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*NBXw2jL5KjBinXtG.gif" /></figure><p>You still with us? Yes? Good, because the fun part hasn’t even started yet.</p><h3>Partial functions</h3><p>Moving on, in Elixir it is possible to define partial functions. Mathematically speaking, a partial function is a function defined only for some values, not for the whole set of values. For example, the division is technically a partial function, because we can’t define it when the divisor is 0. We can make a partial function explicit via pattern matching. And it also works for anonymous functions!</p><pre>iex(0)&gt; partial = fn <br>...(0)&gt;     {:ok, value} when is_number(value) -&gt; value * 2<br>...(0)&gt;     {:notok, _} -&gt; :i_mean_its_not_ok<br>...(0)&gt; end<br>iex(1)&gt; partial.(12)<br># raises a FunctionClauseError<br>iex(2)&gt; partial.({:ok, 12})<br>24</pre><h3>The pin (not my card’s)</h3><p>Finally, no discussion about pattern matching in Elixir would be complete without the ^ operator. So what is it? It is commonly known as the pin operator, and it allows pattern matching without any assignment.</p><p>Recall that normally, using = we perform both pattern matching <strong>and</strong> assignment. That is, we check whenever the left-hand side of the expression matches the right-hand side, and if so, all the variables in the expression get assigned to corresponding values.</p><p>Ex. [1, x, y] = [1, 2, 3] # x = 2, y = 3.</p><p>So, using ^ we can pattern match, but not assign. Like this:</p><pre>iex(0)&gt; x = 2<br>2<br>iex(1)&gt; ^x = 3<br>** (MatchError) no match of right hand side value: 3<br>iex(2)&gt; ^x = 2<br>2</pre><p>You might ask, where would I use this? Well, what about deciding in runtime what matching criteria are you interested in. For example:</p><pre>iex(0)&gt; status_of_interest = :wip # imagine that it is decided while the program is running<br>iex(1)&gt; # maybe can even change throughout the program lifetime<br>iex(2)&gt; partial = fn <br>...(2)&gt;     {^status_of_interest, value} when is_number(value) -&gt; value * 2<br>...(2)&gt;     {:notok, _} -&gt; :i_mean_its_not_ok<br>...(2)&gt; end<br>iex(3)&gt; partial.({:ok, 12})<br># raises a FunctionClauseError<br>iex(4)&gt; partial.({:wip, 11})<br>22</pre><h3>Leveling up</h3><p>Now we’ve seen enough, let’s combine everything!</p><pre>defmodule Measurement do<br>    defstruct [:prob, status: :ok]<br>end</pre><pre>defmodule Measurement.CDF do<br>    defstruct [:value]<br>end</pre><pre>defmodule FairlyInteresting do<br>    @doc &quot;CDF stands for cummulative density function&quot;<br>    def kinda_cdf([], acc, _func), do: [%Measurement.CDF{value: acc}]</pre><pre>    # So, now we have pattern matching on structs, inside lists,<br>    #  with as-patterns and guards, isn&#39;t it cool?<br>    def kinda_cdf([%Measurement{prob: t, status: :ok}=head | tail], acc, func)<br>        when is_function(func, 2) do<br>        [%Measurement.CDF{value: acc} | kinda_cdf(tail, func.(t, acc), func)]<br>    end</pre><pre>    def kinda_cdf([_head | tail], acc, func) when is_function(func, 2) do<br>        kinda_cdf(tail, acc, func)<br>    end<br>end</pre><pre># ...</pre><pre>iex(0)&gt; ms = [%Measurement{prob: 0.11}, %Measurement{prob: 0.07},<br>...(0)&gt;       %Measurement{prob: 0.31, status: :notok}, %Measurement{prob: 0.21},<br>...(0)&gt;       %Measurement{prob: 0.17, status: :ok}, %Measurement{prob: 0.08, status: :notok}]<br>[<br>  %Measurement{prob: 0.11, status: :ok},<br>  %Measurement{prob: 0.07, status: :ok},<br>  %Measurement{prob: 0.31, status: :notok},<br>  %Measurement{prob: 0.21, status: :ok},<br>  %Measurement{prob: 0.17, status: :ok},<br>  %Measurement{prob: 0.08, status: :notok}<br>]<br>iex(1)&gt; FairlyInteresting.kinda_cdf ms, 0.0, &amp;(&amp;1+&amp;2)<br>[<br>  %Measurement.CDF{value: 0.0},<br>  %Measurement.CDF{value: 0.11},<br>  %Measurement.CDF{value: 0.18},<br>  %Measurement.CDF{value: 0.39},<br>  %Measurement.CDF{value: 0.56}<br>]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*o1-ML97xEugzhQl9.gif" /></figure><p>If you’re like Patrick right now, I don’t blame you, even I was a bit shocked while writing this.</p><p>And if that’s not enough, we move onto the mindbending stuff. Bear with me.</p><h3>Working with bits</h3><p>Something cool that Erlang and Elixir can do is pattern matching on binary data. Isn’t this amazing?</p><p>Binary pattern matching in Erlang and Elixir exists because Erlang was initially developed to be used for network and telecom programming, that is implementing software for switches, routers, and servers; developing protocols, and doing this efficiently. Binary matching allows for very concise parsing of binary protocols.</p><pre> #  0                   1                   2                   3<br> #  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1<br> # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br> # |          Source Port          |       Destination Port        |<br> # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br> # |                        Sequence Number                        |<br> # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br> # |                    Acknowledgment Number                      |<br> # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br> # | Data |                                                        |<br> # |Offset|                      data                              |<br> # |      |                                                        |<br> # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+<br> #                    Some Binary Header Format<br></pre><pre>iex(0)&gt; source_port = &lt;&lt;12070 :: 16&gt;&gt;<br>&quot;/&amp;&quot;<br>iex(1)&gt; destination_port = &lt;&lt;80 :: 16&gt;&gt;<br>&lt;&lt;0, 80&gt;&gt;<br>iex(2)&gt; seq_num = &lt;&lt;12_345_678 :: 32&gt;&gt;<br>&lt;&lt;0, 188, 97, 78&gt;&gt;<br>iex(3)&gt; offset = &lt;&lt;0 :: 3&gt;&gt; # you can even specify bit-strings<br>&lt;&lt;0::size(3)&gt;&gt;</pre><p>Now let’s assemble the packet.</p><pre>iex(4)&gt; header = &lt;&lt; source_port &lt;&gt; destination_port &lt;&gt; seq_num &lt;&gt; seq_num, offset :: bitstring&gt;&gt;<br>&lt;&lt;47, 38, 0, 80, 0, 188, 97, 78, 0, 188, 97, 78, 0::size(3)&gt;&gt;<br>iex(5)&gt; packet = &lt;&lt;header :: bitstring, &lt;&lt;&quot;and here comes the data&quot;&gt;&gt; &gt;&gt;<br>&lt;&lt;47, 38, 0, 80, 0, 188, 97, 78, 0, 188, 97, 78, 12, 45, 204, 132, 13, 12, 174,<br>  76, 164, 12, 109, 237, 172, 174, 100, 14, 141, 12, 164, 12, 140, 46, 140,<br>  1::size(3)&gt;&gt;</pre><p>Notice the strange way we assemble the packet. Because we are working on the bit level, not even on the byte level, sometimes concatenation (&lt;&gt;) isn’t possible. That’s why we use the list-like behaviour of &lt;&lt;&gt;&gt;, that is to say this form: &lt;&lt; 12::3, &lt;&lt;1::2, &lt;&lt;3::3&gt;&gt; &gt;&gt; &gt;&gt; will be equivalent to this &lt;&lt;12::3, 1::2, 3::3&gt;&gt;.</p><p>Also, we need to specify that we’re dealing with a bitstring not a sequence of bytes.</p><p>And now we match.</p><pre>iex(6)&gt; &lt;&lt;_sp :: 16, _dp :: 16, _seq_num :: 32, ack_num :: 32, _offset :: 3, data :: bitstring&gt;&gt; = packet<br>&lt;&lt;47, 38, 0, 80, 0, 188, 97, 78, 0, 188, 97, 78, 12, 45, 204, 132, 13, 12, 174,<br>  76, 164, 12, 109, 237, 172, 174, 100, 14, 141, 12, 164, 12, 140, 46, 140,<br>  1::size(3)&gt;&gt;<br>iex(7)&gt; data<br>&quot;and here comes the data&quot;</pre><p>Nice, but can we use ^ for more powerful matching?</p><pre>iex(5)&gt; &lt;&lt;^i, 32, ^have, 32, ^a, &quot;n &quot;, apple&gt;&gt; = &quot;I have an apple&quot;<br>** (MatchError) no match of right hand side value: &quot;I have an apple&quot;</pre><p>Now, this is one thing you can’t do. You can’t combine &lt;&lt;&gt;&gt; and ^ operators. Shame. But it’s useful never the less, you’ll see in a moment.</p><h3>A bit about strings</h3><p>In Elixir you can even match the text. Nice, isn’t it? But text, or strings, are arrays of bytes, so, it’s pretty much obvious why can we do it.</p><pre>iex(0)&gt; partial = fn <br>...(0)&gt;     {:ok, &quot;he&quot; &lt;&gt; v} -&gt; v<br>...(0)&gt;     {:still_ok, v &lt;&gt; &quot;ou&quot;} -&gt; v<br>...(0)&gt;     _ -&gt; :nope<br>...(0)&gt; end<br>iex(1)&gt; <br>iex(2)&gt; partial = fn # won&#39;t compile<br>...(2)&gt;     {:ok, &quot;he&quot; &lt;&gt; v} -&gt; v<br>...(2)&gt;     {:still_ok, v &lt;&gt; &quot;ou&quot;} -&gt; v # because of this<br>...(2)&gt; _ -&gt; :nope<br>...(2)&gt; end<br>** (ArgumentError) the left argument of &lt;&gt; operator inside a match should always be a literal binary because its size can&#39;t be verified.</pre><p>Well, the capability is very limited, because potentially you could have a very long string, and checking its end potentially could be a very expensive operation. There’s a way tho.</p><p>Back to bit sequences. So, because of the Erlang legacy, strings can be treated as sequences of characters, which in turn are just sequences of short unsigned integers. So, if you know the size of the matchable subsequence, you could potentially match even in the middle of the string.</p><p>Just in case someone needed it. If you need to match on the part of the string that is in the known middle and you aware of its length then you can use binary matching:</p><pre>iex(1)&gt; &lt;&lt;&quot;I &quot;, v::binary-size(9), &quot;ing&quot;&gt;&gt; = &quot;I got a string&quot;<br>iex(2)&gt; v<br>&quot;got a str&quot;</pre><p>Strings and bits and bytes and pattern matching in Elixir is a huge topic, so don’t worry if you’re confused at this moment. You could check <a href="https://medium.com/blackode/playing-with-elixir-binaries-strings-dd01a40039d5">this</a> post about exactly that if my ramblings didn’t make sense ;)</p><h3>Epilogue</h3><p>I hope you like it. I don’t know about you, but I like to discover weird powerful things like all the stuff above. I mean, lists and tuples are fine, but to be able to pattern match on bits, that’s some Voodoo magic in here.</p><p>So yeah, that’s it for now. I might write some more about advanced Elixir stuff, most likely related to the actor model. Let’s hope it won’t take as long as usual.</p><p>If you’re reading this, I’d like to thank you and hope all of the above written will be of great help for you, as it was for me. Let me know what are your thoughts about it in the comments. Also, be sure to check my new blog at <a href="http://alexandruburlacu.github.io/">alexandruburlacu.github.io</a>. Eventually all my blogs will be published exclusively there.</p><ol><li>Oh, yeah, almost forgot, the answer: <strong>It will run until killed by the OS, because 1 is not 1.0 in Elixir, nor 0.0 is 0</strong>.</li></ol><h3>P.S.</h3><p>For your efforts, I’d like to reward you with the possibility to run all these examples in a sandbox (elixir &lt;filename.exs&gt;). Knock yourself out ;)</p><p><a href="https://replit.com/@AlexandruBurlac/ElixirPatternMatchingMagic">ElixirPatternMatchingMagic</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c5019ecf7f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Selection for Machine Learning (2/2)]]></title>
            <link>https://medium.com/@alexburlacu1996/feature-selection-for-machine-learning-2-2-1a5a5b822581?source=rss-dbb1c78b5aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a5a5b822581</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[feature-selection]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Alex Burlacu]]></dc:creator>
            <pubDate>Sun, 15 Sep 2019 11:06:46 GMT</pubDate>
            <atom:updated>2019-09-18T18:42:42.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-o_cOg6ABwHfq33-xSrxg.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/0vY082Un2pk">https://unsplash.com/photos/0vY082Un2pk</a></figcaption></figure><p>In this part, we’re gonna see how to use information-theoretic concepts like mutual information, to identify the most relevant features for a machine learning model. Also, the Boruta algorithm will de described and some heuristics on how to choose FS algorithms based on dataset size and sparseness will be given.</p><blockquote>The first part of this series can be accessed <a href="https://towardsdatascience.com/feature-selection-for-machine-learning-1-2-1597d9ccb54a">here</a>.</blockquote><h3>Boruta: when forests help you find the way</h3><p>Boruta is an algorithm, originally written for R, that uses random forests and so-called shadow features, which are permuted original features, to iteratively select and rank important features in a dataset. It’s quite a powerful algorithm capable of clearly deciding if a variable is significant or not and the level of statistical significance of these variables.</p><p>Another interesting thing about Boruta, from its original FAQ</p><blockquote>It is an all relevant feature selection method, while most other are minimal optimal; this means it tries to find all features carrying information usable for prediction, rather than finding a possibly compact subset of features on which some classifier has a minimal error.</blockquote><p>A great (I can’t do better + too much copy-pasting in the blog post is just not fair) explanation of how Boruta works, how to properly use it, and even why the name, can be found on its <a href="https://notabug.org/mbq/Boruta/wiki/FAQ">wiki/FAQ page here</a>. If you intend to use it, check the link.</p><p>The best thing is, it is also available in Python, <a href="https://github.com/scikit-learn-contrib/boruta_py">here</a>. Being part of scikit-learn-contrib group of packages, it’s interface is the all-to-familiar fit_transform/fit+transform methods. It is more flexible than the original implementation, with the possibility to use your estimator (as long as it has feature_importances_ attribute) and tune the threshold for comparison between shadow and real features. Here&#39;s a code example from the project:</p><pre>import pandas as pd<br>from sklearn.ensemble import RandomForestClassifier<br>from boruta import BorutaPy</pre><pre># load X and y<br># NOTE BorutaPy accepts numpy arrays only, hence the .values attribute<br>X = pd.read_csv(&#39;examples/test_X.csv&#39;, index_col=0).values<br>y = pd.read_csv(&#39;examples/test_y.csv&#39;, header=None, index_col=0).values<br>y = y.ravel()</pre><pre># define random forest classifier, with utilising all cores and<br># sampling in proportion to y labels<br>rf = RandomForestClassifier(n_jobs=-1, class_weight=&#39;balanced&#39;, max_depth=5)</pre><pre># define Boruta feature selection method<br>feat_selector = BorutaPy(rf, n_estimators=&#39;auto&#39;, verbose=2, random_state=1)</pre><pre># find all relevant features - 5 features should be selected<br>feat_selector.fit(X, y)</pre><pre># check selected features - first 5 features are selected<br>feat_selector.support_</pre><pre># check ranking of features<br>feat_selector.ranking_</pre><pre># call transform() on X to filter it down to selected features<br>X_filtered = feat_selector.transform(X)</pre><h3>Mutual Information: what is it?</h3><p>Mutual Information is a measure of how much the presence/absence of some variable will affect the correct classification of the target variable.</p><p>Given two discrete random variables <em>X</em> and <em>Y</em> with probability mass functions <em>p</em>( <em>x</em>), <em>p</em>( <em>y</em>) and joint probability mass function <em>p</em>( <em>x</em>, <em>y</em>) we have the following formula for correlation</p><p><em>Cov(X, Y) = E(XY) − E(X)E(Y) = ∑p(x, y)xy − ∑p(x)x ⋅ ∑p(y)y</em> <em>⇒ Cov(X, Y) = ∑[p(x, y)−p(x)p(y)]xy</em></p><p>and for mutual information</p><p><em>I(X, Y) = H(XY) — H(X)H(Y) = E(lnp(x, y)p(x)p(y))<br>⇒ I(X, Y) = ∑p(x, y)[lnp(x,y)−lnp(x)p(y)]</em></p><p>So, these two are not opposites in any way, just two different perspectives on some distributions.</p><p>Compared with correlation, MI is not concerned whenever the variables are linearly dependent or not, but on the other hand, it requires knowledge of the underlining distribution of the variables, which is not always possible, or very hard to approximate.</p><p>So, it’s a trade-off, in which people usually prefer correlation-based methods.</p><h3>MI algorithms for feature selection</h3><p>As per the previous section, computing mutual information between 2 variables might be hard, because knowledge about the underlying distributions is necessary. Usually, one uses approximation methods.<br>But now, for feature selection, one has to consider many combinations of features with the target variable, in fact, exponentially many combinations.</p><p>To make the problem more tractable, some assumptions are used. One of them, the fact that already selected features are independent of the features not selected but under consideration. This allows for a greedy selection process and a simplified formula to solve:</p><blockquote>argmax I(xi; y) — [αI(xi; xs)-βI(xi; xs|y)] where i not in S</blockquote><p>The left side of the formula searches for maximum relevancy and the right one for minimal redundancy. Different MI-based feature selection algorithms vary α and β parameters, thus changing some of the other assumptions of the algorithm. For example, the JMI, aka joint mutual information algorithm assigns the <em>1/#selected features-1 </em>to both α and β. And then we arrive at mRMR.</p><p>mRMR (minimal-redundancy-maximum-relevance) is a class of algorithms that try to identify features with most mutual information with the target variable, yet minimum overlap between them. It assigns <em>1/#selected features-1 </em>to α and 0 to β from the formula above. The <a href="http://home.penglab.com/papersall/docpdf/2005_TPAMI_FeaSel.pdf">original paper</a> described 2 methods, MID and MIQ, that is, minimum information distance and minimum information quotient, respectively.</p><p>A nice package with scikit-learn compatible interface can be found <a href="https://github.com/danielhomola/mifs">here</a>. Here’s a code sample from them:</p><pre>import pandas as pd<br>import mifs</pre><pre># load X and y<br>X = pd.read_csv(&#39;my_X_table.csv&#39;, index_col=0).values<br>y = pd.read_csv(&#39;my_y_vector.csv&#39;, index_col=0).values</pre><pre># define MI_FS feature selection method<br>feat_selector = mifs.MutualInformationFeatureSelector(method=&quot;MRMR&quot;)</pre><pre># find all relevant features<br>feat_selector.fit(X, y)</pre><pre># check selected features<br>feat_selector.support_</pre><pre># check ranking of features<br>feat_selector.ranking_</pre><pre># call transform() on X to filter it down to selected features<br>X_filtered = feat_selector.transform(X)</pre><p>For a more in depth view, with more theory, see <a href="https://thuijskens.github.io/2017/10/07/feature-selection/">this amazing blog post</a>. Also, just so you know, you could use sklearn’s mutual_info_classif or mutual_info_regression functions in combination with SelectKBest or SelectPercentile classes, but using MIFS package is faster and more flexible.</p><h3>Selecting feature selection methods</h3><p>Now that you know all these different feature selection methods, how do you pick one? The answer as usual in ML is — experiment, see for yourself.</p><p>Not very inspiring, isn’t it? That’s why here are some consideration for you, to at least minimize the search space.</p><ul><li>When having a small dataset (less than a couple of thousands) prefer model-based selection, for example using trees or forests. These are powerful methods that are compute expensive, so applying them for larger datasets will be prohibitive. Also, you could afford cross-validation in such a setting.</li><li>When having a very big and sparse dataset, opt for SGDClassifier-based model with L1 penalty.</li><li>For low sample size and big dimensionality datasets, the best option will be to use something like Lasso algorithm.</li><li>For quick EDA-like workflow on low dimensionality datasets (&lt;100 features), don’t forget to find the correlation coeficients between all features in your dataset.</li><li>MI-based feature selection is best when having big (that’s mandatory, to estimate the distribution) and dense (optional, works pretty good with sparse data too) datasets.</li><li>Statistical feature selection (chi2, correlation, et al) are best when running cheap and fast is important and the dataset is not too big (&lt;100k or so).</li></ul><h3>Epilogue</h3><p>Note that all feature selection, both in this blogpost and in the previous one are applicable on feature vectors. That means, no method from here could be applied for vision problems, for example, unless you want to have fewer “features” from the last layer of a CNN, which might be a good idea, idk.</p><p>This series is by no means a definitive guide, but rather a list of handy tools and how to use them. If interested in FS, you should google how to perform wrapper methods efficiently, using optimization techniques like genetic algorithms, simulated annealing, or other methods alike.</p><p>Also, remember this, there’s no free lunch — think which trade-offs are you ready to make, pick a couple of methods, experiment, choose the best one for your problem.</p><p>If you’re reading this, I’d like to thank you and hope all of the above written will be of great help for you, as it was for me. Let me know what are your thoughs about it in the comments section. Your feedback is valuable for me.</p><p>Given my history of publishing, the next post will be sometime in January 😃 I’ll try to do better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a5a5b822581" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>