<?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 Rakesh Sharma on Medium]]></title>
        <description><![CDATA[Stories by Rakesh Sharma on Medium]]></description>
        <link>https://medium.com/@rakeshsharma.pr?source=rss-d98864d89e4c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nppk6TT_LgNdfpQT2bUszw.png</url>
            <title>Stories by Rakesh Sharma on Medium</title>
            <link>https://medium.com/@rakeshsharma.pr?source=rss-d98864d89e4c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 17:03:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rakeshsharma.pr/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[The New Market Makers]]></title>
            <link>https://medium.com/@rakeshsharma.pr/the-new-market-makers-1ffbe69f1aff?source=rss-d98864d89e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ffbe69f1aff</guid>
            <category><![CDATA[hyperscaler]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[market-making]]></category>
            <category><![CDATA[neocloud]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rakesh Sharma]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 10:33:46 GMT</pubDate>
            <atom:updated>2026-11-07T10:43:52.170Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How is the AI market changing? Is a new playing field emerging? It looks like there is more to it than meets the eye. On one side, we are bombarded with news of massive job losses hit by the AI wave. On the other side, there is a ginormous bet on silicon chips, with many emerging players in this space. Let us unfold what the new playing field looks like.</em></p><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/0*mogptjyH_hEqqc2h" /></figure><p>Demand for compute is hitting the roof, and there is a paucity of data centers. The next foundation of human civilization will be built on AI. As electricity fueled the Industrial Revolution, AI will do the same for this stage of human civilization. The proof of this is that a phenomenal $360 billion was spent on AI compute across the world last year. According to BCG, AI-related transactions will hit $2.3 trillion by 2030. Moreover, the valuation of the household names in this space, such as Anthropic and OpenAI, has hit valuations of trillions that have baffled experts. No offense to the experts, the demand for compute is now like a giant supernova burst, and no fabric of human-industrial consortia can meet the demands, at least in the near future.</p><h3>Thus emerge new players — Who exactly?</h3><p>Neocloud companies like CoreWeave and Nebius are the new providers of compute in addition to the hyperscalers (public cloud). The demand for compute has multiple dimensions that are unclear on the surface for laymen to understand, and there are vagaries of supply and demand. This combination is now for marketization. Let us understand the various links in this chain. Firstly, there are chip manufacturers who convert the raw silicon into chips for computing instructions (NVIDIA, Intel, etc.). The next in the chain are the equipment manufacturers who rack up these chips in data centers (like Dell and HP). These racks now make the cloud centers with certain services, which are the hyperscalers, our ubiquitous public cloud like Amazon, Google, and Azure. There is room for many others who can enter the data center and computer markets.</p><h3>Economics and Marketization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*reSsJBHFuUG02OjR.jpg" /><figcaption>source: investopedia</figcaption></figure><p>Why this is ripe for marketization: there are several types of chips located in different locations. The demand peaks at varying times based on the geography and its compute demand. Such varying demand creates a lot of middlemen, and forecasting demand becomes a bottleneck for efficient economics. This is where compute derivatives come in, guaranteeing a contract for long-term demand. No one can forecast the current surge in demand, nor how AI services will serve the world. From large hyperscalers to small fries, there is a need to hedge. This is a brave new world and will call for new players who can act swiftly on this opportunity; startups are offering value propositions of new trading instruments on computers, and some others are opening up bourses and exchanges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ffbe69f1aff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning A new language — What works and what does not.]]></title>
            <link>https://medium.com/@rakeshsharma.pr/learning-a-new-language-what-works-and-what-does-not-422362a99662?source=rss-d98864d89e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/422362a99662</guid>
            <category><![CDATA[language-learning]]></category>
            <category><![CDATA[neuroplasticity]]></category>
            <category><![CDATA[french]]></category>
            <category><![CDATA[language]]></category>
            <dc:creator><![CDATA[Rakesh Sharma]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 11:39:30 GMT</pubDate>
            <atom:updated>2026-07-13T16:05:19.116Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I landed in Toronto this January, but was met with mixed news about the prospects for PR status. French language proficiency enhances my profile. After hearing my lawyer say, “You are never too late to learn anything; however, learning a new language is hard,” I decided to take the plunge anyway, and so far I am surprised by the progress I have made. In this blog, I will share my journey over the last six months, outlining the strategies I used and what worked best for me. Keep reading</em></p><h3>Why Invest in Learning a Language</h3><p>Languages have intrigued me more recently, particularly when I enrolled in an introductory course in Computational Linguistics. Although I did not pursue it further, the course left a lasting impression, and I have been searching for a new language to add to my repertoire. I learned English, Hindi, and Sanskrit at school. Malayalam was my mother tongue, and I could read and speak it well, but I struggled to write it, and I cannot write; there are no neural connections. I picked up Tamil by watching movies in college, and I can vouch that I only understand and can speak very little, so I was multilingual. English is my forte in expressing myself effectively; I do not have the same mastery over any other language. The more one uses the language, the better one gets, and there has to be a way to learn deliberately — this is what one refers to as active learning. According to neuroscientists, learning a new language creates new neural connections and improves cognition, a phenomenon called <strong><em>neuroplasticity</em></strong>. As one ages, there is a decrease in the change of change of neurons and neural pathways. Learning a new skill or language can increase neuroplasticity, and languages are a particularly effective way to combat aging, as many researchers have pointed out.</p><p>Truth be told, I did not start the quest to learn French out of love for the language or to experiment with my neuroplasticity. My motivation stemmed from the need to pass a language test to earn points for immigration. Below are my 2 cents on what really works in practical applications.</p><h3>Gamify using Duolingo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2Qaga-nTfOKmg0vU" /><figcaption>Source: IEE Spectrum</figcaption></figure><p>This is the first strategy I employed when I was scratching at my learning. If one is afraid of learning something new, a gamification strategy can be effective. Duolingo starts building language through what I call everyday learning. It is an all-play-and-no-work approach; there is no way to test your knowledge other than the numerous quizzes on the site. The danger here is that you learn for the test without immersion. You learn by example and repeating those examples. It is best suited for learners who lack motivation and require daily nudges. The community ranking, badges, and gamification will egg you to learn more. The cons of learning by this method are that it is the least structured. There is no emphasis on grammar, and you pick up grammar through usage, which is not ideal when trying to learn the core of the language. The learning process is also slow in this case; it was for me, too.</p><h3>Rocket French — Babbel (same ilk)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*jM6lmGF6quJmOjcq.jpg" /><figcaption>Source: The French Experiment</figcaption></figure><p>The next app I tried was Rocket French and Babbel. Both are of the same ilk; they create immersion for users at different levels and feature several levels and mock everyday scenarios as steps toward immersion. The learning appears more natural than Duolingo. There are examples of conversations that one can record and play out. The microphone capture appeared imperfect or a tad error-prone; the feature works most of the time. Both apps are good for simulating scenarios. Unlike Duolingo, there are fewer gamification-related distractions.</p><h3>Alliance Française — In-person and online tutoring</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/0*_UbDALqNjX3vLuRx" /><figcaption>Source: AF ottawa</figcaption></figure><p>Alliance Française is a premier global institute that works to disseminate the French language and culture worldwide. They provide many ab initio courses from A1 to C1 in a progressive manner. I took my first French lessons in a traditional manner, focusing on instruction delivered in classrooms using Alliance Française textbooks. The progress was very slow; however, group classes bring their separate challenges. Learning with a mix of different levels may make one feel left behind the others. It was for me; as the levels progressed, I was not learning at the same pace as others because the learning was not personalized. There is also less opportunity for personal attention, and learning is never real. If you prefer old-school, classroom-like instruction, this may be the one for you; however, do not expect rapid progress with this method.</p><h3>Finally, what worked for me</h3><p>What nailed it for me was a melange of techniques. I tried the Preply platform for personalized tutoring. Personalized tutoring can be expensive, but it works like a charm when the tutor tailors a course for you. I was lucky to find one who was also an examiner for TEF and TCF. That is not to say Preply works better than other platforms; the key here is finding a language guide who can personalize your learning. The outcome is rapid in this case because one is immersing oneself in learning primarily by listening to the tutor. If one looks back to infancy, we learn by imitating adults, especially with language, as it is the first thing we learn. As of today, I have spent close to 200 hours on language learning through individual sessions and have attained level B1 on my first TCF test across all levels. The learning process is not linear, and one goes through numerous ups and downs. Here are a few things I noted about language learning</p><ol><li>Learning a language is hard; it requires rewiring neural connections, especially if the language differs from your mother tongue. Mastery of grammatical structure can only take one so far; real learning requires reading, speaking, and writing simultaneously.</li><li>One cannot learn a language by reading a book or by listening to podcasts alone; these are not active learning methods. What I mean by &quot;active&quot; here is that there is no way to immerse oneself in learning through these methods.</li><li>Immerse oneself in the language — watch movies, ads, and billboards in it. I even tried reading product descriptions for various groceries in Walmart to get a sense of the difference between Anglaise and Francaise.</li><li>Start speaking early. I used my one-on-one sessions with the tutor each day to speak on topics I was familiar with. Later on, I moved from description to reflection while speaking, a natural progression in language learning.</li><li>Take effective breaks in between the learning sessions. I noticed this aspect too many times throughout my learning. The brain rewires effectively when one pauses in between, allowing it to heal and make those connections. This is an effective form of rewiring; rewiring happens when you are engaged in alternate thinking or learning.</li><li>Language learning is non-linear; there are periods of steady progress; however, one would see a southward shift in progress between periods when new levels of grammar, etc., are introduced. So stick with the process and give it time.</li><li>Tests like TCF and TEF are not clear indicators of language proficiency; these tests are meant for candidate filtering and would require practice and rigor to attain scores at acceptable language levels.</li><li>One may arrive at B1 quickly, but attaining B2 to C1 requires further mastery of the language&#39;s nuances. Progress from upper B1 to upper B2 may take more time than expected.</li><li>Don’t fall for a crash course in language; there is no way to rewire a brain in a short time. One will be left frustrated.</li><li>Have fun with it, enjoy the process!</li></ol><h3>Conclusion</h3><p>I have been learning French for almost a year now and have achieved an upper B2 level, according to my tutor. Reading and speaking remain my strengths, and I still struggle most with writing. Listening has vastly improved; the process taught me to listen with intent. However, to clear language tests like TCF or TEF, all these skills must come together, which poses a challenge for many. I have completed more than 200 hours of personalized training to reach this upper B1-B2 stage; this is from absolute 0 to 1. Now comes the mastery of nuances and prepping for the tests. Will keep you posted on how it goes.</p><p>I sincerely hope my learning experience inspires others to try something new; you are never too old to learn. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=422362a99662" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MS Fabric — why it may not be an ideal platform for Data Science]]></title>
            <link>https://medium.com/@rakeshsharma.pr/ms-fabric-why-it-may-not-be-an-ideal-platform-for-data-science-e205c94f533b?source=rss-d98864d89e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e205c94f533b</guid>
            <category><![CDATA[msfabric]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[microsoft-azure]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Rakesh Sharma]]></dc:creator>
            <pubDate>Tue, 23 Sep 2025 23:23:57 GMT</pubDate>
            <atom:updated>2025-09-30T13:53:08.110Z</atom:updated>
            <content:encoded><![CDATA[<h3>MS Fabric — why it is not an ideal platform for Data Science in 2025</h3><p><em>In this post, I am sharing the intricacies of vendor lock-in and why MS Fabric, at its current state, may not be ideal for Data Science workflows. Fabric has been built with purpose, and there is an idea of everything being connected with the customer in mind. We will take a look at the Pros and Cons of Fabric and what audience for Fabric should be, and where Fabric fits in the organization’s tech stack.</em></p><h3>Why Fabric</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nwIvBWI3wubnxkDo.jpg" /><figcaption>Source: Pixabay</figcaption></figure><p>MS Fabric is the new kid on the block from Microsoft, and it has been released with a purpose in mind- as Satya Nadella has always espoused — to empathize with customers and build product and features that makes life easy for customers. Ahem, they have got that right! The Fabric offering is sold as a Power BI license, allowing one to quickly build a dashboard that now has the backend compute power to orchestrate any data engineering pipelines towards the end goal of displaying the results in the Dashboard. It is a one-stop shop for all data engineering workloads, such as Business Intelligence pipelines, Data Science and Machine Learning workloads, and traditional SQL analytics for ad-hoc reports. Organizations that are already on the Microsoft stack will find it easy to extend their footprint, and that is the selling point of Fabric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tsPw9eCxBC1UHf-YPY_AOg.png" /><figcaption>Source: Oreilly, Fundamentals of Microsoft Fabric</figcaption></figure><h3>The return of the “E<em>xperience”</em></h3><p>Fabric has all the components in a unified experience, such as data engineering workflows, warehouse, lakehouse, Jupyter Notebooks, Synapse AI, Power BI visualizations, CI-CD, DevOps, Git, etc, and each of these is called an experience. Why this clicks with users, for one, is that it addresses the diverse skill sets needed to run a data-driven organization, from business analyst to software engineer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*OE4tRwxuxi1Xl8TJ" /><figcaption>Source: iStock</figcaption></figure><p>A business analyst could prepare reports from their preferred data mart, and at the same time, a data scientist can run experiments reading from the lakehouse. The components in Fabric are arranged in this way, allowing it to be managed like an organization but avoiding data silos. The basic unit of arrangement is called a <em>workspace. </em>Workspaces are grouped into <em>domains </em>and are classified at the business unit level.</p><h3>One Lake and Data Factory</h3><p>Data in fabric resides at a unified storage layer called One Lake, which is also referred to as One Lake Drive. It is stored in a Delta Lake Parquet format, making it ACID-compliant and well-suited for both structured and unstructured data. The Delta Lake format allows for schema evolution, ensures time continuity, and efficient data management with no data loss even during failures. All fabric engines, such as Spark and Power BI, as well as real-time streaming components, can read the Delta format.</p><p>Data Factory is an evolution of Azure Data Factory, allowing for useful data transformation and ETL integrations of cloud-scale data. It is the essence of MS Fabric and connects to more than 170 data sources using the default connectors it provides. It allows ETL, ELT, robust transformations, and orchestration capabilities. It has a slick, low-code or no-code interface, allowing non-technical resources to get started with robust data transformations. Co-pilot integration is another feature with Data Factory, where one can use the agentic AI capabilities to copy, move, or replicate data from different sources to their targets. The figure below captures the extent of Data Factory in the fabric environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xrbi2PtAHzGZfclalDkW9A.png" /><figcaption>Source: microsoft</figcaption></figure><h3>Fabric Pricing Model — the catch</h3><p>This is where one needs to exercise caution, as it departs from the regular pay-per-use model. Fabric is a SaaS cloud product that is sold as a single product with Power BI licensing. Although there are various services, the cost of deploying and utilizing them is based on three key elements: storage, compute, and user licenses. Compute is measured in <em>capacities, </em>and there are two variants: Fabric compute, which is pay-as-you-go, and large, discounted, committed capacities, which are fixed even if not used and are discounted for higher capacities. The last cost is that of a Power BI user license, which is relevant if users are using this interface. This is not by accident; Microsoft has been savvy enough to know that Power BI users could be the end customers when organizations turn data savvy. For capacities under F64, each user may need a Power BI Pro licence, which could increase the cost. Even though there are varied services and layers to the costing, the fabric comes with a single bill. Here are some high-level pointers on understanding the pricing</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JCH3X3aAyz8tV8vh.png" /><figcaption>Source: Erwin &amp; Data Analytics</figcaption></figure><h4>1. Capacity-based pricing</h4><p>Fabric (like Power BI Premium) charges based on <strong>compute capacity (F SKUs)</strong> rather than a pure pay-per-use model.</p><ul><li>You pay for a fixed capacity tier (F2, F4, F8, etc) upto F2048, and progressively costlier</li><li>Even if your workloads don’t fully utilize that capacity, you still pay the same; this is called tier-based pricing. During the development phase, developers will be jostling for compute as we scale the team and are forced to upgrade the tier.</li><li>For steady, enterprise-scale workloads, this is predictable; however, for smaller or spiky workloads, it can be expensive and may catch one by surprise. This is where the development of ETL workloads and random experimentations reach their limits in terms of cost and can be prohibitive.</li></ul><h4>2. Storage + compute separation (but not entirely)</h4><p>Microsoft says Fabric unifies compute/storage (OneLake + engines), but in reality:</p><ul><li>Storage costs are additional (based on OneLake/Azure Data Lake) and are not entirely free; comparatively, your prize is negligible.</li><li>Compute costs depend on the reserved capacity.<br>So you don’t quite get the full cloud-native “pay only for what you use” like Snowflake or BigQuery.</li></ul><h4>3. Overlap with Power BI</h4><p>This is where pricing logic takes a beat. When one signs up for Fabric, we are introduced as a Power BI user. This license includes compute and data integrations, and eventually, there will be a need to scale up. If you’re already paying for <strong>Power BI Premium</strong>, some Fabric features overlap — but you often need to scale up to higher tiers (F64 or more) to get both BI + heavy ML/ETL workloads. This can lead to a feeling of “double paying.” <strong>Power BI</strong> Compute is yet another anomaly in pricing, as the user base expands within the organization. If one needs customized dashboards, Power BI could prove to be a bottleneck.</p><p>What we gauge from our usage so far is that Fabric cost is measured in Capacity Units (CUs) and is a logical cloud compute unit construct of Microsoft, which cannot be translated to CPUs or storage memory. It is challenging to predict upfront what our usage will be. And here is the catch with Fabric: it is intended to unify data and compute in one space, known as the <em>Workspace. </em>It is challenging to separate and pinpoint activities using Lakehouse, Warehouse, or Spark Notebooks, which drives up the cost. For us, our spikes in Notebook compute were sustained during the development phase. Starting on a low tier is not sustainable as the team expands; one keeps being promoted to a higher tier. Post-deployment, the spikes in compute were muted, but as the user base expanded, the Power BI license costs began to impact us.</p><h3>Through Bursting and Smoothing</h3><p>CUs have two unique features, and they use this concept to free up idle resources and allocate them to bottlenecked workloads. They are called <em>bursting</em> and <em>smoothing</em>. <em>Bursting</em> refers to the sudden surge in computational capacity based on demand, allowing tasks to finish in less time. Fabric does not throttle at the limit of the tier but instead provides a credit, which will later be recaptured, released, and charged in our final bill. This prioritises performance over the computational limits based on the tier. There is no need to schedule the pipelines during periods of low computational load carefully. Bursting allows a smaller capacity to accommodate irregular spikes without throttling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VxoWsfpzzFn4KAjQnzCJFg.png" /><figcaption>Source: Oreilly, Fundamentals of MS Fabric</figcaption></figure><p>The smoothing feature enables the recovery from computational surges by averaging the CUs over longer timepoints. A timepoint in Fabric is defined as 30 seconds. By using smoothing, the bursting is averaged out in the subsequent timepoints; there are 2880 timepoints in the next 24 hours. In this strategy, interactive surges are smoothed over the next 5 minutes up to 64 minutes, and background operations are smoothed over 24 hours. There are caveats to this; bursting is not guaranteed. If our compute is running in a region where compute is starved, bursting will not be allowed. If we are not using our computer to its full capacity, then smoothing will recover our burst. However, if we consistently use our capacity for extended time periods, then we might be throttled at our capacity. Either way, bursting at capacity is not guaranteed. We encountered issues in certain edge cases where notebooks running long-duration, heavy computations prevented other notebooks from being spun up, as they had been throttled.</p><h3>What is it meant for and not?</h3><p>The core purpose of this offering is to eliminate the hurdles of stitching together various data silos and to ease the process of getting started. It is ideal for organizations that are already invested in Microsoft solutions. Switching costs to any other cloud provider would be a driver for moving to Fabric, making it an ideal choice for them. It would also be ideal for teams seeking significant collaboration with Data analysts, data scientists, and Business Power BI users, as data resides in a familiar environment created for a specific domain, known as a <em>workspace. </em>Traditional data science and ML teams would likely find Fabric to be very restrictive and opinionated. The computational spike for running random experiments and searching in a large space for parameter fine-tuning could be a bottleneck in fabric getting charged for bursts or spikes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xZIcc_3CnKtgD7Y9.png" /><figcaption>Source: the odd dataguy</figcaption></figure><p>Here are my takes on why it doesn’t fit for Data Science workloads</p><h4>1. Fabric is BI-first, not DS-first</h4><ul><li>Fabric grew out of <strong>Power BI + Synapse</strong> DNA. Its strongest features are data integration, reporting, and dashboards. The offering of MS Fabric as a Power BI license is a great giveaway; anyone would agree.</li><li><strong>Data science workflows (experiments, notebooks, ML pipelines)</strong> were additions as an afterthought.</li><li>Most DS teams find themselves fighting the “BI-first” assumptions (governance, data models, reporting optimization). The workspace is governed by access control for users in Power BI, which is similar to data warehouse governance. There is less stress on experimentation and model iteration and such toolings.</li></ul><h4>2. Limited ML/AI tooling inside Fabric</h4><ul><li>Fabric does include <strong>Notebooks</strong> (Spark-based) and some integration with <strong>Azure ML, </strong>MLflow is not natively integrated. We cannot spin up the MLflow server and monitor training.</li><li>No strong hyperparameter tuning / model registry / deployment orchestration or any such frameworks are included in fabric environment.</li><li>You often bounce between Fabric and Azure ML (extra cost + context switching).</li><li>Compare that to OSS stacks (Spark + MLflow + Prefect) or Databricks, where DS/ML is the first-class offering.</li></ul><h4>3. Pricing + capacity model is unfriendly for experimentation</h4><ul><li>ML workloads are <strong>bursty; </strong>it cannot be predetermined when to scale down or scale up. So committed capacities will be the best bet for computing. Due to the smoothing and bursting, the spikes will eventually be charged in the bill cycle.</li><li>Data Science workloads will necessitate the upgrade of Fabric tiers and <strong>reserved compute capacity (F SKUs)</strong>, resulting in idle time and wasted money.</li></ul><h4>4. Ecosystem lock-in</h4><ul><li>Fabric is tied to <strong>OneLake</strong> and Microsoft services.</li><li>OSS DS stacks thrive on <em>pluggability</em> (DuckDB, Iceberg, Feast, etc.). Fabric forces conformity. There are a multitude of tools available to get started and experiment, but Fabric feels like a constrained environment.</li></ul><h4>5. Collaboration gaps</h4><ul><li>Fabric is ideal for <strong>business analysts and data engineers</strong> who are relatively new to software engineering principles. Machine learning demands more advanced tooling and skills.</li><li>Data scientists need <strong>versioning, CI/CD, experiment tracking, and GitOps integration. </strong>These are possible in Fabric, but not first-class. You often end up stitching Azure DevOps/GitHub manually.</li></ul><h3>Final Takeaways</h3><p>Fabric will continue to grow into a Microsoft flagship and will be a great product for enterprises that are on the Microsoft stack. The offering has significant gaps that need to be addressed for a comprehensive ML and DS adoption. The compute units, or CUs, are a myth in themselves, and from a FinOps perspective, they lack transparency, resembling a fixed-cost model with the capability of cloud-level compute. However, when compared with AWS and GCP&#39;s offerings, there is a lot that consumers are left gasping at in the end. With stellar alternatives for an open source-based DS/ML stack, the path for ML and Data Scientists is apparent — Fabric may not be the first choice for their workloads.</p><p><em>In the next post, I will share the details of an alternate stack that replaced MS Fabric workloads for our client, so keep reading…</em></p><h3>References</h3><ol><li><a href="https://learn.microsoft.com/en-us/fabric/data-factory/data-factory-overview">https://learn.microsoft.com/en-us/fabric/data-factory/data-factory-overview</a></li><li><a href="https://learn.microsoft.com/en-us/fabric/enterprise/throttling">https://learn.microsoft.com/en-us/fabric/enterprise/throttling</a></li><li>Nikola Ilic, Ben Weissman. 2025. O&#39;Reilly Publishing, Fundamentals of MS Fabric</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e205c94f533b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Strategic Questions to Ask VCs Before Fundraising in 2025]]></title>
            <link>https://medium.com/@rakeshsharma.pr/5-strategic-questions-to-ask-vcs-before-fundraising-in-2025-e3fee31a6114?source=rss-d98864d89e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3fee31a6114</guid>
            <category><![CDATA[founders]]></category>
            <category><![CDATA[vc]]></category>
            <category><![CDATA[venture-capital]]></category>
            <category><![CDATA[startup-lessons]]></category>
            <category><![CDATA[fundraising]]></category>
            <dc:creator><![CDATA[Rakesh Sharma]]></dc:creator>
            <pubDate>Sun, 11 May 2025 15:25:44 GMT</pubDate>
            <atom:updated>2025-05-11T15:25:44.811Z</atom:updated>
            <content:encoded><![CDATA[<p><em>There is an excellent excerpt by Venture Deals on how to fundraise. Startups are constantly fundraising and making enough runway to achieve their milestones. At the same time, they are also building the product. The two activities feed each other. Fundraising is hard, no doubt, and you are more likely to come across “No” as an answer, but the process also gives new perspectives to founders and takes one an inch closer to the VC that one would like to be associated with. In this post, I aim to share essential questions for founders to consider before embarking on a blind date with an investor.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9Os9CPlcV_psbSRi" /><figcaption>Photo by <a href="https://unsplash.com/@anetakpawlik?utm_source=medium&amp;utm_medium=referral">Aneta Pawlik</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>I have had the fortune to work with 2 VC firms in the last 2 years and have vetted more than 50+ deals ranging from consumer to Deep-tech ideas. There are 2 primary activities in the VC firm —<strong><em> fundraising and Deal flow</em></strong>. The heart of the VC business is in the relationship management between the VC firm and the founders and limited partners who park their money for investing with us. Having witnessed operations from both sides of the Venture Capitalist, I can say that there is not much clarity on how things get done; what works for some does not work for others, and it varies. I always get questions on how to fundraise for startups or business ideas, and it is not a question of timing; I have chosen to discuss this in this blog post.</p><h3>Why fundraise and when to start</h3><p>What I like about startups is their ability to start with problem-solving, which allows their product to continue developing; they are lean, mean, and in the loop of experimentation. It takes a while for them to find their product-market fit. However, the need for scaling becomes imminent once they identify the fit or critical gap in the problem space they are addressing. It may now require a larger cheque size to implement their plan fully in the market. At this stage, funding constraints should not limit their ability to reach, productize, and expand. There are no points for being late in the race, and proverbial as it may sound, the winner takes it all here. So, if you start fundraising at this critical stage, you may be hard-pressed for time and maybe frustrated due to the delays.</p><h3>How not to sabotage your fundraising activity</h3><p>Be early and have skin in the game. I like this phrase: startup founders should know their investors, their portfolio, and the expertise they bring to the meeting beforehand. Have a clear understanding of why you are holding this meeting, and be prepared to walk away if necessary. Not having clinched a cheque in the meeting is a gain, I would use to learn more about my approach and the investor I want to focus on.</p><p>Fundraising is a negotiation, and sticking with one investor or the other has a long-term impact on the startup, so be prepared to walk away if the meeting outcome is not what you had hoped for. Always keep your walkways at the top of your mind lest you enter a marriage you do not want to keep for long. Investor relations can bring synergies that help run a startup, such as hiring talent, testing loops, and GTM partnerships. It is not just the cash that adds value. Founders need to think long term here.</p><p>Here are my top 5 questions that I believe startup founders should ask to get started on fundraising</p><h4>1. What are the portfolio companies you have invested in?</h4><p>This is a great question to ask upfront to gauge investors&#39; track records. In another sense, the portfolio reflects the fund&#39;s strategy. Initial meetings are brief, so it&#39;s best to conduct thorough research to understand the portfolio comprehensively. However, if an opportunity arises, be confident in asking to learn more. Portfolio companies and their founders&#39; backgrounds can give interesting insights for fundraising.</p><h4>2. What value do you bring on top of the check?</h4><p>This is my favorite question, and I have rarely seen founders ask this question. It shows that money is not the only important criterion for having a fund in the cap table. Long-term thinking founders would weigh in on the other value-added benefits they can bring. Their existing venture capital (VC) network and founder network could be an excellent pool for hiring top talent and gaining strategic expertise. Getting from 0 to 1 is a haul, and it needs support from different stakeholders; cash alone does not solve this problem.</p><h4>3. How does my startup fit into your investment thesis?</h4><p>The founder should research the firm&#39;s thesis, but their explanation to this question would reveal their thinking. This is particularly true for late-stage investors; nevertheless, it is a valuable question to learn more about the partners and their current stage in the fund cycle. Ensure you understand the cheque size and the stage at which they follow up with investments.</p><h4>4. What are the risks you see in our business, and who are our competitors?</h4><p>This question surpasses all others in that it requires partners to understand the problem space founders are in deeply. This is a true test of an investing VC firm, where they will come up with strategic suggestions. VCs with a pedigree will be quick to answer these questions and also show their interest in your firm and how it fits in their portfolio. VCs I have worked with will be forthcoming with risk assessments and might challenge you on the potential of your startup idea. There might be a competitor they have already vetted in the past, and could point to gaps in understanding of the problem space or value capture to pivot.</p><h4>5. What are our barriers to success in your opinion?</h4><p>One thing that VC investors wish for is to invest in firms that are set for success. Many VCs preclude investments if there is no lead investor—seemingly, the barrier is financial and funding. However, there are many barriers that VCs might see, such as market access, network effects, founder background fit, problem market fit, etc. Be inquisitive to know what they think of this space, and have an open conversation to see the odds of success in their opinion.</p><h3><strong>Conclusion</strong></h3><p>Fundraisers will encounter rejections. One may run through a few VC firms before finding the right match. These meetings share valuable perspectives on your next steps as a founding firm. Ideally, founders should iterate on their idea after each meeting and see this as an opportunity. Happy Fundraising !!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3fee31a6114" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are derivatives — Understanding derivatives for Non-Financial Engineers]]></title>
            <link>https://medium.com/@rakeshsharma.pr/what-are-derivatives-understanding-derivatives-for-non-financial-engineers-fa80e94b4c4a?source=rss-d98864d89e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa80e94b4c4a</guid>
            <category><![CDATA[derivatives-pricing]]></category>
            <category><![CDATA[options]]></category>
            <category><![CDATA[derivatives]]></category>
            <category><![CDATA[financial-engineering]]></category>
            <dc:creator><![CDATA[Rakesh Sharma]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 22:43:43 GMT</pubDate>
            <atom:updated>2025-01-16T22:43:43.341Z</atom:updated>
            <content:encoded><![CDATA[<h3>What are derivatives — Understanding derivatives for Non-Financial Engineers</h3><p><em>Derivatives is a term very loosely used in the industry, more so with derivative options. We have financial options and also real options; the whole world like to have some options with them. However, the derivative as an instrument is very old and has been in use in ancient history. Its evolution shows how innovatively it has been used for speculation, hedging, and arbitration strategies by businesses. In this blog, I will take a deep dive into various options and strategies traders use with these options.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kP8-3S6sOueBaAGe" /><figcaption>Photo by <a href="https://unsplash.com/@austindistel?utm_source=medium&amp;utm_medium=referral">Austin Distel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Motivation</h3><p>I came across the term not so long ago when I was doing my master&#39;s in financial engineering. Financial markets and various instruments are very intriguing, and derivatives are seen as an innovation for the financial market. The credit for inventing modern-day financial derivatives is given to Eddie Connor, a trader in the commodity soybean. However, there are various references to derivative as a concept since the time humans started cropping. Rains and floods used to affect the crop yield, and procurers of the yield were to be asked to waive the debt of the farmers by a diktat of the king of Mesopotamia. In the financial world, Derivative means financial instruments that derive their value from other traded assets. These traded assets can be stocks, commodities, etc. Derivatives are extended to many other items outside finance. For example, there are weather derivatives, credit, and interest rates-based derivatives, to name a few</p><h3>Why the notoriety around this term?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HRiHbhp7CSopRaHR" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Derivatives became a mainstream trading instrument in the 20th century when futures and options on equities were introduced in 1919 by the Chicago Mercantile Exchange. However, during the subprime crisis of 2007, Derivatives made from the portfolio of risky mortgages were seen as the reason for the worst recession since the great depression. Many mortgages were not qualified for lending and were subprime and not prime lending. As a result, derivative instruments on these assets, such as CDS and MBS, were turned worthless overnight, leading to a crisis when homeowners defaulted. Large financial institutions and investors who were holders of these instruments lost vast sums of money. As an outcome of this crisis, derivative markets are now more regulated, and banks have stricter frameworks of risk management in place to account for such large crises.</p><p>Having this understanding, let&#39;s now deep dive into different derivative instruments and understand how a market for such an instrument comes into being. Any trade happens when there is demand and supply, which means there are some advantages to this trade than using the assets directly.</p><h3>Popular Derivative instruments</h3><p><strong>Forward Contracts</strong> — It is an agreement to buy or sell an asset at an agreed price in the future. The transaction happens at a definite time in the future, hence the name future contract. A transaction that can occur currently in a market is called <em>spot contract</em>. The transaction is conducted in the OTC (over-the-counter market); this marks the difference between futures and forward contracts. So, OTC is the market maker here as the buyer and seller must come together for this transaction to happen.</p><p>Parties enter into forward contracts to hedge against future fluctuations of prices and assets. For example, client A based in US has a payment GBP 1 million at a future date, which is 6 months from now. A can enter into a forward contract to buy GBP 1 million from a seller, let us say B (this could be a financial institution), at the current spot rate as he/she anticipates an increase in the exchange rate. In this case, A is at an advantage if the future spot price exceeds the current spot price, which is a possible payoff. On the other hand, if the spot price at the future date is lower than the current one, seller B is in an advantageous position and makes a possible payoff. There are no costs of entering into a forward contract, and transactions are realized later.</p><p><strong>Futures Contracts</strong> — It is similar to the forward contract, instead of the OTC this transaction materializes in an exchange. The two parties of the transaction also do not know each other, and the exchange standardizes the contract with essential conditions on the contract. The exchange lists the prices of the futures contracts. The largest exchanges where they are traded are CBOT and CME. The mechanism of trading is similar to what we have seen in the case of forward contracts. A trader can enter into a future contract for hedging or for speculation to make a payoff.</p><p><strong>Options</strong> — These come with optionality, one of the vaguely used terms in the field of strategy and finance. They are similar instruments as above but do not have the obligation to buy or sell the contract. Options are entered by buyers for hedging purposes and give users the right to buy or sell the asset at a determined price. The reason why this is attractive is because the cost of the options is way lower than the cost of losing on any of the positions with the asset in the futures and forward contracts market. A user will have to buy the option to enter into an options contract, but in the case of forward and futures, they do not cost anything at the time of entering into a contract. Buyer of an option will have to pay a price called <strong><em>premium</em></strong> of the contract. Unlike the above 2 types of derivatives options are traded in exchanges and OTC markets. There are 2 types of options —</p><p><strong>Call Option</strong> — In a call option, the buyer of the option has the right but not the obligation to buy an asset at a pre-determined price, which they enter into at the time of the contract.</p><p><strong>Put Option</strong> — In a put option, the buyer of the option has the right but not the obligation to sell an asset at a pre-determined price.</p><p>Buyers of the options are in the long position, and sellers are in the short position. The sellers will create the contract and is called as writing of the options.</p><h3>Let us understand each of these positions in this contract</h3><p>Imagine I have bought an option contract, then I am entering a position of financial trading strategy by which I may benefit at a time in the future. Let us try this with Call options first</p><p><strong>Call Option Scenarios</strong></p><p><strong>Call Option Buyer</strong> — I buy a call option at a premium of say $5 and have the right to buy a MSFT stock at a strike price K of $200, 6 months from now. I believe that the price of the stock will go up and would like to hedge that risk by entering into an options contract as I mentioned before. I am into a long position as I have the right to buy from the seller. A seller, which could be a trader or financial institution, is in a short position. Let us understand the costs incurred by the buyer in this case.</p><p>The buyer initially does not own any stocks of MSFT. His cost of buying option is $5 currently. At the future date the stock of MSFT is at $300. The buyer can buy the same stock for $200 from the seller of options contract. Imagine the buyer is a speculator and wants to make a payoff on the trade he has entered into; he can buy the MSFT stock for $200, sell it for $300, and make a payoff of $100. The total profit will be after the premium deduction is $95.</p><p>The diagram below shows how the payoff is calculated with various stages of MSFT stock price over the timeline, which is the x-axis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ze9-LgHLFq1YItANdwQBxA.png" /><figcaption>Source: Remarkable notes by Author</figcaption></figure><p><strong>Call Option Seller</strong> — Let us take a look at this from the perspective of Call Option seller. An option seller may or may not own MSFT stocks at the time of entering into an options contract. The seller pockets the premium of $5 at the time of selling the contract. At the future date of the contract the seller has to sell the MSFT stock at $200 whereas the market rate is $300 and makes a payoff of -$100 or a profit of -$95 which is (-$100 + $5 premium pocketed). We can describe the payoff and profit equation as the formula below.</p><p>The below image shows the premium pocketed by the buyer and how payoffs changes with increase in stock price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3EDDrgtDLR5kL-UGxTkEyg.png" /><figcaption>Source: Remarkable notes by Author</figcaption></figure><p><strong>Alternate Scenario of Downside Risk</strong></p><p>Let us now relook at the scenario where the MSFT stock is on a downward trend. In the case of the call option buyer, I do not have the opportunity to make a payoff as there is no upside on the stock; the MSFT stock price is USD 200 at the future date. My payoff is $0, and I make a net profit of -$5. Supposedly, if I held a contract of MSFT stock directly, I would have incurred a bigger loss of the entire stock price, say $200. With the call option, I have minimized my losses to the contract premium. In this case, the call option seller will keep the pocketed premium and make a positive net profit.</p><p><strong>Put Option Scenarios</strong></p><p>A user who has entered into a put option contract has the right, not the obligation, to sell an asset at a strike price at a pre-determined date in the future. Like call option a put option can be used for hedging, speculation or statistical arbitrage. Let us analyze the strategic options with a put option contract.</p><p><strong>Put Option Buyer</strong> — Imagine I have bought a put options contract at a premium of $5. I incur a cost of $5 to enter into a contract presently. I am a hedger, and I see that due to certain external factors, the price of the asset, which is MSFT in this case, may go down. The price of a stock of MSFT is $200 and I own a single stock at this price currently. At a future date, the price of the stock has gone down as anticipated, and I exercise my right to sell the MSFT stock at $200, which is the strike price of the contract. The market price of MSFT is $100 at the future date, and I make a payoff of $100 ($200 — $100). The net profit is $95, which is obtained by deducting the premium ($100 — $5).</p><p><strong>Put Option Seller</strong> — The seller immediately pockets the premium of $5 on selling the put options contract. At the future date when the buyer exercises the contract the seller has to buy the MSFT stock at $200 and can immediately sell it at the market price for $100, as the prices are racing to rock bottom. The payoff for the seller is -$100 (-$200 + -$100) and net profit in this case -$95 (-$100 + $5).</p><p><strong>Alternate Scenario of Upside Risk</strong></p><p>In the wake of MSFT stock price increasing the put option buyer loses the opportunity to make any pay off. As market price is higher than the strike price. If he/she exercises the option, he will be making a loss of K — St. The seller on the other hand pockets the premium and do not have the risk of buying the stock at the strike price at the future date.</p><p>It is interesting to notice here that on a bull run, there are two ways of making a payoff. The call option buyer will make a payoff by exercising the option, and the seller will make a payoff by selling the put options. The upside is higher for the buyer.</p><h3><strong>Understanding Moneyness</strong></h3><p>I would like to conclude this post by talking about the concept of moneyness. With derivative options one needs to understand how value of the options is derived. The premium of the option is derived based on the intrinsic value of the option contract. The intrinsic value of the option is based on the future value of the payoff and its time value of money. Moneyness is the relative position of the strike price of the option contract with respect to underlying price of the asset. There are three stages of Moneyness</p><p><strong>At the money </strong>— If the strike price of the option contract and stock price is same at the time of the exercise of the option, it is said to be in at the money.</p><p><strong>Out of the Money</strong> — In the case of a call option, if the strike price is above the underlying stock price, the option buyer will not make any pay off and the option is deemed to be out of Money. In the case of put option if the stock price is above the strike, then it is said to be out of money. In both cases, there is no opportunity for a payoff.</p><p><strong>In the money</strong> — This is a scenario in which there is a payoff if the price of the asset in the contract is greater than the strike price in the case of the call option and if the asset price is lower than the strike price in the case of an option, the options are said to be in the money.</p><h3>Conclusion</h3><p>In this post, I have briefly introduced the derivative instrument called option and why it is attractive for investors, hedgers, and speculators. Option contracts underwrite away the inherent risk of holding that asset. The images shared above show the moneyness for Call Option buyers and sellers and how stock price dynamics affect the option buyer and seller. I hope you liked the post. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa80e94b4c4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI strategy for Enterprises in the era of Gen-AI]]></title>
            <link>https://medium.com/@rakeshsharma.pr/ai-strategy-for-enterprises-in-the-era-of-gen-ai-976b41a44ef8?source=rss-d98864d89e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/976b41a44ef8</guid>
            <category><![CDATA[ai-strategy]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[gen-ai-for-business]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[business-strategy]]></category>
            <dc:creator><![CDATA[Rakesh Sharma]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 07:19:16 GMT</pubDate>
            <atom:updated>2024-10-25T06:18:08.042Z</atom:updated>
            <content:encoded><![CDATA[<p><em>MIT course on AI strategy needs a revamp as it misses the critical component of GenAI.</em> <em>This is not a blog on understanding the pros-cons of the course but more of a takeaway blog for a modern data strategist and where GenAI comes into the picture. The course conspicuously excludes gen-ai in its syllabus and stops short at NLP and NLU use cases. However, GenAI is the transformation that is driving the industry both in research and adoption by the industry due to its low-hanging fruits and gamut of text data. </em><strong><em>A McKinsey study says that GenAI can add to the economy between $2.6 trillion and $4.4 trillion annually and will increase the impact of AI by 15 to 40 percent (Venkat Alturi, 1).</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l-qFj2KuQQovimA9.jpg" /><figcaption>Source:mackrell.net</figcaption></figure><h3>Introduction</h3><p>I recently completed the “<strong><em>MIT course on AI for Business Strategy</em></strong>”. The course, talks little with respect to the usages of AI, is still power-packed, touching on some of the fundamentals that a modern data strategist should glean. Data is everywhere, but to what extent of that is usable remains a question mark in most of the organization. My data journey started when I built map-reduce workflows for an IT service firm in 2014. Since then, the ecosystem of Data and AI has grown exponentially. The course also does not touch on the current sensation of GenAI and LLMs and stops at the capabilities of NLP and NLU. This post tries to bridge the gap between what I learned in the course where the technology landscape is headed and how GenAI leads from where Traditional ML took us.</p><h3><strong>Machine Learning — Departure from traditional software</strong></h3><p>I would like to define Machine Learning as a software paradigm where Machines learn to generalize from data. In traditional software engineering, there are rules, such as the software or code taking input and generating an output based on a fixed rule. This was software paradigm 1.0. Machine learning is an inversion of the above process, where there is a lot of data that is representative of a scenario or business case; machines then learn rules from this data using an algorithm that can be used for further identification or pattern recognition of such data. The above is one of the finest definitions I have come across, as data now drives every product on earth, thanks to the lectures by the <a href="https://fullstackdeeplearning.com/">FSDL</a>. This is the new paradigm, which we call Software 2.0.</p><h3>Broad 2 Categories — Classification and Prediction</h3><p>Machine learning can be divided into 2 categories broadly— prediction and classification. Unsupervised ML models like segmentation can form a third category. However, they still output a definite value for their class (hard classification) or a probability score as a soft classification. It is fair to assume that the model outputs are either a continuous value in the case of prediction exercise or a category value in the case of classification. In many classification models, the output is a probability score. Here is the holy grail of possibilities: a combination of Classifiers and Predictors stacked together could solve complex problems and is the foundation of Neural Networks. The number of layers in the neural networks indicates the complexity of learning that is needed and is also a measure of the complexity of space and time problems to solve. The bottom line is that every business problem can be boiled down to a data problem to predict a value classification or a combination of these in any sequence.</p><h3><strong>From Business to Data</strong></h3><p>This is the first stumbling block in the AI journey for the organization; without the right mapping, a perfect AI strategy can fall flat. Leveraging AI for business requires mapping a business problem into a data problem. This requires right questions to be asked. Often, a pressing problem cannot be solved using data as no data patterns generalize this problem. Or it was not a data problem and could be solved using simple rules or heuristics. Technically if there is a single data point that identifies the pattern of the business problem, then we can train on the data to learn that problem. The first challenge we must tackle is identifying the business problem and whether it can be solved using the data available within the organization. Many of the efforts with AI or ML in organizations fail as they do not realize the extent of the data landscape and how much of that can be leveraged for solving problems. Data needs to be seen as a strategic resource and efforts should be in place to collect and store for the right reasons. The last thing one would want to hear is organization getting data richer, but information poorer (2). From the data, we understand the data landscape and information flow and then identify events and or values that depict the patterns of business problems. My go-to questions here are —</p><p><strong>1) What data points represent the business problem?</strong></p><p><strong>2) What is the event that we can define for this business problem?</strong></p><h3>Finding the right strategy for Business</h3><p>There are three ways in which AI can be a key driver for business — for simplicity we can name it as internal, external and niche products.</p><p><strong><em>Internal Strategy</em></strong></p><p>This is the default go to for every organization as part of their data strategy. The ambition here is to achieve operational excellence and reduce the cost of operations. AI can be used to achieve high level of synchronization and automation of operations reducing manual intervention and achieving cost savings. The KPIs for the organization around the optimization and cost improvement should be linked to the AI or ML models to achieve this goal to complete the feedback loop of model-business cycle to achieve those goals. The definition of the data, their governance as single source of truth is a hygiene in this exercise.</p><p><strong><em>External Strategy</em></strong></p><p>The second strategy using AI is that of differentiation. An organization offering a product or service can use AI to elevate customer experience and features. These products or services are wrapped with AI and ML models using data within the product for high level of personalization or differentiation. The product or service possess a level of intelligence and rudimentary operations are automated making this service/product faster, cheaper and better for the customer. Strategy is to kill the competition by differentiation which competition cannot replicate using their existing data. A classic example of this is Autonomous driving vehicles, where AI or advanced technologies allows customer to use their precious time for other things when behind the wheel. They collect enormous amount of data in this process which improves the performance of the learning model in the car reaching near human level perception for different scenarios. Multiple versions of truth are an acceptable norm here as each department can bring their context for the data for creating that experience for the user.</p><p><strong><em>Data Product Strategy</em></strong></p><p>The third strategy is that of making niche data products using organization’s existing data. Data is definitely the new oil in the current economy and can be a treasure trove for many business use cases. Historical data for many years of a domain could be valuable as market intelligence is not free anymore. With digitization wave hitting every industry there are more data collection touchpoints for every business than before and it is only going to increase. This can be combined with open data sources as part of data strategy to create smart data apps, that shares insights/intelligence. Raw data can be monetized in many cases as every organization will turn a data driven organization in the long run as law of competition will catchup with them. An example is the website yahoo.com which has become an aggregator of financial market data. Data collection process, its governance and quality take center stage in such a data product strategy.</p><p>As discussed above AI is poised to make business cheaper, faster and better with time. As more and more processes get digitized and automated, there will be more data for the machine to learn and generalize the pattern of human interaction and will achieve the state of continuous feedback loop.</p><h3>Identifying Gen-AI Use cases</h3><p>Traditional Machine learning use cases revolve around the problems of using Tabular or unstructured data for making predictions and classification. Using unstructured data in texts and images for Natural Language Processing and Understanding and Computer Vision Processing for inferencing over images required neural networks and deep learning techniques. Most of the traditional machine learning is focused on prediction and classification/discrimination to put in Laymans terms. Gen-AI brings another paradigm called generation and uses a combination of generator and discriminator combination to create new text, videos, images. Yes, AI can get creative!</p><h4><strong>Training — Sequence of words</strong></h4><p>Gen-AI use cases can be an accelerator for business as it can learn from existing data and generate new forms of data that is distinctly new and need not have labelled data, at least in the case of language models. As language is a logical sequence of words and each word is by default labeled output of the previous sequence. This neat trick for training is the key to the explosion of use case and research around the GenAI and specifically LLMs. The precursor of Gen-AI was the GAN neural networks which used a discriminator-generator approach and was popular with creative image generation. Since then, Transformer architecture and large language model took over the world of AI by storm. GenAI models are excellent at creating creative content at scale and goes beyond the traditional ML models capabilities of natural language understanding and can be used for a comprehensive set of use cases.</p><p>Recently GenAI has forayed into the fields of Computer Vision models and Vision Transformer or ViT is already making its mark with OpenAI models. Images can be treated as patches or blocks of sequence just like word sequence. Vision, text, audio and video files can be combined for Multi Modal learning models for advance perception and understanding of human world and is being touted as good as human brain. Given these developments, adoption of GenAI tools has been massive as humans can interact with them in natural language and offers immense potential for automating tasks. Foundation models have shown language generation closer to humans and currently has been used for creative contents generation like images, programming code, website designs, document generation.</p><p>For enterprises, a general-purpose technology will be insufficient to meet their needs and Large Language models might be limited in its use case. Enterprises will have to train the LLMs on its domain or in-house data to achieve industry grade results. And cost of infrastructure could be cost-prohibitive as a fixed cost to get started. How would a GenAI strategy would look like vis-a-vis the above 3 pillars for an organization.</p><p><strong><em>Internal GenAI Strategy</em></strong></p><p>At this stage there is definite value in training organizations entire corpus of text data to create a Language Model that has learned the entire knowledge of the organization. The corpus should include meeting notes, executive memos, strategy documents, financial statements, press release etc. The language model could generate legal documents, prepare executive reports and will enable a new nature of work. This will lead CXOs to reevaluate their organizational structure and identify new levels of value creation task. GenAI tools can empower employees, augment managers and force CXOs to lead differently in operations and talent management.</p><ul><li><strong><em>Augmentation </em></strong>— This could be low in terms of complexity and the value created out will be low hanging but is necessary for the GenAI transformation the organization will make. GenAI will play of the role assistant or co-pilot agents in the organization with human in the loop.</li><li><strong><em>Transformation </em></strong>— This might be the end goal in this exercise where there are employees will see agents as co-workers with many organizations’ processes turning autonomous and agentic.</li></ul><p><strong><em>External GenAI Strategy</em></strong></p><p>Embedding GenAI agents or wrappers to products and services is how GenAI can lead the way here. Chat bots have becoming common purpose and can replace sales or customer service agents in this scenario. AI Agents can also do order fulfillment, draft contracts, generate bills with existing customer details. Personalization of content and product discovery for marketing is another use case that business would like to double click on. GenAI allows content generation at scale and allows for a high level of personalization and complements the dynamic pricing engine of the traditional model. Foundation models can be used for external strategy, but external agents will interact with internal agents or have access to external data to server customers and will remain the largest value pool for external GenAI agents. For every traditional ML model that wraps the product, or service will have a GenAI component that can create the content for next best action.</p><p><strong><em>Niche Product Strategy</em></strong></p><p>Organization’s ability to leverage internal data can result in domain specific language models which can be a niche product for other companies in similar domain. Most of the enterprise level use cases using GenAI centers around prompt-engineering and language model fine tuning. Building a large language model from the scratch will have the capability of learning the entire corpus of the knowledge domain and can become a specific purpose language for other users to consume. Building a LLM would incur a cost of hardware and collection of data of the domain. Data from the organization can be used for domain querying and can be offered as a service like OpenAI. The new set of knowledge will have to be constantly fed into the model as the model evolves.</p><h3><strong>Conclusion</strong></h3><p>GenAI is game changer for business and will reshape, reinvent and redeploy business landscape. The value pool of GenAI is not limited to content generation for customer experience, but there is always faster to value in GenAI based services than other software as it is able to mimic human intelligence for rudimentary tasks. The key for business and C-Suite will be to move the organization to a greater pedestal to engage employees to in a technically evolving environment where many jobs will be redefined. At the same time develop guardrails and guidelines of responsible AI with strong levers of internal and external data.</p><h3>References:</h3><ol><li>Venkat Atluri, Alex Singhla et al. Feb. 2024. mckinsey.com. Beyond the Hype: Capturing the potential of AI and gen AI in tech, media and Telecom (TMT). <a href="https://www.mckinsey.com/industries/technology-media-and-telecommunications/our-insights/beyond-the-hype-capturing-the-potential-of-ai-and-gen-ai-in-tmt">https://www.mckinsey.com/industries/technology-media-and-telecommunications/our-insights/beyond-the-hype-capturing-the-potential-of-ai-and-gen-ai-in-tmt</a></li><li>Gartner Research. Feb. 2024. gartner.com. <a href="https://www.gartner.com/en/documents/5188263">How to Calculate Business Value and Cost for Generative AI Use Cases (gartner.com)</a></li><li>Amanda Luther et al. Feb. 2024. bcg.com. <a href="https://www.bcg.com/publications/2024/what-gen-ais-top-performers-do-differently">What GenAI’s Top Performers Do Differently | BCG</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=976b41a44ef8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to get started with Finetuning LLMs]]></title>
            <link>https://medium.com/@rakeshsharma.pr/how-to-get-started-with-finetuning-llms-84affc9e3cbe?source=rss-d98864d89e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/84affc9e3cbe</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Rakesh Sharma]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 11:22:05 GMT</pubDate>
            <atom:updated>2024-10-01T11:22:05.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aDlUgsMlyWtKCFIM.png" /><figcaption>Source: jina.ai</figcaption></figure><h3>Inspiration</h3><p>I have been tinkering around with concepts of LLMs and fine-tuning. This is partly inspired by a terrific course I attended in Maven by Dan Becker and Hamel Hussain — Fine-tuning LLMs for Data Scientists and ML engineers. I am a novice to LLMs, so I thought of dabbling with hugging-face models before taking a plunge into foundational models that have taken the world by storm. If you are curious about the course, here is a link to the course under maven courses, which boasts of various trends in this space at a time when best practices are only forming around these concepts. The course covers a lot of bases on the current ecosystem of LLMs and the tools available to get started on this quickly. It is fascinating to see some emerging tools in this space and how they move from prompt engineering to a full-blooded AI-agentic architecture for many problems. I also agree that there is still a lot of confusion around various concepts, and I hope to distill some of those through this blog.</p><p><em>Note: Let me start by decoding definitions in this space. After I attended the workshops, I realized it is still a very formative space with tools evolving and no set techniques. Understanding the purpose and needs of finetuning will make one grounded before playing with code. Post the program I also tinker with some exercise in the Generative AI nanodegree from Udacity and helps realize the value of some concepts such as PEFT and LoRA which we will discuss in detail in the later sections.</em></p><h3><strong>LLMs</strong></h3><p>Large language models (LLMs) are deep neural networks trained on a large corpus of text, which could include all the texts on the Internet. They have a special place in Natural Language Processing (NLP), which displays capabilities near human language understanding and the next token generation. The texts that feed into LLMs for training can include online books, news articles, Reddit conversations, GitHub code repositories, etc., making it very useful for various tasks. However, LLMs are trained to generate the next best probable text. So, it is a probabilistic model predicting the next text with the highest likelihood from the entire corpus of text it has been trained on. Under the hood, LLMs use the Transformer architecture, which drives modern deep learning networks for tasks specific to Natural Language Inference and Understanding. Transformer architecture was a watershed moment in deep learning as it brings context to the word and generates meaningful text mimicking what it has been trained on. This is also compared to memorization and is not the purpose of a model where it should be generalized.</p><h3><strong>The secret sauce that makes LLMs</strong></h3><p>Technically, Language Models can be broken down into these pieces — Architecture, Input Data and Tokenizer. We will take a look into each one below.</p><p><strong><em>Architecture</em></strong> — Modern LLMs are defined by the transformer architecture, which has an Encoding and Decoding component. Different models use these components partially. For a sequence-generating architecture like GPT, they strip away the components of Encoding architecture and use only the decoder architecture. BERT models use an encoding architecture with masking based on the principle of attention.</p><p><strong><em>Input Data of LLMs</em></strong> — LLMs are deep learning neural networks whose performance depends on the text that goes into them. To define this model, it is necessary to define the text and its conversion into tokens and even sub-tokens. Understanding the data that goes into the model and the preprocessing steps will enable us to develop meaningful outcomes from the model. In researching on this question, I found a list of sources that go into LLMs</p><p><strong>CommonCrawl/C4<em> — it is non-profit organization that crawls the web and freely provides its content as an archive. It completes an internet crawl every month. You can take a deep dive into their website </em></strong><a href="https://commoncrawl.org/#:~:text=Common%20Crawl%20maintains%20a%20free,%20open%20repository%20of%20web%20crawl"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><p><strong>Eluether-AI —<em> it is a non-profit organization that does research on interpretation and alignment of large AI models and is open source. Their language modeling is cutting edge, and you could read more </em></strong><a href="https://www.eleuther.ai/about"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><p><strong>ROOTS — <em>It stands for Responsible Open Science Open Collaboration Text Sources and is a corpus of 1.6TB dataset spanning 59 languages. There is a </em></strong><a href="https://proceedings.neurips.cc/paper_files/paper/2022/file/ce9e92e3de2372a4b93353eb7f3dc0bd-Paper-Datasets_and_Benchmarks.pdf#:~:text=This%20paper%20documents%20the%20data%20creation%20and%20curation%20efforts"><strong><em>paper </em></strong></a><strong><em>is NeurIPS that explains the purpose of this text and its usages for language model training.</em></strong></p><p><strong>Wikipedia — <em>As we all know is the most common know encyclopedia with free content and maintained by volunteer developers.</em></strong></p><p><strong>BookCorpus — <em>Papers with code defines it as the large collection of free novel books written by unpublished authors and has more than 16 sub-genres. You can take a look at the dataset </em></strong><a href="https://paperswithcode.com/dataset/bookcorpus#:~:text=BookCorpus%20is%20a%20large%20collection%20of%20free%20novel%20books%20written"><strong><em>here</em></strong></a><strong><em>.</em></strong></p><p><strong>Gutenberg —<em> It is a library of more than 70000 free </em></strong><a href="https://www.gutenberg.org/#:~:text=Everything%20from%20Project%20Gutenberg%20is%20gratis,%20libre,%20and"><strong><em>ebooks</em></strong></a><strong><em>.</em></strong></p><p><strong><em>Tokenizer</em></strong> — LLMs treat the vocabulary as tokens of the large text corpus. These tokens are long vectors that represent text in space and are called embedding. For the LLMs to infer or predict the input data, we need to tokenize it using the tokenizer specific to the LLM. This would generate the LLM-compatible tokens for it to process and understand.</p><h3>Text Generation as a Service</h3><p>From now on, LLMs can be defined as text generation at an API call, as we all have used some prompting with ChatGPT models. But LLMs can be used for many other tasks, even for classification, which will require an extra step in the end called Finetuning, which we will discuss in the next section. Many other models, such as Gemini, llama, and Mistral, also have the same functions where we prompt a text, and the model regurgitates text based on the model architecture and the data it is trained on. To generate the text of your liking, we will need to understand the data on which it was trained. The possibility of new knowledge generation is rare to impossible as they are trained to generate the most likely next text. However, LLMs today have been used for many other problems than text generation, and they are becoming an extension of the traditional models for prediction and classification tasks. In this blog, we will deal with text generation use cases, pass by other use cases, and treat LLMs as a model for generating sequences of coherent texts.</p><h3>Why do LLMs Hallucinate?</h3><p>LLMs are trained to statistically output the most likely text when we prompt a text. If the prompt you make is an excerpt from the beginning of a document, it will generate the rest of the document. There may be cases where our prompt generates meaningful text but is factually incorrect. Such text generations are called hallucinations, and the way LLMs work, they are prone to hallucinations. It can be overcome by sharing more context in the prompt text, but inherently, LLMs assume the prompt text to be factually true, and there is a truth bias in the prompt text. This flaw also necessitates humans to be in the loop to avoid make-believe prompts. Checks should be applied to the automated prompting systems. I tried this out in the prompt to see truth bias, but the response was moderate and better than expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5C22ESggAkzsBQ8JeVdcvQ.png" /><figcaption>Source: ChatGPT prompt</figcaption></figure><p>The larger the dataset trained on the LLMs, the larger the tokens, and the larger the compute the better the model output. This is the power law of LLMs, so they will only get better at extracting and generating knowledge from the text inputs they are trained on in the long run.</p><h3><strong>Finetuning 101</strong></h3><p>Let me start with defining fine-tuning. Fine-tuning is a technique within transfer learning where one can use the existing models to learn new data. The massive advantage of Deep learning networks is that they can be trained on a new set of data with all the weights completely updated, learning something new, also called catastrophic learning, where it forgets the weights of the last training. Or we can freeze certain layers and train the layers on the new data so that only select layers get updated. There are pros and cons of both methods. Observing the evolution of the LLMs, we can see a bifurcation in performance. First, there are foundational LLMs, which have many parameters, and task-specific LLMs, which are smaller in size. Finetuning is the bridge between the two. Finetuning relies on whether one would like to use the foundational models for domain-specific tasks. One could get started with the Hugging Face libraries, which bring some handy libraries to get this with minimal fuss.</p><h3><strong>When to Fine-Tune</strong></h3><p>Do not default to Finetuning even if you have a specific task. After trying out several cases and listening to experts, I learned that one should start with a few shot examples and prompting. Most of the cases are solved using careful instruction sets and prompting. However, if we are looking to update facts and new knowledge, the RAG technique might be our friend. Instruction set prompting get un-manageable and will be limited by the token length. By adding context and examples we are not changing the weights of the model, but in finetuning process we are indeed updating the weights of the model and is ideal for complex learning and knowledge extraction. We also need to have dataset with proper input-output mapping to finetune and will have to look beyond synthetic data generation. A prompt can be divided into several component and each has a role in curating the answer from the LLM, prompt templates within LangChain helps us gets around this with different placeholders. Again, they are limited by the length of the prompt. Perhaps chain of thought technique could be an answer in this direction, and that makes for a different discussion. Now that we have covered the questions around on the capabilities of the LLM and how and where Finetuning comes in. Let us focus on a simple finetuning task using <strong><em>Huggingface </em></strong>model repository, I will use the Google Colab Jupyter notebook environment to demonstrate this example. There are several libraries that one can use for this process along with there are critical parameters we need to keep in mind to finetune the model.</p><h3><strong>What Parameters of the model we are Finetuning</strong></h3><p>It is great question to ask what parameters we are finetuning for. If one takes a look at the <strong><em>Huggingface </em></strong>documentation for the class <strong><em>TrainingArguments </em></strong>there is a plethora of arguments and is scary to see as a developer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*CGaNbk_MbyQSmPs7LrwsNg.png" /></figure><p>In this blog I will be covering only the important ones such as <strong><em>algorithms</em>, <em>memory and space optimization, quantization, regularization and distributed training</em></strong>. With the choice of learning algorithms comes trade off over memory allocation. Optimization algorithms serve the purpose of learning and uses forward propagation and backward propagation steps along with weight decay to learn the weights. There are several parameters within learning algorithms we can fine tune to meet our goals</p><p><strong>Optimizers — </strong>For example, <strong><em>Adafactor </em></strong>and <strong><em>SGD </em></strong>uses 4 bytes per parameter, <strong><em>AdamW </em></strong>use 8 bytes instead. In many of the code samples we see the use of 8 bits optimizer being used and is an ideal choice when we need to pretrain LLMs with memory constraints, these also support quantization which we will discuss in detail shortly.</p><p><strong>Learning Rates — </strong>Literally it is the rate at which model adapts to the problem at hand, leading to a reduction in the loss of the mode. The easiest way to visualize in the step size towards the lowest point in a gradient descent algorithm. Learning rates is a hyperparameter and needs to externally be supplied during the LLM training. <strong>2e-05</strong> is the rate that works well with <strong><em>AdamW. </em></strong>It has to be noted that learning rate here is different from what we pass to train an ML model from the scratch. Learning rate along with weight decay value of 0.01 is combination that gives best results. The rest of the parameter need not be tinkered with and remains good as defaults.</p><p><strong>Learning rate Schedule — </strong>Ideally learning rate should adjust itself in the final epochs so that we reach the global minima of the loss and not overshoot the ideal value. This framework enables the algorithm to arrive at the optimum value. Initially it is ideal to have larger learning rate by which the model weights are learned quickly to generalize and in the later stages the learning should be specific which is achieved by lowering the learning rate. There are 2 ways this framework works</p><ul><li><strong><em>Constant rate — </em></strong>The learning rate cannot be changes and is set from the beginning.</li><li><strong><em>Learning rate decay — </em></strong>The learning rate is higher in the beginning and get smaller in the later epoch of the learning, this finetunes the weights of the model to task specific at hand.</li></ul><p><strong>Memory Optimization Parameters</strong></p><p>Once we set the optimizer for the algorithm, we can control their memory and compute optimization parameters using these 2 techniques.</p><ul><li><strong><em>Gradient Checkpointing —</em></strong> It helps in saving the activation values of the forward pass to be used in the backward pass. This reduces the load on the memory but costs more on compute. The missing activations can still be computed when needed in this technique but helps in overcoming memory bottlenecks</li><li><strong><em>Gradient Accumulation — </em></strong>For large batch size calculating the gradient may be limited by memory. In such cases we can accumulate the gradient for multiple batches generates an average gradient. This makes the process slower on the other hand as there are no frequent updates.</li></ul><p><strong>Quantization — </strong>It is a model compression technique that converts the weights and activation values within the LLMs trained memory from high precision value to low precision. An example would be moving from 32-bit floating-point number to an 8-bit integer, there is information loss and but comes with more portability and less memory consumption for AI.</p><p><strong>Regularization Techniques — </strong>These techniques are used in Machine learning to reduce the effects of overfitting. There are several techniques to employ to achieve regularization</p><ul><li><strong>Label Smoothing<em> — </em></strong>Label smoothing helps in model calibration. During any data classification task, the data is scored against the labels using a hard classification technique. The SoftMax cross entropy algorithm fits the activation values final layer into values between 0 and 1. In label smoothing a regularization term is subtracted or divided from these values making it more generalized for new data. This technique is useful when learning from noisy data.</li><li><strong><em>Noise Embeddings — </em></strong>Finetuning datasets are generally small and there is high chance that model overfits on the stylistic characteristics of the document. To overcome these issues, we can add noise embeddings to the dataset. In this technique a noise vector is sampled from IID [-1, 1] and they are added to the embeddings vector of the text data and scaled. It has been found to significantly reduce overfitting. Hugging face has a library NEFTune for the capabilities of noise embedding.</li><li><strong><em>Batch Size — </em></strong>Larger batch size will accelerate the learning by the model. The tradeoff is that it will require more memory. There is also a more chance of model getting caught in sharp local minima and will cause overfitting. The default parameter of Hugging Face library sets the batch size that fits the memory. Batch size should be used in conjunction with learning rate. A high learning rate will lead to overshooting the minima and model will not converge. A large batch size will lead to low variance between different batches and model will have a steep gradient. The key is to get a flatter gradient with smaller batch size and higher learning rate to converge faster.</li></ul><h3><strong>How to do PEFT?</strong></h3><p>The above parameters serve well for a finetuning but could be prohibitively costly in terms of compute and memory if we were to finetune all of them for the model to learn. Ideally one would like to adjust minimal parameters for the getting the maximum effect and Parameter Efficient Finetuning or <strong>PEFT </strong>for short is a technique for that. In <strong>PEFT </strong>we will update only a small portion of model parameters, and it can be easily managed by the <strong><em>peft </em></strong>library from <strong><em>Huggingface</em></strong>. PEFT brings huge savings on compute and memory, and we can use several techniques to achieve this, one of which is LoRA. The below image shows how LoRA uses the technique of low rank decomposition to store the gradients and weights in memory. There are several key parameters we need to consider in LoRA configuration.</p><p>LoRA stands for low rank adaptation and allows us to train dense layers indirectly by optimizing rank decomposition of matrices of dense layers change during adaptation, while keeping the pretrained weights frozen. The idea stems from the hypothesis that change in weights during model finetuning has a low “intrinsic rank”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v7kWSzqYuyT8BUvJ.png" /><figcaption>Source: <a href="https://heidloff.net/v">https://heidloff.net</a></figcaption></figure><p>They are</p><ul><li><strong>r </strong>— Attention dimension of LoRA</li><li><strong>lora_alpha </strong>— The alpha for LoRA technique</li><li><strong>lora_dropout </strong>— The percentage of nodes in the LoRA finetuning process that will be dropped for generalizability</li><li><strong>layers_to_transform </strong>— The layers on which LoRA transformation is applied</li></ul><p>There are several key advantages with LoRA</p><ol><li>It lowers the hardware entry barrier as we do not need to maintain the matrix of weights in memory and can optimize the low-rank matrix</li><li>It is faster due to the linear design and can be used to combine trainable matrices with frozen weights</li><li>We can build several small models from a pre-trained model using LoRA and switch between different tasks by saving and loading different matrices in memory</li></ol><h3><strong>Reducing Floating Point operations</strong></h3><p>Working with reduced precision for floating point operations is a technique we mentioned before for model weight and activation functions to adapt to. There are libraries using which we can load the model weight in lower precision. <strong><em>bitsandbytes </em></strong>is a library that is integrated in Huggingface for this purpose. There is a configuration class that helps us load the model in memory with lower precision by setting parameters, here are few to look at</p><p><strong><em>llm_int8_threshold — </em></strong>The threshold value beyond which fp16 will be used</p><p><strong><em>llm_int8_skip_modules — </em></strong>Specify the exception for which we do not want int8 precision</p><p>Similarly, there are many such configuration parameters to set, I will be exploring these in a notebook separately as a follow of the series on LLMs</p><h3>Conclusion</h3><p>Finetuning is buzzword that is thrown around and must be used for achieving things outside RAG or context-based learning. Finetuning can be achieved at several levels, precision based fine tuning techniques such quantization comes at a cost but retains portability and compute efficiency. PEFT technique is popular for selective finetuning and not on the complete dense layer. I will deep dive into advanced finetuning in a follow up post, so keep reading my post. Thank you!!</p><h3>References:</h3><ol><li><a href="https://symbl.ai/developers/blog/a-guide-to-quantization-in-llms/#:~:text=While%20there%20are%20several%20quantization%20techniques%2C%20the%20most,fine-tuning%20on%20data%20with%20quantization%20in%20mind.%20">A Guide to Quantization in LLMs | Symbl.ai</a></li></ol><p>2. Suhas Pai. 2023. Oreilly Media Inc. Designing Large Language Model Applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84affc9e3cbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with LangChain]]></title>
            <link>https://medium.com/@rakeshsharma.pr/getting-started-with-langchain-cf3bce29066b?source=rss-d98864d89e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf3bce29066b</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rakesh Sharma]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 16:55:34 GMT</pubDate>
            <atom:updated>2024-09-23T16:55:34.070Z</atom:updated>
            <content:encoded><![CDATA[<p><em>LangChain has emerged as the default toolkit for interacting with LLMs. However, one can do without LangChain and rely on an SDK, like the OpenAI SDK or others. Interaction with multiple language models will make this a tedious process, which brings us to the purpose of LangChain. Before delving further, I want to define it as an interface that abstracts away the individual implementations of large language models (LLMs).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*DwDbUgpGamXxUicB.jpeg" /><figcaption>Source:GoPenAI</figcaption></figure><h3><strong>Prelude</strong></h3><p>LangChain is a Python library that offers the building blocks of applications with generative AI capabilities. The core purpose of this company, from the mouth of its founder — is to make interaction with LLMs easier; here is the link to the <a href="https://youtu.be/29XE10U6ooc">video</a>. Technically, it abstracts away the individual functions of LLMs and brings a programming interface that is more intuitive and more commonly pattern-based than their original SDKs. LLMs will evolve with time and bring in more functionalities and capabilities, but no singular API allows users to interact with all of them; LangChain bridges that gap. LangChain is the layer that will keep up with that development and make the interface a breeze. There are many other substitute technologies in this space, like embeddings, vector stores, and ChatAPIs; I would like to explore the possibilities of those with LangChain in this series of blogs. However, LangChain offers programmatic control over all the LLMs using their callback functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/0*UMJjtWUfPSm9Y5fW.png" /><figcaption>Source: datasciencedojo.com</figcaption></figure><h3><strong>Getting Started… LangChain APIs</strong></h3><p>One of the most straightforward use cases of LangChain is its interaction with the LLMs. We can load the open AI models and invoke a prompt, and output can be controlled using parameters such as <strong><em>temperature </em></strong>and <strong><em>max_tokens</em></strong>. In further sections, I will share a notebook with examples of how we can do this using the OpenAI APIs. There are 2 parameters that can be used to control LangChain outputs, they are</p><p><em>temperature</em> — Temperature controls the sampling algorithm for the output of the LLMs. A low value gives more predictable output, and a high value gives more creative output. The value of temperature ranges from 0 to 1.</p><p><em>max_tokens</em> — determines the output length; if that value is 1, it will output only the most probabilistic word. The max_tokens value truncates the output length and can be controlled for various use cases. For GPT 5, it is 4096 tokens.</p><h3>Understanding the Abstraction</h3><p>Another important concept is the of the abstraction of the interaction type within LangChain. LangChain takes into consideration 3 types of interaction — <em>System role</em>, <em>user role</em> and <em>Assistant role</em>. Universally there are three types of interactions that a language model faces — a model can interact with user input who is using web interface with the prompt, a developer using the API making a function call. Another possibility in the realm of AI is output from a model can go in as model input for interaction like an agentic interaction.</p><p>LangChain implements a prompt template that allows users to define context, questions and share examples programmatically. Text based prompts become unwieldy when the prompts become bigger with examples and complex contexts have to be shared. Given this issue, there are three types of messages that can be used for interacting with the LLM. They are system, human, ai, function and tool messages. Let us define these messages here.</p><p><strong><em>SystemMessage </em></strong>— it tells how the model should behave, and it is usually content and there are additional properties that can be defined</p><p><strong><em>HumanMessage </em></strong>— a message from the user.</p><p><strong><em>AIMessage </em></strong>— it is the message from the model and is content generally and additional parameters can be passed like <em>tool_calls</em></p><p><strong><em>FunctionMessage </em></strong>— This message is a result of a function call and carries 3 additional parameters <em>role</em>, <em>content </em>and <em>name</em></p><p><strong><em>ToolMessage </em></strong>— This is the result of the tool call and will contain after <em>tool_call_id </em>in addition to the above parameters.</p><p>A user invokes three methods with LangChain: invoke, batch, and stream. These methods are defined under the Runnable interface. <em>Invoke </em>is the most commonly used method and can be used for a single input into the LLMs; <em>batch</em>, as the name suggests, can be used for multiple inputs. <em>Stream </em>function can be used for token-by-token input transformation.</p><p>LangChain also comes with two ways a developer can interact with the LLMs — an imperative form and a declarative form. The imperative type uses a decorator to invoke the prompt using a defined template. It uses the methods we listed above, namely invoke, batch, and stream methods, to interact with the LLMs. The declarative language uses a pipe operator and is an expression language written in Python/JavaScript, making it easier to build components for a full-blown LLM application. We will see the difference in the code examples below, but at a high level, this is how the toolkit interacts with LLMs. Critical differences exist in the program&#39;s execution based on these two styles; for example, parallel execution and asynchronous execution need to be handled programmatically in the imperative style while is automatic in the declarative style. It is good to default to the declarative style if one is trying to connect and interact with different components. The imperative style is more helpful in creating custom logical flows with more flow control.</p><h3>Injecting your documents into LLMs</h3><p>LLMs are trained on the public corpus of data, and one of their drawbacks is that public data might be old and not current and might miss private data. There is a cut-off date for LLM outputs that can lead to inaccurate or outdated information that we understand as hallucinations. There are two stages of processing that need to include private documents,</p><p><strong>Chunking </strong>— Documents are broken into different pieces, which will be based on the token length.</p><p><strong>Indexing</strong>—The chunked documents are stored with an index for fast retrieval. Indexed chunks can be searched based on similarity to add context. LangChain tracks the document chunked for changes using a hashing index, write time and source ID of the document.</p><p><strong>Embeddings </strong>— At the heart of LLMs is the vector format of text, also known as embeddings. The texts that LLMs are trained on can be represented as a vector of large dimensions in space where similar texts are represented, and this leads to semantic meaning. In the semantic embedding space, a word like <em>cat </em>will be closer to <em>dog </em>or animal but far away from a <em>lion </em>or <em>tiger</em>.</p><p>There are many other uses of embedding as a data structure, such as <em>search</em>, <em>clustering</em>, <em>classification</em>, <em>recommendation, </em>and <em>anomaly detection</em>. LangChain comes with methods for loading documents such as .<em>htm and</em> .<em>pdf </em>and extracting the text content. Another library, unstructured.io, is more comprehensive in terms of features and can be used here, which can be a full-length blog post some other time.</p><p>LangChain has an embedding interface that can be used to embed texts and documents using the embedding structure of the available LLM models. The generated embedding can now be stored in memory for processing or persist in a Vector DB or vector store. LangChain comes with read-and-write methods for the Vector DB. Vector store will index the documents in the embedding space and can be used for fast retrieval or search when our LLM application needs integration with RAG techniques. RAG is a technique for enhancing the accuracy and response of the LLMs to user prompts, and it will be a new topic for discussion in my follow-up post on the same technique. The image embedded below explains just what we discussed in the above sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W_ZUy00AxDlP_IC8.jpg" /><figcaption>source: LangChain.com</figcaption></figure><h3>Conclusion</h3><p>LangChain is the new framework for interacting with LLMs. The LLM landscape is changing fast, with new models being released daily. LangChain abstracts away many details needed to interact with the LLM SDK and gives the power to control the flow of prompt interactions with multiple LLMs programmatically. A Google Colab notebook is shared <a href="https://colab.research.google.com/drive/1W5R7QYBLaX5-3u00N9IJATNYAEYHva7p#scrollTo=3JDJuscus1kK">here</a> and can be used to understand the fundamental interactions and concepts I have mentioned here. I plan to write a follow-up post on using RAGs with LangChain and will formalize an architecture for implementing an LLM application.</p><h3>References:</h3><ol><li>Mayo Oshin, Nuno Campos. Oreilly Publicaitons. Learning LangChain</li><li>Rakesh Sharma. Google Colab. Getting started with LangChain with examples. <a href="https://colab.research.google.com/drive/1W5R7QYBLaX5-3u00N9IJATNYAEYHva7p#scrollTo=3JDJuscus1kK">https://colab.research.google.com/drive/1W5R7QYBLaX5-3u00N9IJATNYAEYHva7p#scrollTo=3JDJuscus1kK</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf3bce29066b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analytical queries SQL — Data Scientist’s best friend]]></title>
            <link>https://medium.com/@rakeshsharma.pr/analytical-queries-sql-data-scientists-best-friend-61ce6e861263?source=rss-d98864d89e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/61ce6e861263</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-window-functions]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Rakesh Sharma]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 09:01:00 GMT</pubDate>
            <atom:updated>2024-08-22T09:07:38.536Z</atom:updated>
            <content:encoded><![CDATA[<h3>Analytical queries SQL — Data Scientist’s best friend</h3><p><em>More and more data find they&#39;re into databases, SQL will remain the evergreen language to learn. I am a data scientist and I Python, R and Julia for my Data Science projects, but data extraction end points are always some tabular databases. In this blog post, I aim to give a taste of decoding business queries outside the comfort of Jupyter Notebook.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*afXGNNyR1HreCYFz" /><figcaption>Source: stratascratch.com</figcaption></figure><h3>Introduction</h3><p>Undoubtedly, the world will see more than 80 % of the data in the unstructured format in the form of text, images, and videos. The rise of apps and social media has contributed to this inequity. Regarding enterprises, over 80% of the data is still in the tabular format, and SQL is your best friend to hack at it. Data Scientists love to code in Python and R and are adept at bringing data into their notebooks for analysis. Extracting and transferring data from the database to your computer is always a computational cost. From transactional databases to analytical DBs, knowing analytical functions is a must in your day-to-day life as a data scientist, as it allows statistical analysis within the data lake and does not hog the network. In this blog, we will explore some business analytical queries and see how we can frame the business problem as an SQL problem and find answers. This blog draws inspiration from my work at my current company, a leading Telco in Dubai, where I have used Teradata advanced SQL functions to solve business questions using descriptive analytics.</p><h3>Analytical functions available</h3><p>Data engineers refer to analytical functions, which are generally referred to as window operations. It means looking through a window, or the user would like to understand the data within a set context, or a defined set of rows related to a single row. In other words, this is similar to an aggregation operation, but in normal aggregation, the query outputs a single row against a column value in the group by clause. In the case of window functions, they retain the original rows of the data set and output aggregated value against each row. These functions can be generally divided into statistical functions and offset functions. Common windowing functions are <strong><em>LAG()</em></strong>, <strong><em>LEAD()</em></strong><em>, </em><strong><em>ROW_NUMBER()</em></strong><em>, </em><strong><em>RANK()</em></strong><em>, </em><strong><em>NTILE()</em></strong> etc. and us used in conjunction with <strong><em>OVER</em>()</strong> clause treats the operation as a window function and causes it to retain all the data rows in the dataset.</p><p>Plying your trade is about answering business queries quickly, and knowing these advanced functions would reduce your time to insight (TTI), a critical metric for data analysis. In the coming sections, I will explain how to use these functions against a business analytical query.</p><h3>Let us start windowing...</h3><p><strong><em>Lag </em></strong>— One of the most commonly used window functions is the lag. Lag generates the previous value of the column over the partition and makes the work easy by avoiding the use of correlated queries. I like correlated queries and is ideal for fetching values against a row. But lag achieves the same result with cleaner code. In the below query example <strong><em>business is interested to see the previous day’s revenue per user</em></strong> and can be achieved as shown below. The query does not have a group by clause for summarization but summarizes against all the rows without restriction. The results of the query can be seen below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGQJBpm2iMrYGJcKYu_mVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*DIgSKheL5yd9ll1ctD4H-g.png" /></figure><p>Within the same context we can answer many other analytical queries. Business is interested in knowing how the revenue has changed week by week. In this case business wants to know of their campaign or offer has brought any uptick in revenue over the week. We will use rows preceding clauses to take the weekly average using the OVER clause. It can be expressed as below. Take a close look at the result table below, the average of the highlighted set of values is the 3.808. The preceding clause uses the previous 6 rows as the window for the operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wbuJaWr7C4XzKoeQZi2Tg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*kyUz4k08RpakQS8tvDtGjA.png" /></figure><p>Suppose business wants to do this analysis with respect to users who have used the service for at least 14 days. We can achieve this using another window operation called <strong><em>ROW_NUMBER </em></strong>or <strong><em>RANK</em></strong>. Take a look at this below as I am using <strong><em>ROW_NUMBER </em></strong>operation here within qualify clause. Qualify is used for filtering within the window operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bya2x3uT6NGuQ3ajMUPIDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*BndkMWnjxhaV5yvlBGUyhg.png" /></figure><p>In this case we do not see records of earlier dates for the user as rollup operation of the last 7 days is not meaningful here. We can add further complexity to the above operation with the business question such as finding the week-on-week growth of the revenue and finding users which has seen back-to back growth at least 3 weeks. I will make use the <strong><em>ROW_NUMBER </em></strong>and <strong><em>RESET </em></strong>clause to achieve the trick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xo2am1wALoM9yNj-9rBEag.png" /></figure><p>In the above example I am creating a CTE table <strong><em>weekly_data </em></strong>and generate the weekly <strong><em>avg_revenue </em></strong>using the preceding clause. The partition is filtered for the 7th days of the week so that we are comparing it week by week. The resulting query is then processed further for consecutive increase in the <strong><em>last_week_revenue </em></strong>column using <strong>row_number</strong>(). The inner working of the <strong>row_number</strong>() uses a rest clause which resets the <strong>row_number</strong>() on a condition that current value is less than the previous value. To answer the business question, we should look at the values of new column <strong><em>revenue_increase </em></strong>with values with consecutive values 0, 1, 2, 3 as seen below for the <strong><em>user_id </em></strong>6688.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*f7aHYnP9va9mOfhBeenONQ.png" /></figure><p><strong><em>At this point the business question is to find out what the longest streak of such an increase is. </em></strong>We can use the above output to achieve the longest streak for the whole customer base, for each customer and also a histogram of frequency of such streaks for at least 3 weeks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*32qXKTcn7qf9dvKynuWPcQ.png" /></figure><p>In the above figure I am finding the longest such streak, surprisingly we see a 13-week streak, whoop! That is an amazing find. I am curious to investigate how and why average revenue user has increased. We could also create a histogram of the longest streak for each user. By now you know the drill, use <strong><em>MAX()</em></strong> function over the <strong><em>user_id </em></strong>partition, as simple as that! We could also use the group by clause to achieve the results and it will return only distinct rows as it is what we need to return a histogram data. However, I would encourage anyone moving to windowing concepts to stick to this query pattern to relearn and use the concepts. I am achieving this using the subquery and count operation as show below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bJd7CXay_8oIKjyU7NM5VQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*4fztG-ZVRzkGA8XRM2pujA.png" /></figure><p>The results look convincing, highly skewed histogram with very few counts of long streaks and hyper-majority of users with no streak and up to 2-week streak.</p><p>I would like to cap the analysis by find the number of 3-week streaks per user and analyzing their histogram. The three-week streak can be inferred from the revenue_increase column using the filter with <strong><em>MOD </em></strong>operator with 3, row_number index sequence of 2 + (0*3) + 2 + (1*3) + … The count of these indexes will give the 3-week streak count for each user. The below figure captures the SQL operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Ao1lJojHzv_7qAZGwznMw.png" /></figure><h3>Conclusion</h3><p>Thats marks the end of the Windowing session for now, we have not explored all the functions in here. There are several analytical functions which one can make use of the more complex ones involve groups and island logics, which we will see in another post. The examples above are using the Teradata SQL and data is a hypothetical sample of revenue usage. SQL is a proven weapon in the arsenal of Data Scientist and should help in quick analysis for business queries.</p><p>Will reach with another post on deeper insights on window functions which helps in summary and statistical analysis using SQL.</p><p>Happy Windowing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61ce6e861263" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science on the Command Line]]></title>
            <link>https://medium.com/@rakeshsharma.pr/data-science-on-the-command-line-121fd9922642?source=rss-d98864d89e4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/121fd9922642</guid>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[awk]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rakesh Sharma]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 17:37:23 GMT</pubDate>
            <atom:updated>2024-09-23T16:59:07.068Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Linux utilities or their equivalents in the Windows subsystem (WSL) are handy tools for quick data analysis. These tools are akin to pocket knives and can do tricks when working in a non-visual environment. Awk and sed, along with other Linux commands, can be powerful toolkits for a data scientist. Keep reading to learn more.</em></p><h3><strong>Introduction</strong></h3><p>Data is not always available in a highly secure data vault; sometimes, it is in CSV and can be processed with very little visualization or knowledge of metadata. Excel readers are perfect for this, with their blend of power query and advanced Excel functions to parse and munge the data. If you are a Linux user who loves to work with the command line, then awk, sed, and gawk could be your everyday friends. This post will discuss advanced usage and tricks with awk to process CSV files in detail. I will work with the WSL on my gaming laptop to share the examples and use airports.csv as the dataset for my data querying tasks. Airports.csv is an open data set and is available <a href="https://ourairports.com/data/">here</a>. You can read about this dataset and combine others for meaningful analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*BTpjNNfM9SelONc8.jpg" /></figure><h3>First things first</h3><p>Once data analysts receive a CSV file, they may want to explore its metadata and data structure. The Linux shell has nifty commands for this and evokes the memories of the <strong><em>head()</em></strong> in R and Python. We will use a combination of cat and head using a pipe operator to accomplish this. Next, we would like to know the size of the records and the number of rows and columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DApxMqOj6_p5XjT-MmeOrA.png" /><figcaption>Source: author</figcaption></figure><p>To find the number of rows, we can use the command word count wc and its switch l; the number of columns can also be counted using the header we obtained in the above step. Since the first row contains the column names, we can translate the header row into a column and count the number of lines as before. This is a neat trick and can be done as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ql0XR_KTCRAXfDvxYxVaGA.png" /><figcaption>Source: author</figcaption></figure><p>As we can read from the command output, there are 80k+ rows and 18 columns. We can list down the columns to understand more using the command below, making it more readable. It replaces the comma with a new line using the tr command and lists down the column headers, as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wv0rQ1VIUtmbqs48ES_Gw.png" /><figcaption>Source: author</figcaption></figure><p>As handy as it seems, for more powerful operations, we can use sed and awk, which were made for pattern matching and querying files on the command line. Commands for advanced operation shell scripts could be limited, but mastering advanced awk one-liners could achieve stunning results. Let us start by playing around with parsing the files. We will use the command to select only the first column of the CSV. To achieve this, we must specify the separator, a comma, and the column number. The format can be seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ue6L9GMYwZInIBmDb3P2lA.png" /><figcaption>Source: author</figcaption></figure><p>In the command above, FS is the field separator, and $1 is labeled as column one. We can now combine multiple fields by numerical identifier and see the output. There is a special field called NR — which stands for the number of records and counts the number of records printed so far. It can be used as a serial index of our output records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xd5JDPsS1e6gboDloDIsOw.png" /><figcaption>Source: author</figcaption></figure><p>Awk commands are also powerful with selection. Filtering by condition is a basic operation a data scientist would like to perform. Awk has a feature for text-based selection for the fields and logical operators like NOT, AND, and OR. It has excellent data validation features and should not be limited to those who are sticklers for data quality. In the examples below, we will filter by text and numbers for basic data quality checks.</p><p>I want to filter by airport_type and select all heliports. The airport type is double-quoted in the file, so I must use the escape character.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*siO7BJWosedQ9w8Zeq7URQ.png" /><figcaption>Source: author</figcaption></figure><p>We can use numerical values to filter records. In my next example, I would like to find records with elevation greater than 3000 ft. I will also set a variable for this filter in the BEGIN block to use in the next processing block. As seen below, I declare a variable called <strong><em>min_el=3000</em></strong> in the <strong><em>BEGIN </em></strong>block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XPnnztszMLBnqYvflIyxNQ.png" /><figcaption>Source: author</figcaption></figure><p>I have used the NOT operator ! to engage the above condition to receive the records with an elevation of less than 3000 feet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-ppRtxXEibEo0y6SLYAhg.png" /><figcaption>Source: author</figcaption></figure><p>Counting is integral to any analysis; AWK allows one to declare and increment variables. In the next example, I count the number of heliports in this file. We can do this using the shell utility wc, but the awk command adds more flexibility and control to such operations. We can see the two usages in the image below. In the AWK-based approach, I declare a counter c and increment the counter based on the condition. The output is being formatted using <strong><em>printf </em></strong>using the END block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mQFOI_79R78L-hYU9DBYRg.png" /><figcaption>Source: author</figcaption></figure><p>We will now look at some further complex operations. I would like to find airports with elevations between 2500 and 3000 feet and identify the number of airports with no scheduled services. We can use a combination of conditions here; I will introduce an if-else logical block to achieve the above, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XzmrYPdntNFInsKH1fMKg.png" /><figcaption>Source: author</figcaption></figure><p>As shown above, I declare 3 variables: no, yes, and all, and iterate them based on the if condition checking for the column; there are better ways of formatting, and the script is not very elegant, but for complex operations, it is better to write awk scripts rather than piping in longer unwieldy commands.</p><h3><strong>Conclusion</strong></h3><p>In my exploration of AWK for the command line, I felt compelled to write about its simple use cases and its capability of fast processing. Many other utilities help in the EDA of CSV files and are one of the most underrated tools for data exploration. CSV is a very popular format in Linux and Windows environments and other BigData systems; awk has many interesting switches along the sed for pattern matching and is a must-have for any data scientist in a terminal environment. I was inspired to write this blog after stumbling upon the online book <a href="https://datascienceatthecommandline.com/">https://datascienceatthecommandline.com/</a> as I am an old-schooler who wanted to vett his hands with old commands from my memory. In the follow-up, I plan to dive deeply into EDA using CSV and other utilities with AWK. I hope this short blog inspired you to explore AWK for data science.</p><p><strong>References:</strong></p><ol><li>Jeroen Janssens. nd. Data Science At the Command Lone. <a href="https://datascienceatthecommandline.com/">https://datascienceatthecommandline.com/</a></li><li>Alfred V Aho et.al. nd. The AWK Programming Language.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=121fd9922642" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>