<?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 Saurav Agarwal on Medium]]></title>
        <description><![CDATA[Stories by Saurav Agarwal on Medium]]></description>
        <link>https://medium.com/@sauravagarwaldigital?source=rss-5dd9f45313ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ylPHgFpn2d6ewtnJ8uO0uw.png</url>
            <title>Stories by Saurav Agarwal on Medium</title>
            <link>https://medium.com/@sauravagarwaldigital?source=rss-5dd9f45313ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:28:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sauravagarwaldigital/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[Envisioning a Generative AI OS — The Backbone of the AI-Native Enterprise]]></title>
            <link>https://sauravagarwaldigital.medium.com/envisioning-a-generative-ai-os-the-backbone-of-the-ai-native-enterprise-27102b2b18ae?source=rss-5dd9f45313ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/27102b2b18ae</guid>
            <category><![CDATA[generative-ai-solution]]></category>
            <dc:creator><![CDATA[Saurav Agarwal]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 16:50:36 GMT</pubDate>
            <atom:updated>2025-11-22T16:51:16.900Z</atom:updated>
            <content:encoded><![CDATA[<h3>Envisioning a Generative AI OS, Backbone of the AI-Native Enterprise</h3><p>We’re at an inflection point.</p><p>Most enterprises today don’t have “an AI platform” they have an <strong>AI pile</strong>.</p><p>A code-generation tool here, a workflow engine there, an evaluation SaaS, a fine-tuning service, a synthetic data vendor, a separate observability stack… all stitched together with brittle glue code and heroic architects.</p><p>The <strong>Generative AI OS</strong> is a response to that chaos.</p><p>It is not “yet another platform”.</p><p>It is the <strong>operating system</strong> that unifies the entire AI lifecycle — from <strong>creation to deployment to governance</strong> — into a single, coherent environment.</p><ul><li>It generates applications from natural language.</li><li>It orchestrates multi-agent systems.</li><li>It runs rigorous evaluations.</li><li>It optimizes inference cost and latency.</li><li>It enforces governance and compliance.</li><li>It produces synthetic data.</li><li>It integrates seamlessly with hybrid infrastructure.</li></ul><p>In short:</p><blockquote><strong><em>It is the universal AI control plane for the enterprise — the nervous system of an AI-native organization.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W59IWReQi1ATl25Oo7oOVA.jpeg" /><figcaption><strong>Enterprise Generative AI OS</strong></figcaption></figure><h3>1. The Core Philosophy: Dual Modality Architecture</h3><p>Most AI platforms are built for one persona: either the “prompt-only” business user <em>or</em> the deeply technical ML engineer.</p><p>A <strong>Generative AI OS</strong> is different. It is built on a <strong>Dual Modality Architecture</strong> that serves both:</p><ul><li>the <strong>architect</strong>, who needs precision, guardrails, and deep control, and</li><li>the <strong>dreamer</strong>, who wants to describe outcomes in plain language and see them materialize.</li></ul><h3>Modality 1: The Omni-Prompt Interface</h3><p>At the front door of the OS is a single, expressive text interface:</p><blockquote><em>“Build a sales intelligence agent that researches prospects, verifies contact information, drafts personalized outreach sequences, updates our CRM automatically, and generates weekly performance analytics with actionable insights.”</em></blockquote><p>From that one instruction, the OS doesn’t just generate code snippets. It produces <strong>full, production-grade artifacts</strong>:</p><ul><li>Frontend UI for internal users</li><li>Backend processing pipelines and APIs</li><li>Multi-agent orchestration workflows</li><li>Deployment configurations and runbooks</li><li>Evaluation suites and test harnesses</li><li>Observability and logging instrumentation</li></ul><p>This is <strong>text-to-everything</strong>: Natural language becomes executable infrastructure. Business requirements become deployed systems. Ideas go from concept to reality in <strong>minutes, not months</strong>.</p><h3>Modality 2: The Modular App Suite</h3><p>But architects and engineers still need to go deep.</p><p>The same OS exposes a <strong>Modular App Suite</strong> for fine-grained control:</p><ul><li>Adjust datasets, training strategies, and eval criteria</li><li>Fine-tune routing logic and decision trees</li><li>Build custom tools and integrations</li><li>Edit agent reasoning graphs and planning strategies</li><li>Configure compliance rules and policy enforcement</li><li>Optimize performance, cost, and latency characteristics</li></ul><p>The duality is deliberate:</p><blockquote><strong><em>The dreamer designs in natural language. The architect/engineer refines in modules. The OS reconciles both.</em></strong></blockquote><h3>2. The Unified Stack: Five Integrated Layers</h3><p>Today, most enterprises buy and wire together 8–10 tools to approximate an “AI stack.”<br> The Generative AI OS collapses that complexity into <strong>five deeply integrated layers</strong>.</p><h3>Layer 1 — Creation &amp; Generation Engine</h3><p><strong>Mission:</strong> Turn intent into working systems.</p><h4>Text-to-Application Engine</h4><p>You describe what you need — dashboards, internal tools, approval workflows, automation systems, microservices — and the OS generates:</p><ul><li>Modern, responsive frontends</li><li>Robust backend services and APIs</li><li>Database schemas and migration plans</li><li>AuthN/AuthZ and session flows</li><li>Agent orchestration logic</li><li>Deployment artifacts (manifests, configs, CI hooks)</li></ul><p>Crucially, it generates <strong>within your context</strong>: tech stack, security posture, coding standards, architectural principles.</p><h4>Visual Agent Workflow Builder</h4><p>For those who think in graphs, not prompts:</p><ul><li>Drag-and-drop nodes for RAG, tools, memory, human-in-the-loop, branching logic, multi-agent collaboration</li><li>An <strong>intelligent auto-wiring layer</strong> that can take a plain-English description of a workflow and design the orchestration graph for you</li></ul><h4>Enterprise Agent Template Library</h4><p>This layer ships with <strong>battle-tested templates</strong>, not toy examples:</p><ul><li>Customer Service Orchestration</li><li>Financial analysis and anomaly detection</li><li>Supply chain and logistics optimization</li><li>HR automation and employee service agents</li><li>Sales intelligence and pipeline agents</li></ul><p>Every template is fully customizable — via <strong>prompt</strong> or <strong>GUI</strong> — and ready to plug into enterprise systems.</p><h3>Layer 2 — Intelligence &amp; Data Foundation</h3><p><strong>Mission:</strong> Turn raw data and base models into <strong>enterprise intelligence</strong>.</p><h4>Synthetic Data Generation Suite</h4><p>Instead of sending data to third-party generators, the OS brings a synthetic data factory <strong>inside your perimeter</strong>:</p><ul><li>Structured tabular data that preserves distributions and correlations</li><li>Conversational transcripts for agent training</li><li>Financial and operational data with realistic patterns and edge cases</li><li>Healthcare-style or regulated data with privacy guardrails</li></ul><p>With built-in:</p><ul><li>Statistical fidelity checks</li><li>Privacy leakage scoring</li><li>Diversity and coverage analysis</li></ul><p>All of this happens within your security boundary — <strong>no data exfiltration</strong>.</p><h4>Comprehensive Fine-Tuning Studio</h4><p>Upload domain artifacts — policy docs, specs, tickets, chats, regulations — and convert a generic foundation model into your <strong>domain expert</strong>.</p><p>The studio supports:</p><ul><li>Full fine-tuning for maximum control</li><li>Parameter-efficient methods (LoRA, QLoRA) for rapid iteration</li><li>Prompt and adapter tuning for lightweight adaptation</li><li>RLHF / DPO / GRPO for preference-aligned behaviour</li></ul><p>Wrapped with enterprise-grade capabilities:</p><ul><li>Experiment tracking and reproducibility</li><li>Hyperparameter optimization</li><li>Cost estimation before you train</li><li>Private model registry with access control</li><li>Automatic model cards and documentation</li></ul><p>Fine-tuning ceases to be art; it becomes <strong>a governed process</strong>.</p><h4>RAG &amp; Knowledge Architecture</h4><p>The OS architects the <strong>AI-native knowledge layer</strong>:</p><ul><li>Vector search over documents, tickets, chats</li><li>Connectors into warehouses, lakes, and databases</li><li>Real-time streaming data as retrieval sources</li><li>APIs and microservices woven into retrieval and reasoning</li><li>Hybrid support — sensitive knowledge on-prem, scale in cloud</li></ul><p>This is not “just a vector DB.” It’s a <strong>first-class knowledge architecture</strong>.</p><h3>Layer 3 — Trust, Governance &amp; Compliance Foundation</h3><p><strong>Mission:</strong> Make “production AI” synonymous with <strong>responsible AI</strong>.</p><h4>Advanced Evaluation Framework</h4><p>Every model and agent is tested, continuously, across multiple dimensions:</p><ul><li>Hallucination detection and risk scoring</li><li>External fact verification and source attribution</li><li>Accuracy and semantic similarity measurement</li><li>Bias and representation analysis</li><li>Safety checks (toxicity, jailbreaks, prompt injection)</li><li>Domain-specific compliance checks</li></ul><p>Evaluations run:</p><ul><li>Pre-deployment (gates)</li><li>Post-deployment (continuous)</li><li>On every model, prompt, or config change</li></ul><p>Nothing goes live unless it <strong>passes thresholds you define.</strong></p><h4>Human-in-the-Loop (HIL) by Design</h4><p>For high-risk workflows, automation is never blind:</p><ul><li>Confidence-based routing: low-risk outputs auto-approve, high-risk outputs escalate</li><li>Role-based queues and SLAs</li><li>Batch review interfaces for legal, compliance, medical, financial, or critical decisions</li></ul><p>Agents pause; humans decide. And the OS tracks every decision for audit and learning.</p><h4>Enterprise Governance &amp; Privacy</h4><p>Governance is baked into the runtime:</p><ul><li>PII detection and redaction</li><li>Encryption at rest and in transit</li><li>Federated learning and differential privacy options</li><li>RBAC / ABAC for data, tools, and models</li><li>Full audit trails, lineage tracking, and change management</li><li>Model versioning, rollbacks, and regulatory reporting supports</li></ul><blockquote><strong><em>This is the difference between a demo and a deployment in a regulated industry.</em></strong></blockquote><h3>Layer 4 — Observability &amp; Intelligence Layer</h3><p><strong>Mission:</strong> Make AI systems observable like modern distributed systems — and then some.</p><h4>Deep Telemetry &amp; Tracing</h4><p>The OS tracks:</p><ul><li>Token usage and cost per app, team, region</li><li>Latency distribution and error rates</li><li>Model- and agent-level performance metrics</li><li>Multi-agent traces: who called what, when, and why</li><li>Tool invocations, API dependencies, DB query profiles</li></ul><p>You can <strong>replay any request</strong> end-to-end and analyze:</p><ul><li>The reasoning path</li><li>Tool choices and fallbacks</li><li>Retrieval quality</li><li>Confidence estimates and hallucination flags</li></ul><h4>Role-Specific Dashboards</h4><ul><li><strong>Executives</strong>: adoption, ROI, cost curves, risk posture</li><li><strong>Developers / MLOps</strong>: errors, performance, deployment status, regressions</li><li><strong>Business owners</strong>: workflow completion, SLA adherence, customer impact</li><li><strong>Compliance</strong>: audit trails, violation alerts, risk scores</li></ul><p>Transparency turns AI from a “black box” into an <strong>engineering discipline</strong>.</p><h3>Layer 5 — Infrastructure &amp; Deployment Foundation</h3><p><strong>Mission:</strong> Support AI everywhere — cloud, on-prem, edge — with a single control plane.</p><h4>Hybrid Deployment Architecture</h4><p>The OS can live:</p><ul><li>Fully <strong>on-prem</strong> (sovereign, air-gapped, regulated)</li><li>Fully <strong>cloud-native</strong> (managed scale, global reach)</li><li><strong>Hybrid</strong>, with sensitive data and models on-prem and heavy compute bursting to cloud</li></ul><p>One console manages it all. Workloads can move without application rewrites.</p><h4>Intelligent Cost &amp; Latency Optimization</h4><p>AI costs don’t have to spiral.</p><p>The OS optimizes at multiple levels:</p><ul><li><strong>Token level</strong>: prompt compression, context pruning, caching, streaming</li><li><strong>Model level</strong>: dynamic routing between small/medium/large models and providers</li><li><strong>Inference level</strong>: batching, quantization, speculative decoding, KV-cache reuse, GPU utilization optimization</li></ul><p>Real-world impact:</p><blockquote><em>40–60% cost reduction and 2–3× latency improvements are typical when optimization is treated as an architectural concern, not an afterthought.</em></blockquote><h3>3. A Day in the Life: Architecting in Hours, Not Quarters</h3><p>Consider Sarah, a Solutions Architect at a B2B SaaS company.</p><h3>9:00 AM — Business Problem</h3><p>The CEO asks for an <strong>intelligent customer support agent</strong>:</p><ul><li>Answers technical questions</li><li>Creates tickets in Jira</li><li>Escalates angry customers</li><li>Achieves 95% accuracy and strict hallucination control</li><li>Live by next week</li></ul><p>A month ago, this was a 2–3 month project.<br> With a Generative AI OS, Sarah can say: <strong>“Yes — this week.”</strong></p><h3>9:15 AM — Intent to System</h3><p>Sarah opens the Omni-Prompt Interface and describes the use case in one paragraph, attaching product PDFs.</p><p>The OS responds with:</p><ul><li>Architecture: RAG stack, agents, integrations</li><li>Email connector, Jira integration, escalation logic</li><li>Synthetic test suite (hundreds of scenarios)</li><li>Evaluation plan with metrics and thresholds</li></ul><p>The initial run yields:</p><ul><li>89% accuracy</li><li>12% hallucination rate</li><li>8.3s latency</li><li>$0.14 per request</li></ul><h3>10:00 AM — Targeted Refinement</h3><p>Sarah moves into the <strong>Modular App Suite</strong>:</p><ul><li>Uses the Evaluation dashboard to pinpoint hallucination scenarios</li><li>Uses the Fine-Tuning Studio with 50 curated examples</li><li>Edits the agent workflow to add <strong>knowledge boundaries</strong> and safe deferrals</li><li>Adjusts tone and persona</li></ul><p>By early afternoon:</p><ul><li>96% accuracy</li><li>4% hallucination rate</li><li>6.1s latency</li><li>$0.09 per request</li></ul><h3>3:00 PM — Governance-First Deployment</h3><p>She deploys in <strong>hybrid mode</strong>:</p><ul><li>Customer data stays on-prem</li><li>Inference via secure gateway</li><li>Auto-scaling, monitoring, alerts, and rollback plans configured</li><li>Audit trails and logs wired to compliance dashboards</li></ul><p>By 3:05 PM, the agent is live.<br>By the next day:</p><ul><li>127 inquiries handled</li><li>70% fully resolved by the agent</li><li>15 valid Jira bugs filed</li><li>4.3/5 customer satisfaction</li><li>Cost a fraction of manual support</li></ul><p>This is <strong>not</strong> a demo. It’s production-grade, governed, observable, and optimized — built in a single working day.</p><h3>4. Why This Architecture Matters for Enterprises</h3><h3>4.1 End of Tool Sprawl</h3><p><strong>Before:</strong></p><ul><li>10+ platforms: dev tools, workflow tools, metrics, eval, synthetic data, fine-tuning, governance…</li><li>Integration maintenance as a permanent tax</li></ul><p><strong>After:</strong></p><ul><li>One OS, with everything as a first-class capability</li><li>A <strong>coherent architecture</strong> instead of a “stack of vendors”</li></ul><h3>4.2 Time-to-Value Compression</h3><p><strong>Before:</strong> Months from concept to production</p><p><strong>After:</strong> Hours to days</p><p>This changes how you think about pilots, PoCs, and production.<br> PoCs become <strong>launch-able assets</strong>, not disposable experiments.</p><h3>4.3 Governance by Design</h3><p>Regulated industries can’t bolt on compliance later.</p><p>With the Generative AI OS:</p><ul><li>PII protection, audit trails, approvals, and policy enforcement are <strong>built into the execution path</strong></li><li>Model, data, and workflow changes are versioned, logged, and reviewable</li></ul><p>This is what allows <strong>financial services, healthcare, government, manufacturing, and legal</strong> to move beyond demos.</p><h3>4.4 Hybrid and Sovereign AI</h3><p>The OS is designed for a world where:</p><ul><li>Data residency, sovereignty, and regulation drive infrastructure choices</li><li>Some workloads belong in the cloud, others never leave the data center</li></ul><p>Hybrid stops being an exception; it becomes the <strong>default architecture</strong>.</p><h3>4.5 Cost as a First-Class Metric</h3><p>Instead of discovering spend at the end of the month, the OS puts:</p><ul><li>Cost per workflow, per team, per model</li><li>Optimization levers and routing strategies directly in the hands of architects and finance leaders.</li></ul><h3>5. Economics: From Fragmentation to Foundation</h3><p>In a typical large enterprise, fragmented AI tooling easily reaches <strong>multi-million-dollar annual TCO</strong> when you factor:</p><ul><li>Platform licenses for multiple vendors</li><li>Integration and maintenance effort</li><li>Training and onboarding costs</li><li>Security and compliance overhead</li><li>Redundant infrastructure and data storage</li></ul><p>A unified OS architecture often delivers:</p><ul><li>~<strong>68% reduction</strong> in three-year TCO</li><li><strong>85% faster</strong> time-to-production</li><li><strong>60% fewer</strong> security incidents</li><li><strong>10× developer productivity</strong> on AI workloads</li></ul><p>Not because it’s “cheaper software,” but because it <strong>removes friction at every layer</strong> of the AI lifecycle.</p><h3>6. Implementation Journey: From Pilot to Enterprise Nervous System</h3><p>A Generative AI OS isn’t “installed”; it’s <strong>adopted</strong> in phases.</p><h3>Phase 1 — Foundation (Weeks 1–4)</h3><ul><li>Deploy the OS (cloud / on-prem / hybrid)</li><li>Integrate identity (SSO, LDAP, AD) and network controls</li><li>Align stakeholders and select 2–3 high-value use cases</li><li>Stand up observability and basic governance</li></ul><h3>Phase 2 — Customization (Weeks 5–12)</h3><ul><li>Build domain-specific agents and workflows</li><li>Fine-tune models on internal data</li><li>Integrate core systems (CRM, ERP, knowledge bases)</li><li>Implement HIL for critical workflows</li><li>Begin cost and latency optimization</li></ul><h3>Phase 3 — Scale (Weeks 13–24)</h3><ul><li>Roll out to multiple business units</li><li>Create internal templates and reusable patterns</li><li>Establish a <strong>Center of Excellence</strong></li><li>Formalize best practices, guidelines, and internal training</li></ul><h3>Phase 4 — Continuous Optimization (Ongoing)</h3><ul><li>Improve models and workflows based on telemetry</li><li>Adopt new capabilities without architectural rewrites</li><li>Continuously tune cost, latency, and quality</li><li>Expand into new lines of business and geographies</li></ul><h3>7. Competitive Lens: Why Unified Architectures Win</h3><p>Compared to:</p><ul><li><strong>Code generation tools</strong>: Great for prototyping, poor for governance, deployment, and integration.</li><li><strong>Workflow automation platforms</strong>: Strong on integration, weak on AI-native reasoning and observability.</li><li><strong>Model training platforms</strong>: Excellent for ML teams, disconnected from end-to-end application lifecycle.</li><li><strong>Single-cloud AI services</strong>: Powerful but often lock you into one provider and make hybrid/sovereign strategies painful.</li><li><strong>Custom development</strong>: Max flexibility, but 6–18-month build times and high maintenance.</li></ul><p>The Generative AI OS offers:</p><blockquote><strong><em>A production-grade “operating system for intelligence” with speed, governance, hybrid flexibility, and extensibility built in.</em></strong></blockquote><h3>8. Future-Proofing: Designed to Evolve</h3><p>The AI landscape will not stand still. Your architecture must anticipate that.</p><ul><li><strong>Model-agnostic core</strong>: Commercial, open-source, custom, future architectures — all pluggable behind a stable abstraction.</li><li><strong>Plugin-ready</strong>: New tools, metrics, data sources, and providers can be added as plugins, not rewrites.</li><li><strong>API-first</strong>: Every capability accessible programmatically, so the OS can integrate into your existing ecosystem.</li><li><strong>Template marketplace &amp; standards</strong>: Portable workflows, agents, and evaluations via standard formats to avoid lock-in.</li><li><strong>Backward compatible evolution</strong>: New features arrive without breaking existing workloads.</li></ul><h3>9. Security &amp; Compliance: Non-Negotiable by Design</h3><p>Finally, no OS is credible without <strong>security as a core property</strong>:</p><ul><li>Encryption in transit and at rest</li><li>VPC, private endpoints, and zero-trust architectures</li><li>MFA, SSO, granular permissioning</li><li>SOC 2, ISO 27001, GDPR, HIPAA alignment (and beyond)</li><li>Deep audit logging, anomaly detection, and compliance dashboards</li></ul><p>This is what allows AI to move from “sandbox experiments” to <strong>core operational systems</strong>.</p><h3>10. The Architectural Shift: From Tools to an Operating System</h3><p>The old world:</p><ul><li>AI as a set of disconnected tools</li><li>Value gated by integration work, governance gaps, and team silos</li></ul><p>The new world:</p><ul><li>AI as a <strong>unified operating system</strong></li><li>A foundational layer that standardizes how you <strong>create, deploy, monitor, govern, and evolve</strong> intelligent systems</li></ul><blockquote><em>The Generative AI OS doesn’t replace your AI strategy.<br></em><strong><em>It makes your AI strategy executable.</em></strong></blockquote><p>From one agent to thousands.<br> From a single cloud to a hybrid estate.<br> From data generation to fine-tuning to evaluation and optimization.</p><p><strong>One platform. One control plane. Many possibilities.</strong></p><p>The fragmented stack era is ending.<br> The <strong>operating system era for enterprise AI</strong> has begun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27102b2b18ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Domain-Specific Foundational Sovereign SLMs]]></title>
            <link>https://sauravagarwaldigital.medium.com/building-domain-specific-foundational-sovereign-slms-bf8fe5251a81?source=rss-5dd9f45313ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8fe5251a81</guid>
            <dc:creator><![CDATA[Saurav Agarwal]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 07:37:59 GMT</pubDate>
            <atom:updated>2025-06-11T09:20:30.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TenaGMwI1oujiEXrr1cw6Q.png" /></figure><p>Large Language Models (LLMs) have revolutionized artificial intelligence, enhancing everything from conversational agents to advanced analytics. Yet, general-purpose LLMs — while powerful — pose significant challenges for domain-specific enterprise use cases, especially in regulated sectors like finance, healthcare, and legal industries. Concerns include high computational resource demands, regulatory compliance complexities, licensing limitations, and inadequate domain customization.</p><p><strong>Why Domain-Specific SLMs?</strong></p><p>Domain-specific Small (large) language models (SLMs) overcome several critical limitations of general-purpose LLMs:</p><p><strong>1. Regulatory Compliance:</strong> <br> General-purpose models often leverage web-scraped datasets with opaque provenance, raising serious compliance and ethical concerns. Domain-specific SLMs built with NeMo rely exclusively on transparently curated datasets that align strictly with regulatory frameworks such as GDPR, HIPAA, and data sovereignty laws prevalent in many jurisdictions.</p><p><strong>2. Enhanced Domain Customization:</strong> <br> SLMs specifically designed for niche sectors such as finance, healthcare, and law support specialized capabilities such as long-context understanding, multilingualism, multimodal inputs, and unique linguistic nuances, significantly surpassing general-purpose LLMs in domain benchmarks.</p><p><strong>3. Improved Performance:</strong> <br> Trained on carefully selected, domain-specific datasets, SLMs demonstrate superior accuracy, reduced latency, and better generalization, resulting in significantly improved user experiences and task outcomes within targeted industries.</p><p><strong>4. Resource Efficiency:</strong> <br> With reduced parameters, SLMs lower inference costs substantially. They allow deployment on enterprise GPU servers or even resource-limited edge devices like NVIDIA Jetson platforms, significantly enhancing cost-effectiveness and scalability.</p><p><strong>The SLM Development Lifecycle with NVIDIA NeMo FW</strong></p><p>NVIDIA NeMo Framework offers robust capabilities for SLM creation, including dataset management, scalable model training, alignment, and comprehensive evaluation. The following sections detail the structured SLM development process.</p><p><strong>Dataset Curation and Provenance</strong></p><p>The quality and relevance of training data are paramount for domain-specific SLMs. Using NVIDIA NeMo Curator, a powerful tool for scalable data processing, enterprises can curate high-quality datasets that align with Responsible AI principles, licensing requirements, and domain-specific needs. This section details the data curation pipeline for a domain-specific SLM, leveraging NeMo Curator on NVIDIA GPU clusters to process a diverse, multi-trillion-token dataset optimized for enterprise use cases like Finance/ Healthcare.</p><p>To understand the size of Pretraining dataset needed we can go through various research papers, one such example is to go through the benchmark numbers from DCLM <a href="https://nam11.safelinks.protection.outlook.com/?url=https%3A%2F%2Farxiv.org%2Fpdf%2F2406.11794&amp;data=05%7C02%7Csaurava%40nvidia.com%7C0f66fab4e40343f130ce08dcd7895086%7C43083d15727340c1b7db39efd9ccc17a%7C0%7C0%7C638622232020257621%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C0%7C%7C%7C&amp;sdata=E2wHfFh1c%2B7DUhDHj%2FNF5xB3hwxnqfOmdcN1CsCGcgw%3D&amp;reserved=0">paper</a> which provides key benchmark numbers and valuable details for curating datasets for Foundational models. e.g. for training and 2 B SLM, the curated dataset comprises of about 1.5 trillion tokens for pretraining, blending open-source, domain-specific, and proprietary data to ensure broad coverage and task-specific accuracy. The distribution includes:</p><p><strong>Generic Datasets (1.2T tokens)</strong>:</p><ul><li>Fineweb: 200B tokens (general English)</li><li>Multilingual (Hindi, Spanish, French): 600B tokens</li><li>Stack (Code): 300B tokens</li><li>OpenWebMath &amp; DeepMindMath: 50B tokens</li><li>Wiki: 5B tokens</li><li>Books (Fiction: 25B, Non-Fiction: 25B)</li><li>Cosmopedia-v2: 30B tokens</li><li>Arxiv: 30B tokens</li><li>StackExchange: 30B tokens</li></ul><p><strong>Domain-Specific Datasets (300B tokens)</strong>:</p><ul><li>DCLM (e.g. Domain): 250B tokens</li><li>Books-L: 37B tokens</li><li>Reddit: 10B tokens</li><li>Magpie: 3B tokens</li></ul><p><strong>Proprietary/ Synthetic Datasets (100 B tokens)</strong>: The dataset prioritizes permissively licensed, high-quality sources, with 80% open-source data and 20% domain-specific content. Proprietary data, taken from enterprise workflows and software can further add quality to the curated dataset.</p><p><strong>Multilingual data (100 B tokens) : </strong>For continuous pre — training, a strategy to use is 100B tokens (5% of the PT tokens) and train the model on the high quality dataset. For this we came up with Data composition as follows:</p><ol><li>Code+Math: For reasoning ability. This constitutes around 20–30%.</li><li>Multilingual Data: For multilingual abilities. This constitutes around 20–30%. (Sovereign Languages — e.g. Hindi, French, Bahasa)</li><li>Proprietary: Domain specific. 10%</li><li>Domain+ generic data: Remaining part of data. 30–50%. (Data Replay strategy for CPT)</li></ol><p><strong>Data Processing with NeMo Curator</strong></p><p>NeMo Curator’s scalable pipelines, powered by Dask-based jobs on NVIDIA GPU clusters, enable efficient data preprocessing and quality assurance. The dataset development process focuses on collecting high-quality, domain-relevant data while adhering to Responsible AI practices and licensing guidelines.</p><p><strong>Key Steps in Data Pre Processing:</strong></p><ol><li><strong>Deduplication</strong>: NeMo Curator removes redundant tokens, ensuring a lean and diverse dataset.</li><li><strong>Quality Classification</strong>: High-quality documents (e.g., from Arxiv, Domain Manuals) are prioritized for multiple training epochs, while low-quality tokens are used sparingly. Train a quality filter model with approximately 1,000 manually labelled examples using NeMo Curator categorizing data into high, medium, and low quality using classifiers.</li><li><strong>Domain-Specific Filtering</strong>: NeMo Curator extracts domain-relevant tokens from public datasets (e.g., DCLM) and proprietary sources, enhancing model performance on industry-specific tasks. High-quality and domain-specific documents are classified from the existing corpus of downloaded data, including publicly available, permissively licensed language and code datasets.</li><li><strong>Synthetic Data Generation : </strong>To address gaps in domain-specific data, NeMo Curator integrates innovative synthetic data generation techniques:</li></ol><p><strong>NemotronGenerator</strong>: Generates sophisticated synthetic datasets, including domain-specific dialogues, mathematical problems, programming challenges, and scenario-based conversations, significantly enhancing dataset richness and relevance.</p><p><strong>Proprietary Data Enhancement</strong>: <a href="https://github.com/sauravdev/NeMo-Curator/blob/sauravdev-patch-1/tutorials/SDG.ipynb">Generate</a> synthetic domain data using NVIDIA’s Nemotron model via an asynchronous OpenAI client. It creates subtopics, paragraphs, sections, and a tutorial based on a main topic, saving the output in a JSONL file, with features for parallel processing and token counting.</p><p>To learn more about Nemo Curators, below are some useful resources:</p><ul><li><a href="https://github.com/NVIDIA/NeMo-Curator?tab=readme-ov-file#get-started">Nemo Curator Git page with getting started steps</a></li><li><a href="https://github.com/NVIDIA/NeMo-Curator/tree/main/examples/slurm">Example script to use SLURM</a></li><li><a href="https://docs.nvidia.com/nemo-framework/user-guide/latest/datacuration/index.html">Curator documentation</a></li></ul><p><strong>Model Architecture Selection and Pretraining</strong></p><p>The model training process follows an autoregressive language modeling approach with an initial context length of 8k, leveraging Flash Attention for efficiency. Training is conducted on a distributed multi-GPU setup using the NVIDIA Nemo framework, with mixed-precision training, regular checkpoints.</p><ul><li><strong>Multi-Head Attention (MHA) vs. Grouped Query Attention (GQA)</strong>: GQA is preferred for better efficiency and scalability, especially for long-context models, due to its balance between accuracy and performance.</li><li><strong>Rotary Position Embedding (RoPE)</strong>: Used for positional encoding, starting with an 8k context length to allow future extension to 32k+ without retraining. Extends the context length to 32k to improve coherence and relevance for enterprise applications, leveraging 100 billion tokens from high-quality datasets.</li><li><strong>Model Selection</strong>: Scaling down a large model (e.g., LLaMA 3 8B to 2B) is favored for efficiency, as LlaMA models are state of the art and thoroughly tested.</li></ul><p>Training Llama 3 Foundational model documentation <a href="https://docs.nvidia.com/nemo-framework/user-guide/25.02/llms/llama3.html">here</a></p><p><strong>Training a Custom Tokenizer</strong></p><p>Tokenization is a pivotal step in developing domain-specific SLMs, enabling efficient text processing for enterprise applications. Using the SentencePiece library and NVIDIA NeMo, enterprises can craft custom tokenizers and train high-performance LLMs tailored to domains.</p><p>The tokenizer was trained using SentencePiece’s Byte-Pair Encoding (BPE), with a 64,000-token vocabulary optimized for multilingual (Hindi, French, Spanish) and domain-specific (e.g., finance) contexts. Key features include extensive special tokens for extensibility, high character coverage (0.9995), support for long contexts (up to 65,535 bytes), robust handling of code and mathematical content, and reserved tokens allowing future enhancements.</p><p>Refer to the Nemo tokernizer training procedure <a href="https://docs.nvidia.com/nemo-framework/user-guide/24.07/llms/tokenizer/sentencepiece/train.html#training-the-tokenizer">here</a>.</p><p><strong>Training Approach &amp; Optimization</strong></p><p>A three-phase approach, is followed:</p><ol><li><strong>Phase 1: Broad Coverage : </strong>General English and multilingual data (e.g., Fineweb, Multilingual) establish foundational knowledge with less emphasis on quality. Pretraining runs for a single epoch.</li><li><strong>Phase 2: High-Quality Focus : </strong>High-quality subsets (e.g., Arxiv, Cosmopedia-v2) are prioritized for multiple epochs to refine model performance.</li><li><strong>Phase 3: Domain-Specific Adaptation: </strong>Domain-specific data (e.g., DCLM, Domain corpus) is introduced using NeMo Curator’s filters to ensure relevance.Domain-specific variants are created through continual pretraining.Each stage of continual pretraining uses standard recipes, mixing long-context and domain-specific data with a small portion of earlier pretraining data. Documentation <a href="https://docs.nvidia.com/nemo-framework/user-guide/24.09/longcontext/index.html">here</a></li></ol><p><strong>Scaling Model Architectures with Parallelism</strong></p><p>For larger models or those handling extended context lengths (e.g., 32k tokens), NeMo FW implements tensor parallelism, pipeline parallelism, or context parallelism. Tensor parallelism splits model weights and computations across GPUs, reducing memory demands per device. Pipeline parallelism divides the model layers across GPUs, enabling efficient processing of deep architectures. Context parallelism, specifically recommended for long-context models, optimizes activation memory management, ensuring stability during training.</p><p><strong>Resource Orchestration and Batch Size Optimization</strong></p><p>NeMo integrates with Kubernetes and SLURM to orchestrate GPU clusters, dynamically allocating resources to avoid memory bottlenecks and ensure high throughput.</p><p>To maintain training efficiency, NeMo targets a global batch size of 4–6 million tokens, sharded appropriately across multiple GPUs to balance memory usage and computational efficiency. The optimal per-GPU batch size typically ranges between 512 and 1024 tokens, depending on the cluster size.</p><p><strong>Data Quality and Epoch Strategy</strong></p><p>The training schedule prioritizes high-quality data to enhance model performance. High-quality datasets, such as curated financial corpora or proprietary enterprise data, are processed over multiple epochs, allowing the model to deeply learn domain-specific patterns. In contrast, low-quality data, such as noisy web-scraped content, is limited to a single epoch to prevent overfitting to irrelevant patterns. This selective epoch strategy, facilitated by NeMo’s data pipelines, optimizes the model’s ability to generalize across tasks.</p><p><strong>Hyperparameter Tuning and Ablation Studies</strong></p><p>Fine-tuning hyperparameters is essential for optimal performance. NeMo adjusts the learning rate using a cosine annealing schedule, starting with a higher rate (e.g., max_lr = 1e-5) than the final rate observed during pretraining (e.g., min_lr = 5e-7). This approach balances rapid convergence with stability, ensuring the model adapts effectively to domain-specific tasks.</p><p>To determine the ideal mix of data quality levels before scaling to larger models, ablation studies on smaller LLMs (less than 1 billion parameters) can be done. These studies evaluate the impact of data quality on downstream task performance, providing insights into the optimal dataset composition for enterprise use cases.</p><p><strong>Efficient Scaling with Mixed-Precision Training</strong></p><p>NeMo’s mixed-precision training significantly reduces memory footprints, enabling the pretraining of billion-parameter models. By combining 16-bit floating-point computations with tensor parallelism, NeMo minimizes memory usage while maintaining numerical stability.</p><p><strong>Instruction Tuning for Downstream Alignment</strong></p><p>After pretraining, NeMo’s Aligner toolkit facilitates instruction tuning to align the model with specific downstream use cases, such as chatbots or agent integrations. This process refines the model’s behavior, ensuring it delivers accurate, contextually appropriate responses in enterprise workflows. NeMo’s instruction tuning pipelines is utilised to perform supervised fine-tuning enabling precise alignment with domain preference data.</p><p><strong>Model Evaluation Harness</strong></p><p>We carried out a comprehensive evaluation procedure based on the <a href="https://github.com/EleutherAI/lm-evaluation-harness">lm-evaluation-harness</a> to rigorously test our model against various open-sourced models available with permissible licenses. The evaluation covered a diverse set of benchmarks to assess performance across multiple dimensions.</p><p><strong>Benchmark Categories</strong></p><ul><li>Utilizing the <a href="https://github.com/EleutherAI/lm-evaluation-harness">lm-evaluation-harness</a> framework, NeMo rigorously assesses SLM performance across diverse benchmarks:</li><li>General linguistic and comprehension benchmarks</li><li>Code generation accuracy</li><li>Multilingual linguistic benchmarks</li><li>Long-context coherence evaluation</li><li>Domain-specific task precision</li><li>Proprietary enterprise benchmarks assessing industry-relevant scenarios</li></ul><p>This extensive evaluation ensures robust, validated SLM performance tailored precisely to enterprise needs.</p><p><strong>Conclusion</strong></p><p>Through meticulous dataset curation, advanced synthetic data generation, precise model architecture selections, efficient training optimization, tokenizer customization, alignment tuning, and rigorous evaluation, enterprises can develop sovereign SLMs tailored specifically to their unique regulatory, linguistic, and computational requirements. These tailored models empower enterprises, driving significant innovation, compliance, performance, and efficiency gains in specialized AI applications across sensitive and regulated industries.</p><p>Thanks to <a href="https://medium.com/u/951776c7edd">HEMANT GIRI</a> , <a href="https://medium.com/u/6de6d85a1285">Vishwas Pai</a> and <a href="https://medium.com/u/a04061482797">Mitra Rath</a> for contribution on this blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8fe5251a81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accelerating MLOps with the power of GPUs]]></title>
            <link>https://sauravagarwaldigital.medium.com/accelerating-mlops-with-the-power-of-gpus-a3f56e994d3?source=rss-5dd9f45313ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3f56e994d3</guid>
            <dc:creator><![CDATA[Saurav Agarwal]]></dc:creator>
            <pubDate>Fri, 18 Feb 2022 11:26:06 GMT</pubDate>
            <atom:updated>2022-02-18T11:26:06.180Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://en.wikipedia.org/wiki/MLOps">MLOps</a> at a glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*LO4aQw2GJM4Al3-M.png" /></figure><p>Source: <a href="https://blogs.nvidia.com/blog/2020/09/03/what-is-mlops/">https://blogs.nvidia.com/blog/2020/09/03/what-is-mlops/</a></p><p>MLOps is a set of practices that aims to deploy and maintain machine learning models in production reliably and efficiently. The word is a compound of “machine learning” and the continuous development practice of DevOps in the software field.</p><h3><a href="https://cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning#devops_versus_mlops">DevOps vs MLOps</a></h3><p>ML Systems differ from conventional Software Solutions in the following ways:</p><ul><li>CI is no longer only about testing and validating code and components, but also testing and validating data, data schemas, and models.</li><li>CD is no longer about a single software package or a service, but a system (an ML training pipeline) that should automatically deploy another service (model prediction service).</li><li>CT is a new property, unique to ML systems, that’s concerned with automatically retraining and serving the models.</li></ul><h3>Benchmarking</h3><p>To start with we created two notebooks, one with CPU support &amp; another with GPU support; having the entire Data Science Pipeline merged into a single Notebook. Based on the respective notebook run, we found the stats listed below comparing CPU vs GPU performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dPYZMwQc3-cJS--d.png" /></figure><p>NYC Taxi Fare Prediction Pipeline Times, CPU vs GPU</p><p>The GPU wipes the floor with the CPU in this Pipeline Runtime Test. The CPU took over 5 hours for a task that the GPU finished in just over a minute, a whopping <strong>267 times faster</strong>. This is the best case scenario for the CPU as the multithreading was utilized for both Data Wrangling &amp; Training. A Data Scientist’s work majorly consists of experimenting with data, features &amp; parameters. <strong>Such speedups in development can be the deciding factor in getting your product to the market before your competitor.</strong></p><p>Machine : NC24rs_v3 (24 vcpus, 448 GB RAM, 4 × NVIDIA Tesla V100)</p><p>Data : <a href="https://www.kaggle.com/c/new-york-city-taxi-fare-prediction/data">https://www.kaggle.com/c/new-york-city-taxi-fare-prediction/data</a></p><p>Code : <a href="https://github.com/rppol/MLOps_GPU/tree/main/notebooks">https://github.com/rppol/MLOps_GPU/tree/main/notebooks</a></p><h3>Hands On MLOps Implementation</h3><p>Based on the above notebooks we will now showcase how can we implement MLOps lifecycle for our Data Science Pipeline.</p><p>We’ll be using <a href="https://rapids.ai/start.html">Rapids</a> &amp; <a href="https://dask.org/">Dask</a> here, for GPU based Data Wrangling &amp; Training. <a href="https://www.jenkins.io/">Jenkins</a> will be used for CI/CD pipelines &amp; <a href="https://mlflow.org/">MLflow</a> for Model Tracking.</p><p>Ideally there must be separate servers for Development &amp; Production but here we’ll use the same server for everything.</p><p>Basic knowledge of Linux &amp; Python is required.</p><h3>Environment Setup</h3><p>You will need an Nvidia GPU equipped machine for this which satisfies these <a href="https://rapids.ai/start.html">prerequisites</a>. I’ve used the NC24rs_v3 VM with Ubuntu 20.04 on Azure.</p><ol><li><a href="https://docs.microsoft.com/en-us/azure/virtual-machines/linux/quick-create-portal">Setup VM &amp; SSH into it</a></li><li><a href="https://docs.microsoft.com/en-us/azure/virtual-machines/linux/n-series-driver-setup">Install Nvidia Drivers</a></li><li><a href="https://docs.docker.com/engine/install/ubuntu/">Install Docker</a></li><li><a href="https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html#docker">Install Nvidia Container Toolkit</a></li><li><a href="http://set%20up%20git%20%26%20configure%20git/">Install &amp; Configure Git</a></li><li><a href="https://www.jenkins.io/doc/book/installing/linux/">Install &amp; Start Jenkins</a></li><li>Install &amp; Set up Conda for Jenkins with these steps :</li></ol><p>8. Build Directory Structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/0*du1W0X1SoV53vX86.png" /></figure><ul><li>Triton Inference Server Directory</li><li>Data Directory</li></ul><p>Ideally in production systems there will be an API feeding data constantly and one should use tools like <a href="https://dvc.org/">dvc</a> for version control. Here we will be using static data from <a href="https://www.kaggle.com/c/new-york-city-taxi-fare-prediction/data">New York City Taxi Fare Prediction</a> competition. The training file is split in a ratio of 9:1 as train.csv &amp; test.csv respectively. Use the script below to download these from Google Drive (~5GB).</p><p>10. Install &amp; Setup <a href="https://developer.nvidia.com/nvidia-triton-inference-server">Triton Inference Server</a></p><p>We’re developing an XGBoost model. Triton has a <a href="https://github.com/triton-inference-server/fil_backend">FIL Backend</a> built with RAPIDS <a href="https://medium.com/rapids-ai/rapids-forest-inference-library-prediction-at-100-million-rows-per-second-19558890bc35">Forest Inference Library</a> for fast GPU-based inference.</p><p>11. Open ports on VM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/0*8ckfvbvjNFzjFAlq.png" /></figure><h3><a href="https://github.com/rppol/MLOps_GPU">Code</a></h3><p><strong>GitHub Repository: </strong><a href="https://github.com/rppol/MLOps_GPU"><strong>https://github.com/rppol/MLOps_GPU</strong></a></p><p>Structure:</p><ol><li><a href="https://github.com/rppol/MLOps_GPU/tree/main/notebooks">notebooks</a> : These notebooks aren’t for deployment, as they are for performance benchmarking &amp; experimentation.</li></ol><ul><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/notebooks/nyc-taxi-fare-cpu.ipynb">nyc-taxi-fare-cpu.ipynb</a> : An intuitive CPU only notebook built with pandas (Data Wrangling), modin (multithreading), XGBoost (all core training).</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/notebooks/nyc-taxi-fare-gpu.ipynb">nyc-taxi-fare-gpu.ipynb</a> : An intuitive GPU only notebook built with dask_cudf (Data Wrangling), xgboost.dask (distributed GPU based training).</li></ul><p>2. <a href="https://github.com/rppol/MLOps_GPU/tree/main/src">src</a> : This folder contains all the source files. We have modularized above notebook to make it easy to configure for MLOps deployment. Every major function is split into intuitively named python scripts. Every script supports independent execution.</p><ul><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/src/read_params.py">read_params.py</a> : Changing hardcoded values can be very annoying &amp; prone to errors. This python script builds a helper functions to read <a href="https://github.com/rppol/MLOps_GPU/blob/main/params.yaml">params.yaml</a> file, i.e. a one stop destination to modify parameters.</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/src/dask_client.py">dask_client.py</a> : Builds the Dask Client, this client is carried through the scripts as creating a new one takes time. Maximum allocated GPU Memory must be specified in the <a href="https://github.com/rppol/MLOps_GPU/blob/main/params.yaml">params.yaml</a> file.</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/src/load_data.py">load_data.py</a> : Helps in loading both Training &amp; Test data in GPU Memory. Uses dask_cudf to speed up &amp; distribute reading. “test” parameter must be set to true for reading test data. Relative path to the data directory &amp; file names must be provided in the <a href="https://github.com/rppol/MLOps_GPU/blob/main/params.yaml">params.yaml</a> file.</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/src/feature_engg.py">feature_engg.py</a> : This is a Data Cleaning, Manipulation &amp; Feature Addition script. It removes outliers and unreasonable data and adds interesting features like distance to various landmarks.</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/src/split_data.py">split_data.py</a> : Splits the data as training &amp; validation scripts. The split ratio can be varied using <a href="https://github.com/rppol/MLOps_GPU/blob/main/params.yaml">params.yaml</a> file.</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/src/generate_Dmatrix.py">generate_Dmatrix.py</a> : Converts data to a format XGBoost can handle.</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/src/train.py">train.py</a> : Training script for local use &amp; troubleshooting. This isn’t used in the automated pipeline.</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/src/train_with_tracking.py">train_with_tracking.py</a> : Model training script with MLflow tracking. MLflow server must be running before execution of this script. It tracks all the parameters &amp; model built. It also tests the model on unseen data, and tracks metrics. Visit <a href="https://towardsdatascience.com/xgboost-fine-tune-and-optimize-your-model-23d996fab663">this</a> for a guide on fine tuning XGBoost models.</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/src/log_production_model.py">log_production_model.py</a> : This script finds the best model out of all versions by comparing rmse. It loads, converts &amp; saves this model in production model folder for further processing.</li></ul><p>3. <a href="https://github.com/rppol/MLOps_GPU/tree/main/test">test</a> : Holds testing python scripts for both model &amp; server.</p><ul><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/test/test_and_evaluate.py">test_and_evaluate.py</a> : Generates predictions on unseen data &amp; compares with actual values. Generates metrics like Root Mean Squared Error, Mean Absolute Error, R-squared Error. Model can be passed as an argument or it’s loaded from production_model directory.</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/test/triton_inference_test.py">triton_inference_test.py</a> : Tests if Triton Server is working or not with 1% data. Uses grpc for networking.</li></ul><p>4. <a href="https://github.com/rppol/MLOps_GPU/tree/main/scripts">scripts</a> : Contains shell scripts executed by Jenkins.</p><ul><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/scripts/train_test_log.sh">train_test_log.sh</a> : Trains, Tests &amp; Logs new model.</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/scripts/Productionize.sh">Productionize.sh</a> : Gets best Model &amp; copies it to Model Repository.</li><li><a href="https://github.com/rppol/MLOps_GPU/blob/main/scripts/triton_test.sh">triton_test.sh</a> : Tests Triton after new model is loaded.</li></ul><p>5. artifacts : Stores models in MLflow format.</p><p>6. <a href="https://github.com/rppol/MLOps_GPU/blob/main/Jenkinsfile">Jenkinsfile</a> : Describes CI/CD Pipeline.</p><p>7. <a href="https://github.com/rppol/MLOps_GPU/blob/main/params.yaml">params.yaml</a> : One stop Destination to control everything, stores configuration, parameters, path, ip, ports.</p><h3>Building CI/CD Pipeline</h3><ol><li>Fork <a href="https://github.com/rppol/MLOps_GPU">https://github.com/rppol/MLOps_GPU</a></li><li>Log into Jenkins ( your_public_ip_here:8080 )</li></ol><p>Username : admin</p><p>Password can be found using the following command :</p><p>3. Add your GitHub credentials</p><p>4. Click New Item</p><p>5. Choose Pipeline, Enter a valid Name &amp; click OK</p><p>6. Choose “Do not allow concurrent builds” as a single build consumes all GPU resources</p><p>7. Scroll down to Pipeline &amp; choose following options :</p><ul><li>Enter your repository’s URL</li><li>Attach your GitHub credentials created in Step 2</li><li>Choose main branch</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kwQSS-MPRafWp2VQ.png" /></figure><p>8. Click Apply &amp; Save</p><p>This pipeline can be configured to build periodically or trigger builds after actions like git push &amp; availability of new data. To keep things simple, we’ll trigger it manually.</p><h3>Running CI/CD Pipeline &amp; Deployment</h3><ol><li><strong>Make sure Jenkins, MLflow Server &amp; Triton are running</strong></li></ol><p>2. Servers can be accessed here :</p><ul><li>Jenkins : your_ip_here:8080</li><li>JupyterLab : your_ip_here:9999/lab?</li><li>MLflow : your_ip_here:8003</li><li>Triton Inference Server : your_ip_here:8001</li><li>Triton Metrics : your_ip_here:8002</li></ul><p><strong>3. Executing Pipeline</strong></p><ul><li>Go to : your_ip_here:8080/job/your_pipeline_name/</li><li>Hit Build Now to start execution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*OpdAtuIwl4RiO6ys.png" /></figure><p>Jenkins Pipelines</p><ul><li>Hover over each stage to check logs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t97sy8NBAErhRYAS.png" /></figure><p>Console Output of train_test_log.sh in Build &amp; Test Model Stage</p><p><strong>4. MLflow Tracking</strong></p><ul><li>Each Pipeline Build generates a new model &amp; MLflow provides an intuitive UI to monitor everything.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0yzo30hmZNmcM2CB.png" /></figure><p>MLflow experiments</p><ul><li>Select two or more runs and click compare to compare them</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rmKsLtb-Rm3hInZx.png" /></figure><p>Model Comparison in MLflow</p><h3>Tuning Hyper Parameters</h3><ul><li>Go to : your_ip_here:9999/lab?</li><li>Edit the values in params.yaml to your heart’s content</li><li>Visit <a href="https://towardsdatascience.com/xgboost-fine-tune-and-optimize-your-model-23d996fab663">this</a> to tune hyperparameters like a pro</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/0*nydXGVMzqeZ-wEXL.png" /></figure><p>params.yaml</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k28si2LKvx9OTHNC.png" /></figure><p>Through the above demonstration, it is now evident that the MLOps pipeline can be completely accelerated on GPUs. The GPU VM costs 1.8× the CPU VM but with an acceleration of around <strong>267×</strong>, it pays for itself.</p><p>Data Scientists can spend more time on Model Optimization &amp; Tuning rather than Deployment &amp; waiting while the CPU crunches number one by one.</p><p><strong>LinkedIn : </strong><a href="https://www.linkedin.com/in/rutikpol/"><strong>https://www.linkedin.com/in/rutikpol/</strong></a></p><h3>References</h3><ul><li>Data : <a href="https://www.kaggle.com/c/new-york-city-taxi-fare-prediction/data">https://www.kaggle.com/c/new-york-city-taxi-fare-prediction/data</a></li><li>Code : <a href="https://towardsdatascience.com/nyc-taxi-fare-prediction-605159aa9c24">https://towardsdatascience.com/nyc-taxi-fare-prediction-605159aa9c24</a></li><li>General Intuition : <a href="https://cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning">https://cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning</a></li><li>Similar Video Tutorial : <a href="https://youtube.com/playlist?list=PLZoTAELRMXVOk1pRcOCaG5xtXxgMalpIe">https://youtube.com/playlist?list=PLZoTAELRMXVOk1pRcOCaG5xtXxgMalpIe</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3f56e994d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Data Science using NVTabular on Spark & Dask]]></title>
            <link>https://sauravagarwaldigital.medium.com/distributed-data-science-using-nvtabular-on-spark-dask-b25e11752207?source=rss-5dd9f45313ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/b25e11752207</guid>
            <dc:creator><![CDATA[Saurav Agarwal]]></dc:creator>
            <pubDate>Fri, 18 Feb 2022 11:24:32 GMT</pubDate>
            <atom:updated>2022-02-18T11:24:32.382Z</atom:updated>
            <content:encoded><![CDATA[<h3>NVTabular — Why, What, and How?</h3><p>W<strong>hy?</strong> Around 75–80% of the time is spent on ETL and feature engineering tasks by Data Engineers/AI practitioners instead of model building or fine-tuning of hyperparameters. With Big Data in Deep Learning-based systems, we experience performance bottlenecks majorly due to the following:</p><ul><li>Data ETL (extract-transform-load) takes a substantial quantity of time,</li><li>Feature engineering investigations create and evaluate several groups of new features from existing ones for their efficacies,</li><li>If not well optimized, data loading can become the input bottleneck at train time, which leads to wastage of high-throughput GPU computing,</li><li>Comprehensive repeated experimentation for model selection or tuning of hyperparameters.</li></ul><p>For training and deployment models on GPUs, the primary objective of NVTabular is simplifying and accelerating the tabular-data processing pipeline.</p><p>W<strong>hat? </strong>It is a collection of high-speed operators, on-GPU preprocessing, and feature engineering of tabular data with the capability of handling terabyte-scale datasets. The output can be made available to training frameworks such as HugeCTR, PyTorch, or TensorFlow at high throughput using NVTabular data loader extensions, eliminating the input bottleneck commonly found in GPU system training.</p><p>NVTabular focuses on the data preparation and data-loading phase. Here’s a common recommender system pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bvPh8Nli18CO2doB.png" /></figure><p>Recommender system training pipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/0*qHjSOsqKlDzR9SOq.png" /></figure><p>Position compared to other popular DataFrame libraries</p><p><strong><em>Features of NVTabular</em></strong></p><ul><li>Fast Data loading, Preprocessing, and Feature Engineering</li><li>Eliminating CPU bottlenecks by using GPU-acceleration</li><li>Execution is done Out-of-core. No GPU memory limits and reduced I/O through lazy execution.</li><li>Pytorch, TensorFlow, and HugeCTR compatible.</li><li>Missing values or outliers can be filtered out.</li><li>Inputting and filling in missing data.</li><li>Discretization or bucketing of continuous features.</li><li>Creating features by splitting or combining existing features.</li><li>Normalizing numerical features to have zero mean and unit variance.</li><li>Encoding discrete features using one-hot vectors or converting them to continuous integer indices.</li><li>More features are added continuously.</li></ul><p>To know more click <a href="https://github.com/NVIDIA/NVTabular">here</a></p><p><strong><em>NVTabular Vs CuDF, Pandas, Spark3</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nRQximE9XXzyJ3zY.png" /></figure><p>Feature comparison of NVT Vs Others</p><p>The three main advantages of NVTabular are:</p><ul><li><strong>Performance:</strong> Up to 10x performance improvement is done by Lazy execution and GPU acceleration.</li><li><strong>Scale:</strong> Dataset operations can scale beyond GPU/CPU memory.</li><li><strong>Usability:</strong> To accomplish the same processing pipeline, fewer API calls are required.</li></ul><p>H<strong>ow? </strong>The steps we need to follow to use NVT are given below along with the generic code:</p><ul><li>Specifying continuous and categorical columns.</li><li>Defining an NVTabular workflow and supplying a set of train and validation files.</li><li>Add preprocessing operations to the workflow.</li><li>Executing by saving the processed data to disk.</li></ul><pre>import nvtabular as nvt<br>import glob# specify continuous feature names<br>cont_names = [&quot;I&quot;+str(x) for x in range(1, 14)]# specify categorical feature names<br>cat_names = [&quot;C&quot;+str(x) for x in range(1, 27)]# specify target feature<br>label_names = [&quot;label&quot;]# all feature names<br>columns = label_names + cat_names + cont_names# initialize workflow<br>proc = nvt.Worfklow(cat_names=cat_names, cont_names=cont_names, label_name=label_names)# create datsets from input files<br>train_files = glob.glob(&quot;./dataset/train/*.parquet&quot;)<br>valid_files = glob.glob(&quot;./dataset/valid/*.parquet&quot;)<br>train_dataset = nvt.dataset(train_files, gpu_memory_frac=0.1)<br>valid_dataset = nvt.dataset(valid_files, gpu_memory_frac=0.1)# add feature engineering and preprocessing ops to workflow<br>proc.add_cont_feature([nvt.ops.ZeroFill(), nvt.ops.LogOp()])<br>proc.add_cont_preprocess(nvt.ops.Normalize())<br>proc.add_cat_preprocess(nvt.ops.Categorify(use_frequency=True, freq_threshold=15))# compute statistics, transform data, export to disk<br>proc.apply(train_dataset, shuffle=True,    output_path=&quot;./processed_data/train&quot;, num_out_files=len(train_files))proc.apply(valid_dataset, shuffle=False, output_path=&quot;./processed_data/valid&quot;, num_out_files=len(valid_files)</pre><h3>How to run multi-node NVTabular preprocessing using DASK</h3><p>A combination of the scheduler, workers, and clients is called the Dask cluster which enables distributed execution of Python functions. Dask enables easily scheduled tasks for multiple workers: multi-GPU or multi-node. We just need to initialize a Dask cluster (Like LocalCUDACluster) and NVTabular will use the cluster to execute the predefined workflow. Dask enables us to build up a graph of the computation that we want to perform and then executes it in parallel.</p><p>We start a cluster to enable distributed parallelism and connect to it to run the application by following the below steps:</p><ol><li>At first, we start dask-scheduler.</li><li>Second start the workers dask-cuda-worker schedulerIP:schedulerPort.</li><li>Finally, run the NVTabular application where the NVTabular Workflow has been initialized as described in the Multi-GPU Support section.</li></ol><p>For Example: Perform SSH on a list of machines and set up a Dask cluster. We can make use of all three remote machines as workers as the scheduler will likely use far fewer resources.</p><pre>import nvtabular as nvt<br>from dask.distributed import SSHCluster, Client</pre><pre>cluster = SSHCluster([&quot;localhost&quot;, &quot;MachineA&quot;, &quot;MachineB&quot;, &quot;MachineC&quot;])<br>client = Client(cluster)<br>workflow = nvt.Workflow(features, client=client)</pre><p>Other ways to deploy a “cluster” for Dask can be found in this <a href="https://blog.dask.org/2020/07/23/current-state-of-distributed-dask-clusters">article</a>. The dask_cuda.LocalCUDACluster API is typically used for a single machine with multiple GPUs.</p><h3>How to load data into DL libraries using various data loaders of NVTabular</h3><p>The data loading process while training pipelines with TensorFlow/PyTorch is another bottleneck in deep learning recommender systems. GPU doesn’t get fully utilized as the data loader is comparatively much slower in preparing the next batch. With NVTabular highly customized tabular data loader, for accelerating existing pipelines in TensorFlow, a speed-up by 9x is observed experimentally.</p><p>The main features of the data loader are:</p><ul><li>removal of the item-by-item data loading bottleneck</li><li>asynchronously read data in batches directly into GPU memory instead of CPU-GPU communication</li><li>Horovod multi-GPU training support</li></ul><h3>Use NVTabular data loader with TensorFlow Keras</h3><pre>import os<br>import glob# Set input data folder path<br>INPUT_DIR = os.environ.get(<br>    &quot;INPUT_DATA_DIR&quot;, os.path.expanduser(&quot;~/project/data/&quot;)<br>)# Define glob parquet data path<br>TRAINING_PATHS = sorted(glob.glob(os.path.join(INPUT_DIR,&quot;train/*.parquet&quot;)))</pre><p>The <a href="https://github.com/NVIDIA/NVTabular/blob/9aa70caa1dfb5d2fd694cad535def1e470d37b29/nvtabular/loader/tensorflow.py#L89">KerasSequenceLoader</a> manages to shuffle by loading in chunks of data from different parts of the full dataset, concatenating them, and then shuffling, then iterating through this super-chunk sequentially in batches.</p><p>More information is given in this <a href="https://medium.com/nvidia-merlin/training-deep-learning-based-recommender-systems-9x-faster-with-tensorflow-cc5a2572ea49">blogpost</a>.</p><pre>from nvtabular.loader.tensorflow import KerasSequenceLoader# Load data using tensorflow keras <br>train_tf = KerasSequenceLoader(<br>    TRAINING_PATHS,<br>    batch_size=BATCH_SIZE,<br>    label_names=LABEL_COLUMN,<br>    cat_names=CATEGORICAL_COLUMNS,<br>    cont_names=NUMERIC_COLUMNS,<br>    engine=&quot;parquet&quot;, # specifying the type of read engine to use<br>    shuffle=True,     # whether to shuffle chunks of batches<br>    buffer_size=0.06, <em># </em>(0,1), fraction of total GPU mem to occupy<br>    parts_per_chunk=1,# Dataset partitions to load and concatenate<br>)</pre><p>Similar to training(train_df) we can load the validation/test dataset.</p><h3>Use NVTabular data loader with PyTorch</h3><p>TorchAsyncItr class creates batches of tensors. Each batch size is specified by the user. The data input requires an NVTabular dataset. Handles spillover to ensure all batches are the specified size until the final batch. The class DLDataLoader is an extension of the torch data loader. It is required to support the FastAI framework.</p><p>Read more <a href="https://github.com/NVIDIA-Merlin/NVTabular/blob/main/nvtabular/loader/torch.py">here</a></p><pre>import torch<br>import nvtabular as nvt<strong><br></strong>from nvtabular.loader.torch import TorchAsyncItr, DLDataLoadertrain_dataset = TorchAsyncItr(<br>    nvt.Dataset(TRAINING_PATHS),<br>    batch_size=BATCH_SIZE,<br>    cats=CATEGORICAL_COLUMNS + CATEGORICAL_MH_COLUMNS,<br>    conts=NUMERIC_COLUMNS,<br>    labels=LABEL_COLUMN,<br>)train_loader = DLDataLoader(<br>  train_dataset, <br>  batch_size=None, <br>  collate_fn=lambda x: x, <br>  pin_memory=False, <br>  num_workers=0<br>)</pre><h3>Distributed NVTabular On Databricks</h3><ol><li>Use the below docker image in the Databricks cluster or (OPTIONAL) pull it for editing</li></ol><pre>docker pull <strong>allxu/nvt-061:test</strong></pre><p>[<strong>Note</strong>: NVTabular is already present in the above docker image]</p><p>2. (OPTIONAL) Edit the docker file if you want to add new packages</p><p>3. (OPTIONAL) Build the docker image</p><p>docker build -t &lt;USERNAME&gt;/&lt;REPONAME&gt;:&lt;TAG&gt; .</p><p>[<strong>Note</strong>: For any dependency related error during build please refer to the above link to the docker file to install required packages]</p><p>4. (OPTIONAL) Push the docker image to our own docker hub and set the repository to the public</p><p>5. Start a Databricks cluster and use the docker image URL mentioned above and use the below configuration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kQ6OKsc1FOTz5RU5.png" /></figure><p>Cluster configuration</p><p>6. Get the notebook from the below GitHub gist link and upload it to Databricks and attach the cluster created in step 5.</p><p>Criteo Spark Keras Training Example using Horovod</p><p>7. Clone or download the zip file containing sample data from the github link below</p><h3><a href="https://github.com/Tauhait/Horovod_TestSample_Data.git">GitHub — Tauhait/Horovod_TestSample_Data: Criteo Spark Keras Training Example using Horovod</a></h3><h3><a href="https://github.com/Tauhait/Horovod_TestSample_Data.git">You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…</a></h3><p><a href="https://github.com/Tauhait/Horovod_TestSample_Data.git">github.com</a></p><p>8. Set up Databricks CLI in your command line from the below link to upload sample data to Databricks File System</p><h3><a href="https://docs.databricks.com/dev-tools/cli/index.html">Databricks CLI</a></h3><h3><a href="https://docs.databricks.com/dev-tools/cli/index.html">Run using the appropriate version of for your Python installation. To list the version of the CLI that is currently…</a></h3><p><a href="https://docs.databricks.com/dev-tools/cli/index.html">docs.databricks.com</a></p><p>9. Follow the step by step process to upload the sample data to Databricks using dbfs from the below gist</p><p>Upload sample data using Databricks CLI</p><p>10. Run the notebook and check results</p><h3>Pandas Vs NVTabular performance comparison in Databricks</h3><p>Here we perform ETL along with <strong>Join</strong> and <strong>Lambda</strong> operations on the same data using Pandas and NVTabular in Databricks cluster (as in above step 5).</p><p>For all operations, we can see that there is a minimum 6x speedup using NVT compared to Pandas when we process huge data.</p><p>Here is the notebook which shows execution time comparison on every operation using the <a href="https://github.com/NVIDIA-Merlin/NVTabular/tree/main/examples/getting-started-movielens">movielens</a> dataset and code.</p><p><a href="https://github.com/Tauhait/NVTabular/blob/main/NVTabular_test.ipynb">Notebook Link</a></p><h3>Horovod</h3><p>Horovod is a distributed deep learning training framework for TensorFlow, Keras, PyTorch, and Apache MXNet. For faster distributed deep learning we can make use of Horovod.</p><h3>Distributed NVTabular + Horovod on Spark</h3><p>Follow the below steps to set up distributed NVTabular on Spark and also note that the demonstration is done based on <em>DGX-2 machine(with V100 GPUs).</em></p><p>1. Download and create our own dockerfile from below</p><p>Dockerfile to run Spark on NVTabular</p><p>2. Build the docker image</p><p>docker build -t &lt;USERNAME&gt;/&lt;REPONAME&gt;:&lt;TAG&gt; .</p><p>3. Docker run</p><pre>nvidia-docker run \<br> --network host \<br> --device /dev/infiniband \<br> --privileged \<br> -v /&lt;PATH&gt;:/data/parquet \<br> -it &lt;USERNAME&gt;/&lt;REPONAME&gt;:&lt;TAG&gt; bash</pre><p>4. Start spark inside the docker container</p><pre>cd /workspace<br>./start-spark.sh</pre><p>5. Set up Notebook</p><pre>SPARK_HOME= $PATH_TO_SPARK_HOME<br>SPARK_URL=spark://$SPARK_MASTER_IP:7077<br>export PYSPARK_DRIVER_PYTHON=jupyter<br>export PYSPARK_DRIVER_PYTHON_OPTS=&#39;notebook&#39;$SPARK_HOME/bin/pyspark --master $SPARK_URL --deploy-mode client \<br>--driver-memory 20G \<br>--executor-memory 50G \<br>--executor-cores 6 \<br>--conf spark.cores.max=96 \<br>--conf spark.task.cpus=6 \<br>--conf spark.locality.wait=0 \<br>--conf spark.yarn.maxAppAttempts=1 \<br>--conf spark.sql.shuffle.partitions=4 \<br>--conf spark.sql.files.maxPartitionBytes=1024m \<br>--conf spark.sql.warehouse.dir=$OUT \<br>--conf spark.task.resource.gpu.amount=0.08 \<br>--conf spark.executor.resource.gpu.amount=1 \<br>--conf spark.executor.resource.gpu.discoveryScript=./getGpusResources.sh \<br>--files $SPARK_HOME/examples/src/main/scripts/getGpusResources.sh</pre><p>To set up Spark refer to the following -</p><p><a href="https://github.com/NVIDIA/spark-rapids-examples/blob/branch-21.10/examples/criteo_train/spark-env.sh">spark-env.sh</a>: configuration script</p><p><a href="https://github.com/NVIDIA/spark-rapids-examples/blob/branch-21.10/examples/criteo_train/start-spark.sh">start-spark.sh</a>: launch Spark script</p><p><a href="https://github.com/NVIDIA/spark-rapids-examples/blob/branch-21.10/examples/criteo_train/submit.sh">submit.sh</a>: commands used to submit the job</p><p>Example: <a href="https://github.com/NVIDIA/spark-rapids-examples/tree/branch-21.10/examples/criteo_train">Run Criteo example benchmark using Dockerfile</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b25e11752207" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bitcoin Price Prediction using RAPIDS  : cuDF, DLPack and Keras on GPU]]></title>
            <link>https://sauravagarwaldigital.medium.com/bitcoin-price-prediction-using-rapids-cudf-dlpack-and-keras-on-gpu-2b2c6c256e13?source=rss-5dd9f45313ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b2c6c256e13</guid>
            <category><![CDATA[rapid]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[Saurav Agarwal]]></dc:creator>
            <pubDate>Mon, 17 May 2021 10:53:23 GMT</pubDate>
            <atom:updated>2021-05-25T04:21:19.942Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bitcoin Price Prediction using RAPIDS : cuDF, DLPack and Keras on GPU</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*lc4LoohHwV9OxfDD" /></figure><p><strong>Disclaimer : This blog is for learning purpose to demonstrate how to use NVIDIA stack for time series data and not intended to be used to create applications or use it as an investment advice in real world scenario.</strong></p><p>The popularity of Cryptocurrencies have skyrocketed with eminent entrepreneurs like Elon Musk backing it openly.</p><p>Though there is more volatility and unpredictability for cryptocurrencies as compared to stocks due to factors like technological progress, internal competition, pressure on the markets to deliver, lack of indexes, economic problems, security issues, political factor etc, but we can still try our luck using Deep Learning techniques. In addition to this, we will be using NVIDIA’s GPU framework very similar to Pandas i.e. cuDF and also try to run Deep Learning using Keras Tf on GPU’s.</p><p>In this blog, I will be going through a four step process to predict cryptocurrency prices:</p><ol><li>Data extraction using Rest API’s</li><li>Data Preparation and pre-processing using cuDF.</li><li>Predict the price of cryptocurrency using LSTM neural network using Keras Tf on GPU.</li></ol><h3>Data extraction</h3><p>The dataset can be downloaded from the CryptoCompare website which can be found <a href="https://min-api.cryptocompare.com/">here</a>.</p><p>The dataset contains below useful features. The details for them are as follows:</p><ol><li><strong>close</strong> — It is the market close price for currency for that particular day.</li><li><strong>high</strong>— It is highest price of currency for the day.</li><li><strong>low</strong>— It is the lowest price for currency for that day.</li><li><strong>open</strong>— It is market open price for currency for that day.</li><li><strong>volumefrom</strong>— The volume from of currency that is being in trade for that day.</li><li><strong>volumeto —</strong>The volume to of currency that is being in trade for that day.</li></ol><h3>Code Explanation</h3><p>The notebook on github can be found <a href="https://github.com/sauravdev/RAPIDS-Notebooks.git">here</a>.</p><p>In the Google colab GPU mode, I started with installing RAPIDS and importing all relevant libraries.</p><pre># Install RAPIDS</pre><pre>!git clone <a href="https://github.com/rapidsai/rapidsai-csp-utils.git">https://github.com/rapidsai/rapidsai-csp-utils.git</a><br>!bash rapidsai-csp-utils/colab/rapids-colab.sh stable<br>import sys, os, shutil<br>sys.path.append(&#39;/usr/local/lib/python3.7/site-packages/&#39;)<br>os.environ[&#39;NUMBAPRO_NVVM&#39;] = &#39;/usr/local/cuda/nvvm/lib64/libnvvm.so&#39;<br>os.environ[&#39;NUMBAPRO_LIBDEVICE&#39;] = &#39;/usr/local/cuda/nvvm/libdevice/&#39;\<br>os.environ[&quot;CONDA_PREFIX&quot;] = &quot;/usr/local&quot;<br>for so in [&#39;cudf&#39;, &#39;rmm&#39;, &#39;nccl&#39;, &#39;cuml&#39;, &#39;cugraph&#39;, &#39;xgboost&#39;, &#39;cuspatial&#39;]:<br>    fn = &#39;lib&#39;+so+&#39;.so&#39;<br>    source_fn = &#39;/usr/local/lib/&#39;+fn<br>    dest_fn = &#39;/usr/lib/&#39;+fn<br>    if os.path.exists(source_fn):<br>       print(f&#39;Copying {source_fn} to {dest_fn}&#39;)<br>       shutil.copyfile(source_fn, dest_fn)</pre><pre># fix for BlazingSQL import issue<br># ImportError: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.26&#39; not found (required by /usr/local/lib/python3.7/site-packages/../../libblazingsql-engine.so)<br>if not os.path.exists(&#39;/usr/lib64&#39;):<br>   os.makedirs(&#39;/usr/lib64&#39;)<br>   for so_file in os.listdir(&#39;/usr/local/lib&#39;):<br>       if &#39;libstdc&#39; in so_file:<br>           shutil.copyfile(&#39;/usr/local/lib/&#39;+so_file, &#39;/usr/lib64/&#39;+so_file)<br>           shutil.copyfile(&#39;/usr/local/lib/&#39;+so_file, &#39;/usr/lib/x86_64-linux-gnu/&#39;+so_file)</pre><pre>import cudf</pre><p>I have used Canadian exchange rate and stored the real time data into a cuDF data-frame. I used to_datetime() method to convert string Date time into the Date time object. This is necessary as Date time objects in the file are read as a string object.</p><pre>endpoint = &#39;https://min-api.cryptocompare.com/data/histoday&#39;<br>res = requests.get(endpoint + &#39;?fsym=BTC&amp;tsym=CAD&amp;limit=2000&#39;)<br>hist = cudf.DataFrame(json.loads(res.content)[&#39;Data&#39;])<br>hist = hist.set_index(&#39;time&#39;)<br>hist.index = cudf.to_datetime(hist.index, unit=&#39;s&#39;)\<br>target_col = &#39;close&#39;</pre><p>Let’s see how the dataset looks like with all the trading features like price, volume, open, high, low.</p><pre>hist.head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*0uA8r_jrii69QZJ1UOiVWA.png" /><figcaption>Crypto Data</figcaption></figure><p>Next, I split the data into two sets — training set and test set with 80% and 20% data respectively. The decision made here is just for the purpose of this tutorial. In real projects, you should always split your data into training, validation, testing (like 60%, 20%, 20%).</p><pre>def train_test_split(df, test_size=0.2):<br>    split_row = len(df) - int(test_size * len(df))<br>    train_data = df.iloc[:split_row]<br>    test_data = df.iloc[split_row:]<br>    return train_data, test_datatrain, test = train_test_split(hist, test_size=0.2)</pre><p>Now let’s plot the cryptocurrency prices in Canadian dollars as a function of time using the below code:</p><pre>def line_plot(line1, line2, label1=None, label2=None, title=&#39;&#39;, lw=2):<br>    fig, ax = plt.subplots(1, figsize=(13, 7))<br>    ax.plot(line1, label=label1, linewidth=lw)<br>    ax.plot(line2, label=label2, linewidth=lw)<br>    ax.set_ylabel(&#39;price [CAD]&#39;, fontsize=14)<br>    ax.set_title(title, fontsize=16)<br>    ax.legend(loc=&#39;best&#39;, fontsize=16)line_plot(train[target_col], test[target_col], &#39;training&#39;, &#39;test&#39;, title=&#39;&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bso9IV90WXL96lWIIE1D_Q.png" /><figcaption>Bitcoin Price Trend</figcaption></figure><p>We can see there is no seasonal pattern as such and with crypto its hard to generalize anything.</p><p>Next, I made a couple of functions to normalize the values. Normalization is a technique often applied as part of data preparation for machine learning. The goal of normalization is to change the values of numeric columns in the dataset to a common scale, without distorting differences in the ranges of values.</p><pre>def normalise_zero_base(df):<br>    return cudf.DataFrame(df.values / df.values[0] - 1)</pre><pre>def normalise_min_max(df):<br>    return (df - df.min()) / (df.max() - df.min())</pre><p>Next, I made a function to extract data of windows which are of size 5 each as shown in the code below:</p><pre>def extract_window_data(df, window_len=5, zero_base=True):<br>    window_data = []<br>    for idx in range(len(df) - window_len):<br>        tmp = df[idx: (idx + window_len)].copy()<br>        if zero_base:<br>            tmp = normalise_zero_base(tmp)<br>        window_data.append(tmp.values)<br>    return np.array(window_data)</pre><p>I continued with making a function to prepare the data in a format to be later fed into the neural network. I used the same concept of splitting the data into two sets — training set and test set with 80% and 20% data respectively as shown in the code below:</p><pre>def prepare_data(df, target_col, window_len=10, zero_base=True, test_size=0.2):<br>    train_data, test_data = train_test_split(df, test_size=test_size)<br>    X_train = extract_window_data(train_data, window_len, zero_base)<br>    X_test = extract_window_data(test_data, window_len, zero_base)<br>    y_train = train_data[target_col][window_len:].values<br>    y_test = test_data[target_col][window_len:].values<br>    if zero_base:<br>        y_train = y_train / train_data[target_col][:-window_len].values - 1<br>        y_test = y_test / test_data[target_col][:-window_len].values - 1</pre><pre>    return train_data, test_data, X_train, X_test, y_train, y_test</pre><h3>DLPack</h3><p><a href="https://github.com/dmlc/dlpack">DLPack </a>is an open in-memory tensor structure to for sharing tensor among frameworks. DLPack enables</p><ul><li>Easier sharing of operators between deep learning frameworks.</li><li>Easier wrapping of vendor level operator implementations, allowing collaboration when introducing new devices/ops.</li><li>Quick swapping of backend implementations, like different version of BLAS</li><li>For final users, this could bring more operators, and possibility of mixing usage between framework</li></ul><p><strong>With PytTorch, Chainer and Tensorflow (experimental) we can use </strong><a href="https://twitter.com/hashtag/DLPack?src=hashtag_click"><strong>#DLPack</strong></a><strong> and </strong><a href="https://twitter.com/hashtag/__cuda_array_interface__?src=hashtag_click"><strong>__cuda_array_interface__</strong></a><strong> to use </strong><a href="https://twitter.com/hashtag/cuDF?src=hashtag_click"><strong>cuDF</strong></a><strong> dataframes as input in Keras without disrupting the GPU workflow.</strong></p><pre>arr_tf_xt = tf.experimental.dlpack.from_dlpack(X_train.toDlpack())<br>arr_tf_yt = tf.experimental.dlpack.from_dlpack(y_train.toDlpack())</pre><p>Now let’s build the model. Sequential model is used for stacking all the layers (input, hidden and output). The neural network comprises of a LSTM layer followed by 20% Dropout layer and a Dense layer with linear activation function. I complied the model using Adam as the optimizer and Mean Squared Error as the loss function.</p><pre>def build_lstm_model(input_data, output_size, neurons=100, activ_func=&#39;linear&#39;, dropout=0.2, loss=&#39;mse&#39;, optimizer=&#39;adam&#39;):<br>    model = Sequential()<br>    model.add(LSTM(neurons, input_shape=(input_data.shape[1], input_data.shape[2])))<br>    model.add(Dropout(dropout))<br>    model.add(Dense(units=output_size))<br>    model.add(Activation(activ_func))<br>    model.compile(loss=loss, optimizer=optimizer)<br>    return model</pre><p>Next, I set up some of the parameters to be used later. These parameters are — random number seed, length of the window, test set size, number of neurons in LSTM layer, epochs, batch size, loss, dropouts and optimizer.</p><pre>np.random.seed(42)<br>window_len = 5<br>test_size = 0.2<br>zero_base = True<br>lstm_neurons = 100<br>epochs = 20<br>batch_size = 32<br>loss = &#39;mse&#39;<br>dropout = 0.2<br>optimizer = &#39;adam&#39;</pre><p>Now let’s train the model using inputs x_train and labels y_train.</p><pre>train, test, X_train, X_test, y_train, y_test = prepare_data(<br>    hist, target_col, window_len=window_len, zero_base=zero_base, test_size=test_size)model = build_lstm_model(<br>    X_train, output_size=1, neurons=lstm_neurons, dropout=dropout, loss=loss,<br>    optimizer=optimizer)<br>history = model.fit(<br>    X_train, y_train, epochs=epochs, batch_size=batch_size, verbose=1, shuffle=True)</pre><p>Let us take a look at snapshot during model training for 20 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*PkNy4BmgHEhzCoYHJQpjfA.png" /></figure><p>Training of the neural network</p><p>I used Mean Absolute Error (MAE) as the evaluation metric.</p><p>The MAE value obtained looks good. Finally, let’s plot the actual and predicted prices using the below code:</p><pre>targets = test[target_col][window_len:]<br>preds = model.predict(arr_tf_xtest).squeeze()<br>mean_absolute_error(preds, arr_tf_ytest)</pre><pre>0.028300751124918887</pre><pre>preds = testcd[target_col].values[:-window_len] * (preds + 1)<br>preds = cudf.Series(index=targets.index, data=preds)<br>predscd = preds.to_pandas()<br>line_plot(targetscd, predscd , &#39;actual&#39;, &#39;prediction&#39;, lw=3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*vvMshLvWwl8qZ0_0c0zhuw.png" /></figure><p>However, do not expect this accuracy in real world scenario due to several factors like not split and used validation set, not considered volatility of bitcoin and overall new/market sentiment on bitcoin / crypto currencies.</p><h3>Conclusion</h3><p>In this article, I demonstrated how to predict cryptocurrency prices in real time using LSTM neural network on GPU especially using RAPIDS and DLPack.</p><p>Feel free to play with the hyper-parameters or try out different neural network architectures for better results.</p><p>This is for a small dataset hence we did not compare the performance, for larger datasets GPU will be a clear winner with RAPIDS cuDF accelerating in order of magnitude of double digits with a lesser TCO.</p><p><strong>Disclaimer : This blog is for learning purpose to demonstrate how to use NVIDIA stack for time series data and not intended to be used to create applications or use it as an investment advice in real world scenario.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b2c6c256e13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Too Small Data — Solving Small Files issue using Spark]]></title>
            <link>https://sauravagarwaldigital.medium.com/too-small-data-solving-small-files-issue-using-spark-b7ef66827a24?source=rss-5dd9f45313ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7ef66827a24</guid>
            <category><![CDATA[small-files]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Saurav Agarwal]]></dc:creator>
            <pubDate>Fri, 25 Dec 2020 16:24:47 GMT</pubDate>
            <atom:updated>2020-12-25T16:27:33.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qTsosXZdy5bga-U0uBK5-g.jpeg" /></figure><h3>Too Small Data — Solving Small Files issue using Spark</h3><p>I am pretty sure you all must have come across the issue of Small files issues while working with Big Data frameworks like Spark, Hive etc.</p><p><strong>What is a small file?</strong></p><p>Definition of small file can be a data file which is considerably smaller than the default block size of the underlying file systems (e.g. 128MB by default in CDH)</p><p><strong>Sources of small files?</strong></p><p>These small files originate from different sources of data as well as resultant of data processing jobs as well.</p><p><strong>Problems due to small files</strong></p><p>In addition to creating inefficient storage (particularly in HDFS etc) mainly, small files affect the compute performance of the job a lot as well. The reason being small files results in more disk seeks while running computations through these compute engines.</p><p>For example, we know that in Spark, the task within an executor reads and processes one partition at a time. Each partition is one block by default. Hence, a single concurrent task can run for every partition in a Spark RDD. This means that if you have a lot of small files, each file is read in a different partition and this will cause a substantial task scheduling overhead compounded by lower throughput per CPU core.</p><p><strong>Solution</strong></p><p>The solution to these problems is 3 folds.</p><ul><li>First is trying to stop the root cause.</li><li>Second, being identifying these small files locations + amount.</li><li>Finally being, compacting the small files to larger files equivalent to block size or efficient partition size of the processing framework.</li></ul><p>For avoiding small files in the first place make sure the processes producing the data are well-tuned. In case the process is Spark make sure you use repartition() OR coalesce() OR set the spark shuffle partitions property effectively to avoid small files issue in the first place.</p><p>If things are already worse. Now, let&#39;s try to understand how to identify these small files. We will consider HDFS as the storage framework here.</p><p>Below shell script can be run using all list privileges in the base path on which small files need to be identified.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6871f205f7a49ba0f9557f603efc8638/href">https://medium.com/media/6871f205f7a49ba0f9557f603efc8638/href</a></iframe><p>Now that final_list.csv has a list of the directory at N depth_level and the respective amount of small files in it sorted by the amount in decreasing order, we can very well run a Spark job to concatenate these small files as an offline process. Below is a snippet of the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7c58f61baef1b1c2a658715cb4ab7b4/href">https://medium.com/media/d7c58f61baef1b1c2a658715cb4ab7b4/href</a></iframe><p>This code snippet written in Scala will merge the small files into larger files by dynamically calculating the size of the target directory using the <strong>bucket_cal</strong> function.</p><p>Hope it will help, do let me know in case of any questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7ef66827a24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Masking in Big Data [Spark]]]></title>
            <link>https://medium.datadriveninvestor.com/data-masking-in-big-data-spark-cf3d111a7ea9?source=rss-5dd9f45313ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf3d111a7ea9</guid>
            <category><![CDATA[data-masking]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Saurav Agarwal]]></dc:creator>
            <pubDate>Thu, 08 Aug 2019 17:57:03 GMT</pubDate>
            <atom:updated>2019-09-10T11:48:02.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZcM4yBSBaoMdBDKNNJMJw.png" /></figure><p>We often face challenges over masking data in our Big Data pipelines so that all sensitive data is masked from the unauthorized users. These users can be developers, business analysts, data engineers or just anyone trying to play around.</p><p>Since we know that we just cannot mask data to make it XXXX to make it useless, I have come up with a useful method for data masking in a generic way for all types of data so that the same data can be used for useful purposes.</p><p><a href="https://www.datadriveninvestor.com/2019/01/25/why-data-will-transform-investment-management/">Why Data will Transform Investment Management | Data Driven Investor</a></p><p>Data formats can be of any type e.g. email, credit card, number, string, date, etc. We need to preserve these types so that user at least knows what can be the expected data formats.</p><p>Take an example of following Deals dataset defined as <strong>DealsDF</strong>-</p><pre> — — -+ — — — — — — — -+ — — — — — + — — — — — -+<br>|deal_id|discount_amount|product_id|active_flag|<br>+ — — — -+ — — — — — — — -+ — — — — — + — — — — — -+<br>|deal1 |1.0 |product1 |Y |<br>|deal2 |1.2 |product2 |Y |<br>|deal1 |1.5 |product3 |N |<br>|deal1 |1.2 |product4 |Y |<br>|deal1 |1.2 |product2 |Y |<br>+ — — — -+ — — — — — — — -+ — — — — — + — — — — — -+</pre><p>The task is to mask the deal_id, discount amount and product_id for each deal_id. We can use below snippet to do it.</p><pre>def mask(inputDF: Dataset[Row], colmask: Map[String, List[String]], customMaskSring: String = “”): Dataset[Row] = {<br> var initialDF = inputDF<br> colmask.foreach {<br> case (“email”, value) =&gt; value.foreach { v =&gt; { initialDF = initialDF.withColumn(v, lit(“<a href="/service/mailto:aXXX@XXXX.com">aXXX@XXXX.com</a>”)) } }<br> case (“custom”, value) =&gt; value.foreach { v =&gt; { initialDF = initialDF.withColumn(v, lit(customMaskSring)) } }<br> case (“creditcard”, value) =&gt; value.foreach { v =&gt; { initialDF = initialDF.withColumn(v, lit(“xxxx-xxxx-xxxx-1234”)) } }<br> case (“randomnumber”, value) =&gt; value.foreach { v =&gt; { initialDF = initialDF.withColumn(v, lit(scala.util.Random.nextInt(10000))) } }<br> case (“number”, value) =&gt; value.foreach { v =&gt; { initialDF = initialDF.withColumn(v, lit(0)) } }<br> case (“string”, value) =&gt; value.foreach { v =&gt; { initialDF = initialDF.withColumn(v, lit(“xxxx”)) } }<br> case (“date”, value) =&gt; value.foreach { v =&gt; { initialDF = initialDF.withColumn(v, lit(“01–01–1900”)) } }<br> case _ =&gt; { initialDF }<br> }<br> initialDF<br> }</pre><p>And if we run below code example, we get the masked data.</p><pre>val maskeddf= mask(DealsDF, Map(“string” -&gt; List(“deal_id”, “product_id”),”number” -&gt; List(“discount_amount”)))</pre><pre>maskeddf.show(false)</pre><pre>+ — — — -+ — — — — — — — -+ — — — — — + — — — — — -+</pre><pre>|deal_id|discount_amount|product_id|active_flag|</pre><pre>+ — — — -+ — — — — — — — -+ — — — — — + — — — — — -+</pre><pre>|xxxx |0 |xxxx |Y |</pre><pre>|xxxx |0 |xxxx |Y |</pre><pre>|xxxx |0 |xxxx |N |</pre><pre>|xxxx |0 |xxxx |Y |</pre><pre>|xxxx |0 |xxxx |Y |</pre><pre>+ — — — -+ — — — — — — — -+ — — — — — + — — — — — -+</pre><p>We can also create a config table and fetch value of Map e.g.<em> Map(“string” -&gt; List(“deal_id”, “product_id”),”number” -&gt; List(“discount_amount”))</em> from the table instead of coding.</p><p>It’s as simple as this, in the next post I will include different type of encryption algorithms to mix and match with masking to secure your big data pipelines.</p><p>Happy Coding!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf3d111a7ea9" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/data-masking-in-big-data-spark-cf3d111a7ea9">Data Masking in Big Data [Spark]</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling complexity in Big Data —  Process nested json with changing schema tags]]></title>
            <link>https://medium.datadriveninvestor.com/handling-complexity-in-big-data-process-nested-json-with-changing-schema-tags-699972dc17e4?source=rss-5dd9f45313ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/699972dc17e4</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Saurav Agarwal]]></dc:creator>
            <pubDate>Sat, 03 Nov 2018 16:48:08 GMT</pubDate>
            <atom:updated>2019-09-10T11:45:32.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyNo9dsZje9vStCgGxPeOQ.jpeg" /></figure><h3>Complexity in Big Data — Process nested json with changing schema tags</h3><p>You may have seen various cases of reading json data ranging from nested structure to json having corrupt structure. But, let&#39;s see how do we process a nested json with a schema tag changing incrementally. We will use Spark Dataframe API in its native language Scala to solve this problem.</p><p>Let&#39;s see how do we process sample json structure as below-</p><pre>{ “id” : “595ada836ef4fb4fe47d8c01”),<br> “response” : { “0” : { “currency” : “JPY”, “rate” : 112.27 }, <br> “1” : { “currency” : “AUD”, “rate” : 1.30078 },<br> “2” : { “currency” : “EUR”, “rate” : 0.87544 }, <br> “3” : { “currency” : “GBP”, “rate” : 0.76829 },<br> “4” : { “currency” : “CNY”, “rate” : 6.77907 } }, <br> “ratesDate” : “2017–07–03”,<br> “createdAt” : “2017–07–04T00:00:03.421Z”,<br> “updatedAt” : “2017–07–04T00:00:03.421Z” }</pre><p>We can see in the above json that the response from API is a nested struct type having incremental tags ranging from 0 to n. What makes this problem complex but still easily solvable is because we know the tags are incremented by 1.</p><p><a href="https://www.datadriveninvestor.com/2019/01/25/why-data-will-transform-investment-management/">https://www.datadriveninvestor.com/2019/01/25/why-data-will-transform-investment-management/</a></p><p>Lets start by reading the data and printing the json schema to understand it’s complexity using below-</p><pre>val dataframe = spark.read.option(“multiLine”,true).json( “hdfs://path/of/json”)</pre><pre>dataframe.printSchema</pre><pre>root<br> | — _id: string (nullable = true)<br> | — createdAt: string (nullable = true)<br> | — ratesDate: string (nullable = true)<br> | — response: struct (nullable = true)<br> | | — 0: struct (nullable = true)<br> | | | — currency: string (nullable = true)<br> | | | — rate: double (nullable = true)<br> | | — 1: struct (nullable = true)<br> | | | — currency: string (nullable = true)<br> | | | — rate: double (nullable = true)<br> | | — 2: struct (nullable = true)<br> | | | — currency: string (nullable = true)<br> | | | — rate: double (nullable = true)<br> | | — 3: struct (nullable = true)<br> | | | — currency: string (nullable = true)<br> | | | — rate: double (nullable = true)<br> | | — 4: struct (nullable = true)<br> | | | — currency: string (nullable = true)<br> | | | — rate: double (nullable = true)<br> | — updatedAt: string (nullable = true)</pre><p>We can very well see above schema is quite complex but let&#39;s take the challenge of converting this schema to a more structured format-<br>First, we have to find out how many responses are getting in that particular json record, so we have to loop through the nested field names and create a counter for getting the number of responses.<br>Below is a code snippet to do that -</p><pre>import scala.util.Try<br>import org.apache.spark.sql.DataFrame<br>var counts=0<br>for(name &lt;- dataframe.select(“response.*”).schema.fieldNames) {<br>if (Try(name.toInt).isSuccess == true)<br>{<br>counts+=1<br>}<br>}</pre><p>Now that we know how many responses we have, we can create a dataframe and add response tags content as column names with the values being concatenated based on a fixed nested structure. See, below code snippet for the actual implementation-</p><pre>var dataframeflattened = dataframe<br>for(c &lt;- 0 to counts-1) {<br>var concatstringcurrency = “response.”+c.toString()+”.currency”<br>var concatstringcurrencyrate = “response.”+c.toString()+”.rate”<br>dataframeflattened = dataframeflattened.withColumn(concatstringcurrency,col(concatstringcurrency)).withColumn(concatstringcurrencyrate,col(concatstringcurrencyrate))<br>}</pre><p>And, finally, we arrive at the required flattened dataframe -</p><p>dataframeflattened.drop(“response”).show</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ycizwXMAPCCny0Lc3_6IQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RwpA4JKm4lYJuagNelNX1A.png" /></figure><p>Also, an alternative way of flattening the data can be using explode() as shown below -</p><pre>var dataframeflattenedalttmp = dataframe.withColumn(“temp”,explode(array(col(“response.*”))))</pre><pre>var dataframeflattenedalt = dataframeflattenedalttmp.withColumn(“currency”,explode(array(col(“temp.currency”)))).withColumn(“rate”,explode(array(col(“temp.rate”)))).drop(“temp”,”response”)</pre><pre>dataframeflattenedalt.show</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*iieqeSAn5q70UaA36XsgTw.png" /></figure><p>Great, we solved major part of it, but in the next part of <strong>Complexity in Big Data </strong>series we will see how do we parse multiple json having different schema altogether and unifying all different json dataframes to a single dataframe and writing it to a target path Or a Hive table.</p><p>Special thanks to Priyanshu and Subhasish for giving different ideas for solving it.</p><p>Stay Tuned! and Keep Shining!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=699972dc17e4" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/handling-complexity-in-big-data-process-nested-json-with-changing-schema-tags-699972dc17e4">Handling complexity in Big Data —  Process nested json with changing schema tags</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NoSQL Simplified]]></title>
            <link>https://sauravagarwaldigital.medium.com/nosql-simplified-55829125896e?source=rss-5dd9f45313ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/55829125896e</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Saurav Agarwal]]></dc:creator>
            <pubDate>Sat, 22 Sep 2018 17:24:51 GMT</pubDate>
            <atom:updated>2018-09-22T17:30:44.630Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Basics of NoSQL</strong><br>NoSQL eliminates the need of a schema, hence pushing the data handling capacity by a huge margin by compromising on ACID. However, with accurate supporting applications in place, NoSQL provide a good combination of high data handling capacity with good accuracy. In this article we will discuss popular NoSQL databases.<br><strong>What is CAP Theorem?</strong><br>CAP theorem states that at best we can aim for two of three following properties. CAP stands for:</p><ul><li>Consistency — This means that data in the database remains consistent after the execution of an operation.</li><li>Availability — This means that the database system is always on to ensure availability.</li><li>Partition Tolerance — This means that the system continues to function even if the transfer of information amongst the servers is unreliable.</li></ul><p>The various databases and their relations with CAP theorem is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*FPRzUaCJKQLI7z7_bVI1DQ.png" /><figcaption>CAP Theorem</figcaption></figure><p>Following are some common features of NoSQL databases :<br>1. They are not relational<br>2. Mostly open-source<br>3. They are all cluster-friendly<br>4. They are schema less<br>5. They emerged out of 21st century Web world<br>However, we often refer to NoSQL as schema less, this does not mean that these database do not adhere to any kind of schema. For example consider the following NoSQL expression :<br>Tab1[“Revenue” ] * Tab1[“Total count”]</p><p>NoSQL has an implicit schema, which might not be constant throughout the database. Such thing is both a boon and a curse. The base thing is whenever we want to modify a field we need to understand this implicit schema. The good thing is that with a changing schema it asks for much lesser effort to append this database compared to RDBMS. Also RDBMS is not great with a distributed network which is not the case with NoSQL.</p><p><strong>Types of NoSQL databases</strong></p><p>However, in literature NoSQL has been broken down into 4 major types, I found a very interesting way suggested by Martin Fowler to categorize NoSQL. Based on the way NoSQL stores data, it is primarily of two types :<br>1. Aggregate based Database<br>2. Graph based Database<br>The primary difference between the two is that in aggregate type, database tries to store all the information for a particular ID (this can be an individual or transaction or product etc.) as a single object. Whereas graph type follows the exact opposite philosophy. Graph type database tries to cut the data into highly granular information and stores them with all the shared relations or edges. We will discuss the aggregate based databases, which are more common today, in this article.<br>Column-oriented Databases :<br>Imagine that you have a RDBMS orders table with 1 Million rows and 100 columns. Now you want to pull all the customer names with orders of more than $500. You essentially need command on only two columns, but to do this query you will essentially have to browse through all 100 columns. Column oriented databases give a solution to this problem. A detailed discussion on this type of database is out of scope for this article, but what you need to understand is just the underlying concept.<br>Please share you views/opinion/comments with us in the comments section below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55829125896e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>