<?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 Rick(Rugui) Chen on Medium]]></title>
        <description><![CDATA[Stories by Rick(Rugui) Chen on Medium]]></description>
        <link>https://medium.com/@rickruguichen?source=rss-c074bc07b3ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qzE76iqj-Vd_LT94</url>
            <title>Stories by Rick(Rugui) Chen on Medium</title>
            <link>https://medium.com/@rickruguichen?source=rss-c074bc07b3ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 23:32:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rickruguichen/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[Bridging the Divide: Unifying Platform and ML Engineering on Google Cloud for Next-Gen AI]]></title>
            <link>https://medium.com/google-cloud/bridging-the-divide-unifying-platform-and-ml-engineering-on-google-cloud-for-next-gen-ai-3d2e7b57e900?source=rss-c074bc07b3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d2e7b57e900</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[ml-engineering]]></category>
            <category><![CDATA[gke]]></category>
            <dc:creator><![CDATA[Rick(Rugui) Chen]]></dc:creator>
            <pubDate>Sat, 12 Jul 2025 21:10:56 GMT</pubDate>
            <atom:updated>2025-07-13T03:30:13.852Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dm6gt8SMKmWnhVxEY7guZQ.png" /></figure><h4>I. Introduction: The Dual Mandate of AI Infrastructure</h4><p>Generative AI is revolutionizing industries, but it’s also creating a significant challenge for the teams building the infrastructure to support it.[<a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fvertexaisearch.cloud.google.com%2Fgrounding-api-redirect%2FAUZIYQG9aEON_zq8hvQfBczfT1EWPK_vEbDN_Q_n0tDPN9YnSrDs9BsvulQcZwXoIAn14wxFIdIyRaVy35IhfikTHKL7XsoU92iA74IJ6aBjT-rxGxE2q0bS03Ew6ucaW9w3KLN5Sw8xRU-Vqct9yDpPVwvno2uRQWUJAKci1JMITJyG">1</a>] This new wave of AI requires a careful balancing act between the rapid innovation demanded by Machine Learning (ML) Engineers and the stability and control prioritized by Platform Engineers.</p><p>On one side, Platform Engineers are the guardians of infrastructure, focusing on reliability, security, and performance.[<a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fvertexaisearch.cloud.google.com%2Fgrounding-api-redirect%2FAUZIYQGRmC6s3gsKrrGMO2jESHeg72xh7uUowvWnvbHiDCS0IHhmpO81EMnTrbnXS0mDFRIhF3I4Vjqb8CGRGcFYTlzeyO5MdvIYzh1R-m9OmAbef0W5uQin1BIg-Q04ZKZbxC3Om9ZaOZ6toahWZmq8aJ3-">2</a>] They build and manage the foundational systems, ensuring everything runs smoothly and efficiently. On the other side, ML Engineers are the innovators, driven to accelerate model development and experimentation to create cutting-edge Generative AI products.[<a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fvertexaisearch.cloud.google.com%2Fgrounding-api-redirect%2FAUZIYQFPckOg8QbhjKi6Q3zwFqCYqPx_uJgxEsviYgj7mTVQIM8pGxdOoZPRnZlG5WABVH-Mi3wYlqM1Bv6B7dQFhRrnTHCZ4XbzHBebjue9j4YCnRUSHY_uZcBLDLtcLHLsPrEB7QAV6ABNhjyecrxpfxIyrGwTXpgqxMfVaGAw6Kb2l6vp415zQoU%3D">3</a>]</p><p>This clash of priorities can lead to friction, with ML Engineers feeling stifled by infrastructure constraints and Platform teams viewing rapid changes as a threat to stability.[<a href="https://www.google.com/url?sa=E&amp;q=https%3A%2F%2Fvertexaisearch.cloud.google.com%2Fgrounding-api-redirect%2FAUZIYQG2MVUudPTsHiu1PYDkQUhZc5gZd-Cao01EW0GQE56ffyG6UefOkcdddrqHoVWktiDWE0T-FqdYSWxuBvpWNgOWuad6fFFFEZ133dxGGhOiJcXBubDHi221S-2COkCNMRNRqJHEmg-8xlYdoleq-aoUhIBzDVhUxrIOipNETyhxTCvYY1m0Dh9ShISKodiDRLTls-UA6w%3D%3D">4</a>] The key to success lies in bridging this gap. An effective cloud strategy must provide both the robust control needed by platform teams and the agile, streamlined workflows required by ML engineers. This synergy is crucial for fostering a collaborative and efficient AI development lifecycle.II. Empowering the Platform Team: Control, Reliability, and Automation</p><p>Platform teams, as infrastructure custodians, are responsible for its stability, security, and performance. Google Cloud offers services empowering these teams with control and automation for robust AI infrastructure.</p><h4>GKE: The Foundation for Customizable Control</h4><p><a href="https://cloud.google.com/kubernetes-engine/docs/integrations/ai-infra">Google Kubernetes Engine (GKE)</a> is a managed Kubernetes service providing platform teams with deep, customizable control over AI infrastructure, including compute, storage, network, and security management.</p><p>For enterprise AI workloads, GKE Enterprise extends GKE into a powerful AI backbone, addressing complex security, governance, and operational requirements. This suite provides guardrails for platform engineers to confidently offer Kubernetes-based infrastructure to ML teams, ensuring adherence to enterprise security standards and operational best practices, while maintaining flexibility for innovation.</p><p>Key control and security features within GKE Enterprise include:</p><ul><li><strong>Workload Identity Federation:</strong> Enables least privilege by granting granular IAM permissions to Kubernetes service accounts, ensuring AI workloads access only necessary Google Cloud resources and reducing attack surface.</li><li><strong>Fleet-wide Identity Pool:</strong> For multi-cluster organizations, fleets allow consistent IAM bindings across all clusters, simplifying governance and access control at scale.</li><li><strong>Binary Authorization:</strong> Ensures only trusted container images run on clusters, blocking unauthorized deployments and enforcing security throughout the software supply chain.</li><li><strong>Cloud Armor (WAF):</strong> Filters incoming Layer 7 network traffic to protect AI workloads, offering various rule types and integrating with the GKE Gateway Controller.</li><li><strong>Identity Aware Proxy (IAP):</strong> Provides an additional security layer for AI applications via load balancers, securely authenticating and authorizing users without a VPN.</li><li><strong>Kubernetes Network Policies:</strong> Offers Kubernetes-native traffic control, defining granular ingress and egress rules for pods to ensure secure communication and workload isolation.</li></ul><p>GKE’s native Kubernetes support also enables platform teams to build robust automation and CI/CD pipelines using tools like GitHub Actions, Argo Workflows, and Jenkins, ensuring reliable and performant AI application deployment and maintenance.</p><h4>Vertex AI: The Fully Managed Platform Advantage</h4><p><a href="https://cloud.google.com/vertex-ai?hl=en">Vertex AI </a>offers a fully managed service for the entire ML lifecycle, significantly reducing operational burden on platform teams. This frees them from provisioning and managing physical infrastructure, allowing focus on MLOps pipelines, advanced security, and overall AI platform strategy.</p><p>This shift enables a more efficient division of labor: platform teams become strategic enablers, building robust, secure, and cost-optimized managed environments, while ML teams become agile innovators, leveraging these environments without infrastructure complexities. This fosters collaboration and accelerates the AI development lifecycle.</p><p>Vertex AI provides a unified workbench and comprehensive MLOps environment, including tools for end-to-end ML workflows, feature engineering, experiment tracking, model management, and quality monitoring. This aligns with platform goals of operationalizing ML at scale and ensuring model reliability.</p><p>Built-in security features like VPC peering, VPC Service Controls, customer-managed encryption keys (CMEK), and fine-grained Identity and Access Management (IAM) are critical for platform teams, ensuring data protection and access control with minimal manual configuration.</p><p>Vertex AI training jobs are optimized for ML. It also supports distributed training with features like Reduction Server and automated hyperparameter optimization. Vertex AI Pipelines often run on GKE clusters , and Vertex AI itself leverages AI Hypercompute , assuring platform teams that workloads run on Google Cloud’s optimized and secure foundation.</p><p><strong>Table 1: GKE vs. Vertex AI for AI Workloads (Platform vs. ML Engineer Perspective)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-1rx3mx9Bmx8wseyz8LIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5TuxEvM5rFBLLpVpxRy0w.png" /></figure><h4>Infrastructure as Code (IaC) and Curated Cluster Management</h4><p>IaC is paramount for platform teams to achieve reliability, consistency, and scalability. Google Cloud offers specialized tools combining IaC with high-performance AI infrastructure.</p><p><strong>AI Hypercompute (Cluster Director): Powering High-Performance AI</strong></p><p><a href="https://cloud.google.com/ai-hypercomputer/docs/overview">AI Hypercompute</a>, with <a href="https://cloud.google.com/ai-hypercomputer/docs/cluster-director">Cluster Director</a>, is Google Cloud’s specialized infrastructure for deploying and managing accelerators (TPUs, GPUs) as a single, high-performance unit. This is critical for large-scale Generative AI training and inference.</p><p>Key features of AI Hypercompute for AI workloads include:</p><ul><li><strong>Dense Colocation of Accelerator Resources:</strong> Physically close host machines, provisioned as resource blocks, interconnected with a dynamic ML network fabric, minimizing network hops and optimizing for low latency in distributed training.</li><li><strong>Topology-Aware Scheduling:</strong> Provides detailed topology information for efficient job placement and maximized accelerator utilization.</li><li><strong>Advanced Maintenance Scheduling and Controls:</strong> Full control over VM maintenance within resource blocks, including synchronized upgrades and alerts for scheduled events, improving “goodput”.</li><li><strong>Enhanced Networking &amp; Rapid Storage:</strong> 400G Cloud Interconnect offers 4x more bandwidth. Rapid Storage solutions like Cloud Storage zonal buckets and Anywhere Cache provide up to 20x faster random-read data loading and 70% latency reduction, directly impacting training/inference speed.</li><li><strong>360° Observability &amp; Job Continuity:</strong> Comprehensive monitoring dashboards, AI Health Predictor, Straggler Detection, and multi-tier checkpointing ensure uninterrupted training.</li><li><strong>Open Software Capabilities:</strong> Co-designed software supports popular ML frameworks (PyTorch, JAX, vLLM, Keras), facilitating faster delivery and cost-efficient resource utilization.</li></ul><p>AI Hypercompute underpins nearly every AI workload on Google Cloud, including Vertex AI. It’s accessible via Compute Engine APIs or natively integrated with GKE, offering flexible deployment.</p><h4>Cluster Toolkit: Open-Source IaC for AI/ML Clusters</h4><p>The Google Cloud <a href="https://cloud.google.com/cluster-toolkit/docs/overview">Cluster Toolkit</a>, an open-source software, simplifies deploying HPC, AI, and ML workloads on Google Cloud, enabling fast creation of turnkey clusters adhering to best practices.</p><p>At its core, Cluster Toolkit leverages IaC principles. It uses a cluster blueprint (YAML) to declaratively define configurations. These blueprints utilize modules (Terraform or Packer files) to define infrastructure as code. The gcluster engine combines modules based on the blueprint to produce a deployment folder, which can be customized before deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11HZFJ-ETchSo14fEO5r4A.png" /></figure><p>While effective for creation and deletion, modifying active clusters typically involves deleting, updating the blueprint, creating a new deployment folder, and redeploying. This ensures a controlled, IaC-driven change management process. As an open-source solution, it’s highly configurable and extensible, supporting various use cases and integrating with <a href="https://slurm.schedmd.com/documentation.html">Slurm</a>. It also integrates with Cloud Monitoring for performance visibility.</p><p>The synergy of specialized hardware (AI Hypercompute) and robust IaC (Cluster Toolkit) automates and optimizes AI infrastructure provisioning. This benefits both platform and ML teams: platform teams achieve control, reliability, and automation, while ML engineers gain faster, on-demand access to optimally configured compute resources, accelerating development and iteration.</p><h3>III. Accelerating ML Innovation: Velocity, Experimentation, and Iteration</h3><p>ML engineers need to rapidly develop models, iterate quickly, and accelerate time-to-market for Generative AI products. Google Cloud can be integrated with specialized tools addressing these needs, allowing ML engineers to focus on core competencies.</p><h4>Ray on GKE and Vertex AI: Scalable AI and Python Applications</h4><p><a href="https://www.anyscale.com/product/open-source/ray">Ray </a>is an open-source framework for scaling AI and Python applications, providing infrastructure for distributed computing and parallel processing in ML workflows. ML engineers can use existing open-source Ray code on Vertex AI with minimal changes, leveraging Vertex AI’s integrations with Google Cloud services like Vertex AI Inference and BigQuery.</p><p>Ray’s key benefit is scaling the <em>same Python code</em> seamlessly from a laptop to a large distributed cluster, reducing re-engineering efforts. Ray’s integrated AI libraries (Ray Train, Ray Data, Ray Serve) offer a unified API, allowing easy swapping between ML frameworks (PyTorch, JAX, Hugging Face, XGBoost) on a consistent runtime (Ray, often orchestrated by KubeRay).</p><p>Ray’s open-source nature allows direct <a href="https://github.com/llm-on-gke/kueue-ray/tree/main/raytrain-example">deployment on GKE</a>, offering a powerful, scalable foundation for ML workloads. Platform engineers provision GKE clusters with high-performance accelerators like NVIDIA H100 and A3 Ultra (H200 GPUs). ML engineers use Ray’s APIs to request generic or specific Ray-supported accelerator types (e.g., NVIDIA_H100, NVIDIA_H200), abstracting Kubernetes manifests, GPU drivers, and network configurations. Platform teams can enable advanced networking like GPUDirect-TCPX on GKE for A3 VMs, which Ray workloads automatically leverage for enhanced GPU communication and data transfer, without ML engineer configuration. This ensures ML engineers achieve high experimentation velocity while platform teams maintain control over optimized infrastructure.</p><p>ML engineers connect to <a href="https://cloud.google.com/vertex-ai/docs/open-source/ray-on-vertex-ai/overview">Ray clusters on Vertex AI </a>via Ray Client for interactive development (e.g., Colab Enterprise notebooks) or submit Python scripts as batch jobs using the Ray Jobs API. Vertex AI manages Ray clusters, ensuring capacity and lifecycle, freeing ML engineers from operational overhead. Long-running Ray clusters benefit iterative development through data and image caching, reducing startup times for short-lived jobs.</p><p>While remote Ray environments use containers for consistency , the ML engineer’s l<em>ocal development</em> is simplified. They write and test Python code locally, then connect to the remote Ray cluster. The burden of local Dockerfile creation, image building, and registry management is abstracted or handled by the Vertex AI platform, accelerating development cycles.</p><h4>SkyPilot: Unified Abstraction for Any Infrastructure</h4><p><a href="https://docs.skypilot.co/en/latest/docs/index.html">SkyPilot</a> is an open-source framework providing a unified abstraction layer for running AI and batch workloads across diverse compute resources. It simplifies ML workflows by abstracting underlying infrastructure complexities across cloud providers or on-premises setups.</p><p>ML engineers define resource requirements (GPU types, TPUs, CPUs) in a simple YAML file or via CLI. SkyPilot intelligently identifies optimal infrastructure, provisions resources, runs the job, and manages its lifecycle, including reliable provisioning with automated retries and repeatable deployments. It can also be run in common <a href="https://github.com/llm-on-gke/skypilot-gke">ML development environments</a> such as Colab, Notebook, Workbench etc.</p><p>SkyPilot includes features for cost reduction and GPU availability, such as Autostop for idle resource cleanup, robust Spot instance support (3-6x cost savings with auto-recovery), and Intelligent scheduling for selecting the cheapest and most available infrastructure. It also facilitates reproducible data analysis environments, where ML engineers specify resources, data sources (e.g., Google Cloud Storage mounted via GCSFuse), software setup, and run commands in a single YAML file.</p><p>For high-performance GPU workloads on Google Cloud, SkyPilot enables <a href="https://github.com/skypilot-org/skypilot/tree/master/examples/gcp_gpu_direct_tcpx">GPUDirect-TCPX</a> on A3 VMs (H100) and <a href="https://github.com/skypilot-org/skypilot/tree/master/examples/gcp_gpu_direct_tcpx">RDMA</a> on A3Ultra/A4 (H200, B200 GPUs) via a single YAML parameter. This technology allows direct GPU-to-network interface communication, bypassing CPU bottlenecks and significantly enhancing large data transfers. SkyPilot abstracts the complex provisioning of network infrastructure, VM configuration, and GPUDirect-TCPX setup from ML engineers.</p><p>SkyPilot abstracts infrastructure: ML engineers define their environment and job <em>as code</em> (YAML) and interact via CLI. SkyPilot handles remote provisioning, environment setup, and workload execution. This frees ML engineers from manual local containerization for development iterations, as the remote execution environment is managed and consistent.</p><h4>XPK (Accelerated Processing Kit): GKE Orchestration for ML</h4><p><a href="https://github.com/AI-Hypercomputer/xpk">XPK </a>(Accelerated Processing Kit) is a CLI tool simplifying training job orchestration on accelerators (TPUs, GPUs) within GKE. It’s recommended for quick cluster creation for proofs of concept and testing.</p><p>XPK decouples capacity provisioning from job execution. Platform teams provision GKE clusters with reserved ML hardware once. ML engineers then submit training jobs as “workloads” to this shared pool, without re-provisioning for each job, reducing setup overhead. XPK achieves minimal job start times by leveraging Docker containers with pre-installed dependencies and cross-ahead-of-time compilation. Hardware returns to a shared pool upon job completion, maximizing utilization and enabling faster subsequent jobs.</p><p>XPK generates preconfigured, training-optimized GKE clusters and allows easy workload scheduling without deep Kubernetes expertise, abstracting Kubernetes manifests and kubectl commands. It supports various TPU (v4, v5e, v5p, Trillium) and GPU (A100, A3-Highgpu, A3-Mega, A3-Ultra, A4) types, and standard CPUs. It integrates with Google Cloud Storage solutions (Cloud Storage FUSE, Filestore, Parallelstore, Block storage) for flexible data access. XPK supports private GKE clusters for enhanced security and integrates with Vertex AI Tensorboard and Experiments for monitoring and tracking training runs.</p><p>XPK abstracts the Kubernetes layer, allowing ML engineers to interact with a simple CLI to submit code. XPK handles containerization and deployment to the remote GKE cluster. This enables ML engineers to focus on Python code and models, with the platform and XPK managing remote execution complexities.</p><p><strong>Table 2: ML Engineer Tools on Google Cloud (Ray, SkyPilot, XPK) — Capabilities and Benefits for Fast Iteration</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ot0hKkDtE0rCgHbcNZvSsQ.png" /></figure><p>Ray, SkyPilot, and XPK enable rapid iteration and ease of use for ML engineers through robust abstraction. Instead of manual Dockerfile creation or complex Kubernetes manifests, ML engineers interact with higher-level Python APIs, simple YAMLs, or specialized CLIs. These tools translate ML intent into necessary commands for platform-managed infrastructure. This unifies teams: ML engineers gain simplicity and velocity, while platform engineers retain control and visibility over managed, remote environments. This shifts the “containerization burden” from the developer’s local machine to the automated platform, fostering productive collaboration.</p><h3>IV. The Future of AI Infrastructure: Trends for Optimization and Collaboration</h3><p>The convergence of platform and ML engineering involves establishing practices and a culture of shared responsibility and continuous optimization. Several key trends shape this future, ensuring optimal balance of performance, reliability, and cost in AI infrastructure.</p><h3>MLOps as the Unifying Practice</h3><p>MLOps (Machine Learning Operations) integrates ML, software engineering, and operations to streamline the entire ML model lifecycle, from development to deployment, monitoring, and maintenance. It bridges data scientists/ML engineers (model builders) and operations/platform engineers (reliability enforcers).</p><p>Key MLOps components and practices include:</p><ul><li><strong>CI/CD for ML:</strong> Automates building, testing, and deploying ML models, ensuring consistent quality and rapid iteration.</li><li><strong>Versioning:</strong> Extends version control to datasets, hyperparameters, model configurations, and trained model weights for reproducibility and traceability.</li><li><strong>Model Monitoring and Management:</strong> Continuous monitoring of model performance and detection of data/concept drift, with tools to track metrics, detect anomalies, and trigger retraining.</li><li><strong>Infrastructure Management:</strong> Efficiently manages computational resources for ML models, leveraging cloud platforms for optimized utilization and cost.</li><li><strong>Collaboration and Reproducibility:</strong> Fosters teamwork, breaks down silos, and emphasizes consistent environments and clear documentation.</li><li><strong>Governance and Compliance:</strong> Addresses model explainability, bias detection, and audit trails, crucial for regulated industries.</li></ul><p>MLOps implementation leads to faster time-to-market, improved collaboration, enhanced model maintainability, and consistent performance. It defines the <em>process</em> and cultivates the <em>culture</em> for scalable enterprise AI, ensuring infrastructure capabilities inform model development and vice versa.</p><p><strong>Table 3: Key MLOps Practices for Platform-ML Collaboration</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPtCEbKjnsK_t2wGU1anRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjQD7vaAPe1QjiRRk3I48Q.png" /></figure><h3>FinOps for AI: Optimizing Cost and Value</h3><p>As AI workloads scale, cloud costs can become a barrier. FinOps provides a framework to make cost a first-class citizen in AI infrastructure decisions. It’s an operational framework and cultural shift integrating technology, finance, and business to drive financial accountability and accelerate business value from cloud transformation.</p><p>Key optimization areas within FinOps for AI include:</p><ul><li><strong>Resource Optimization:</strong> Ensures efficient utilization of compute, storage, and network resources for AI workloads, including right-sizing instances, managing idle resources, and optimizing data storage.</li><li><strong>Pricing Optimization:</strong> Leverages Google Cloud’s pricing models (committed use discounts, sustained use discounts, preemptible instances, <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/dws">Dynamic Workload Scheduler</a>) to reduce costs for predictable or fault-tolerant AI workloads.</li><li><strong>Architecture Optimization:</strong> Designs AI solutions with cost efficiency in mind, e.g., choosing between public foundation models, fine-tuning private models, or standard vs. provisioned capacity for LLMs.</li></ul><p>Google Cloud supports FinOps with native cost-management tools for real-time billing analysis, custom reporting dashboards, and automation scripts for guardrails and budget alerts. Mandatory labeling policies for all resources enable precise cost allocation and transparent reporting. FinOps success relies on strong partnership between IT finance, application development, and infrastructure teams.</p><p>FinOps for AI provides methodologies for AI cost planning, forecasting, and resource allocation. This empowers financial and engineering teams to understand cost drivers, adapt to innovations, and align financial outlays with business value. It transforms cost from a finance-only concern into a collaborative engineering objective.</p><h3>Green AI Initiatives: Sustainable AI Infrastructure</h3><p>The environmental impact of AI is a critical dimension of infrastructure optimization. Large-scale AI and Generative AI are energy-intensive, with data centers consuming significant and growing electricity.</p><p>Strategies for sustainable AI include:</p><ul><li><strong>Energy-Efficient AI Models:</strong> Optimizing algorithms to use less energy via model pruning, quantization, and knowledge distillation.</li><li><strong>Sustainable Data Centers:</strong> Investing in renewable energy-powered facilities and liquid cooling systems for GPUs and AI chips. Google uses AI-optimized energy management to cut data center consumption by 40%.</li><li><strong>Hardware-Software Co-Design:</strong> Building AI-specific chips and optimizing software for maximum energy efficiency.</li><li><strong>Edge AI Processing:</strong> Moving computations closer to data sources and users to reduce reliance on centralized cloud processing.</li><li><strong>Next-Gen Computing:</strong> Future breakthroughs like optical and quantum AI hold potential for dramatic energy reduction.</li></ul><p>While platform teams manage physical infrastructure, ML engineers’ choices in model architecture and training efficiency directly impact energy consumption, making Green AI a shared objective. Green AI is transitioning from a niche concern to a fundamental imperative, adding a crucial dimension to platform and ML engineer collaboration.</p><h3>Balancing Performance, Reliability, and Cost</h3><p>Optimal AI infrastructure involves a continuous balance between performance, reliability, and cost. High performance often requires significant compute, increasing costs. High reliability necessitates redundancy, monitoring, and automated recovery, adding complexity and potential cost. Aggressive cost-cutting can compromise performance and reliability.</p><p>MLOps provides the operational framework for reliability and performance. FinOps introduces financial accountability and optimization strategies for cost management. Green AI adds environmental sustainability, pushing for energy-efficient practices that can also lead to long-term cost savings.</p><p>By embracing these trends and leveraging Google Cloud’s comprehensive tools, organizations foster a collaborative environment where platform and ML engineers work in concert. This synergy enables deployment of AI systems that are powerful, innovative, robust, cost-efficient, and environmentally responsible, ultimately accelerating the realization of business value from AI investments.</p><p>Don’t forget to check out other GKE related resources on AI ML infrastructure offered by Google Cloud and check the resources included in the <a href="https://cloud.google.com/kubernetes-engine/docs/integrations/ai-infra">AI/ML orchestration on GKE</a> documentation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d2e7b57e900" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/bridging-the-divide-unifying-platform-and-ml-engineering-on-google-cloud-for-next-gen-ai-3d2e7b57e900">Bridging the Divide: Unifying Platform and ML Engineering on Google Cloud for Next-Gen AI</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed OpenSource LLM Fine-Tuning with LLaMA-Factory on GKE]]></title>
            <link>https://medium.com/google-cloud/distributed-opensource-llm-fine-tuning-with-llama-factory-on-gke-3bef8257051e?source=rss-c074bc07b3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bef8257051e</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Rick(Rugui) Chen]]></dc:creator>
            <pubDate>Mon, 08 Jul 2024 00:36:43 GMT</pubDate>
            <atom:updated>2024-07-08T03:54:09.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mAl0mKPpa_vdMKb1.png" /></figure><h3><strong>TLDR:</strong></h3><p>In this blog post, we explore the exciting potential of distributed fine-tuning for Large Language Models (LLMs) using open-source tools like LLaMA-Factory on Google Kubernetes Engine (GKE). LLMs have revolutionized natural language processing, but their vast size often demands extensive computational resources for customization. We’ll delve into how LLaMA-Factory, combined with GKE’s scalability, provides a streamlined solution for adapting these powerful models to specific tasks.</p><p><strong>Key Takeaways:</strong></p><ul><li><strong>Open-Source Power:</strong> LLaMA-Factory empowers researchers and developers to leverage pre-trained LLaMA models and efficiently fine-tune them on their own datasets. This democratization of LLM fine-tuning opens doors to a wide range of applications.</li><li><strong>Distributed Efficiency:</strong> We’ll discuss how to distribute the fine-tuning process across multiple nodes on GKE, significantly accelerating model adaptation and reducing resource constraints.</li><li><strong>GKE’s Scalability:</strong> GKE’s ability to dynamically allocate resources ensures optimal utilization during training, making it a cost-effective platform for even the most demanding LLM projects.</li></ul><h3>About LLaMA-Factory:</h3><p><a href="https://github.com/hiyouga/LLaMA-Factory">LLaMA-Factory </a>is an open source tool( with CLI and web user interface) for efficient fine-tuning of large language models. It supports various models, training approaches, and datasets. Some of the features include fine-tuning, quantization, and instruction tuning. LLaMA-Factory is open-source and available on GitHub.</p><p>Its unique capability is to integrate Training,Fine-tuning, inference together and also includes other frameworks such as Accelerate, BitsandBytes, DeepSpeed, vLLM, FlashAttention, Weights &amp;Biases etc. It quickly becomes one of most popular ML open source tool with 25K stars on Github.</p><p>To start with fine-tuning and inference with LLaMA-Factory on stand-alone local machine, you can use its WebUI following the<a href="https://colab.research.google.com/drive/1eRTPn37ltBbYsISy9Aw2NuI2Aq5CQrD9?usp=sharing"> colab</a> provided. Or you can use the CLI command through <a href="https://github.com/hiyouga/LLaMA-Factory?tab=readme-ov-file#getting-started">quick start</a></p><p>While the WebUI or CLI commands are convenient to run fine-tuning on stand-alone local machine, this blog will go one step deeper to explore how enterprises can leverage same tool for distributed open source LLM fine-tuning on multiple GKE nodes with Nvidia L4 accelerators.</p><h3>1. Prerequisites:</h3><p>Access to a Google Cloud project with the L4 GPU available and enough quota in the region you select.</p><p>A computer terminal with kubectl and the Google Cloud SDK installed. From the GCP project console you’ll be working with, you may want to use the included Cloud Shell as it already has the required tools installed.</p><p>Some models such as Llama3 will need Huggingface API token to download model files</p><p>Meta access request: <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/">https://ai.meta.com/resources/models-and-libraries/llama-downloads/</a> need register an email address to download</p><p>Go to Hugging face, create account account with same email registered in Meta request. Then find Llama 3 8Bmodel, fill out access request: <a href="https://huggingface.co/meta-llama/Meta-Llama-3-8B">https://huggingface.co/meta-llama/Llama-3–8b</a>.</p><p>Get Hugging face access token from your huggingface account profile settings, you will need it in next steps</p><p><strong>Setup project environments</strong></p><p>From your console, select the Google Cloud region and project, checking that there’s availability for L4 GPUs in the one that you end up selecting. The one used in this tutorial is us-central, where at the time of writing this article there was availability for L4 GPUs( alternatively, you can choose other regions with different GPU accelerator type available):</p><pre>export PROJECT_ID=&lt;your-project-id&gt;<br>export REGION=us-central1<br>export ZONE_1=${REGION}-a # You may want to change the zone letter based on the region you selected above<br>export ZONE_2=${REGION}-b # You may want to change the zone letter based on the region you selected above<br>export CLUSTER_NAME=fine-tuning-cluster<br>gcloud config set project &quot;$PROJECT_ID&quot;<br>gcloud config set compute/region &quot;$REGION&quot;<br>gcloud config set compute/zone &quot;$ZONE_1&quot;</pre><p>Then, enable the required APIs to create a GK cluster:</p><pre>gcloud services enable compute.googleapis.com container.googleapis.com</pre><p>Now, you need to go ahead download the <a href="https://github.com/llm-on-gke/vllm-inference/tree/main">source code repo</a> provided for this exercise:</p><pre>git https://github.com/llm-on-gke/LLaMA-Factory<br>cd LLaMA-Factory<br>export WORK_DIR=$(pwd)</pre><p>In this exercise, you will be using the default service account to create the cluster, you need to grant it the required permissions to store metrics and logs in Cloud Monitoring that you will be using later on:</p><pre>PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format=&#39;value(projectNumber)&#39;)<br>GCE_SA=&quot;${PROJECT_NUMBER}-compute@developer.gserviceaccount.com&quot;<br>for role in monitoring.metricWriter stackdriver.resourceMetadata.writer; do<br>  gcloud projects add-iam-policy-binding $PROJECT_ID --member=serviceAccount:${GCE_SA} --role=roles/${role}<br>done</pre><h3>2. Create GKE Cluster and Nodepools</h3><p><strong>Create a GKE Cluster</strong></p><p>Now, create a GKE cluster with a minimal default node pool, as you will be adding a node pool with L4 GPUs later on:</p><pre>gcloud container clusters create $CLUSTER_NAME \<br> --location &quot;$REGION&quot; \<br> --workload-pool &quot;${PROJECT_ID}.svc.id.goog&quot; \<br> --enable-image-streaming --enable-shielded-nodes \<br> --shielded-secure-boot --shielded-integrity-monitoring \<br> --enable-ip-alias \<br> --node-locations=&quot;$ZONE_1&quot; \<br> --workload-pool=&quot;${PROJECT_ID}.svc.id.goog&quot; \<br> --addons GcsFuseCsiDriver \<br> --no-enable-master-authorized-networks \<br> --machine-type n2d-standard-4 \<br> --num-nodes 1 --min-nodes 1 --max-nodes 3 \<br> --ephemeral-storage-local-ssd=count=1 \<br> --enable-ip-alias</pre><p><strong>Create 2 GKE Nodepools</strong></p><p>Create2 additional empty Spot node pool with regular (we use spot to illustrate, one nodepool for 1 L4 gpu per node, while the 2nd nodepool for 2 L4 GPU per node.</p><pre>gcloud container node-pools create l4-node-pool --cluster \<br>$CLUSTER_NAME --accelerator type=nvidia-l4,count=1,gpu-driver-version=latest   --machine-type g2-standard-8 \<br>--ephemeral-storage-local-ssd=count=1   --enable-autoscaling --enable-image-streaming   --num-nodes=0 --min-nodes=0 --max-nodes=3 \<br>--shielded-secure-boot   --shielded-integrity-monitoring --node-locations $ZONE_1,$ZONE_2 --region $REGION --spot</pre><pre>gcloud container node-pools create l4-2-node-pool --cluster \<br>$CLUSTER_NAME --accelerator type=nvidia-l4,count=2,gpu-driver-version=latest   --machine-type g2-standard-24 \<br>--ephemeral-storage-local-ssd=count=0   --enable-autoscaling --enable-image-streaming   --num-nodes=0 --min-nodes=0 --max-nodes=3 \<br>--shielded-secure-boot   --shielded-integrity-monitoring --node-locations $ZONE_1,$ZONE_2 --region $REGION --spot</pre><p>After a few minutes, check that the node pool was created correctly:</p><pre>gcloud container clusters get-credentials $CLUSTER_NAME --region $REGION --project $PROJECT_ID<br>gcloud container node-pools list --region $REGION --cluster $CLUSTER_NAME</pre><p>Also, create a secret to store hugging face API token</p><pre>export HF_TOKEN=&lt;paste-your-own-token&gt;<br>kubectl create secret generic huggingface --from-literal=&quot;HF_TOKEN=$HF_TOKEN&quot; </pre><h3>3. Build LLaMA-Factory container image:</h3><p><a href="https://github.com/llm-on-gke/LLaMA-Factory/blob/main/cloudbuild.yaml">cloudbuild.yam</a>l and <a href="https://github.com/llm-on-gke/LLaMA-Factory/blob/main/Dockerfile">Dockerfile </a>are included in downloaded repo here to build the container image, run the following to kick off container image build process:</p><pre>WORK_DIR=$(pwd)<br>gcloud artifacts repositories create gke-llm --repository-format=docker --location=$REGION<br>gcloud auth configure-docker $REGION-docker.pkg.dev<br>gcloud builds submit . --region=$REGION</pre><p>The build may last around 9–10 minutes</p><h3>4. Deploy sample LLM Fine-tuning jobs</h3><p>In this blog, we simply use <a href="https://jobset.sigs.k8s.io/docs/">jobset</a>( a kubernetes SIG project) in GKE to manage distributed workload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*MppVloV7qCLtLGEd.png" /></figure><p>And a basic pytorch based workload would look similar to the following:</p><pre>apiVersion: jobset.x-k8s.io/v1alpha2<br>kind: JobSet<br>metadata:<br>  name: pytorch<br>spec:<br>  replicatedJobs:<br>    - name: workers<br>      template:<br>        spec:<br>          parallelism: 2<br>          completions: 2<br>          backoffLimit: 0<br>          template:<br>           spec:<br>            containers:<br>            - name: pytorch<br>              image: gcr.io/k8s-staging-jobset/pytorch-resnet:latest<br>              ports:<br>              - containerPort: 3389<br>              env:<br>              - name: MASTER_ADDR<br>                value: &quot;pytorch-workers-0-0.pytorch&quot;<br>              - name: MASTER_PORT<br>                value: &quot;3389&quot;<br>              command:<br>              - bash<br>              - -xc<br>              - |<br>                torchrun --nproc_per_node=1 --master_addr=$MASTER_ADDR --master_port=$MASTER_PORT resnet.py --backend=gloo</pre><p>Let’s install jobset controller in GKE with the following command:</p><pre>VERSION=v0.5.2<br>kubectl apply --server-side -f https://github.com/kubernetes-sigs/jobset/releases/download/$VERSION/manifests.yaml</pre><p>Sample distributed fine-tuning jobs are included under gke folder from downloaded source repo:</p><ol><li>gke/<a href="https://github.com/llm-on-gke/LLaMA-Factory/blob/main/gke/fine-tune-2x1-l4.yaml">fine-tune-2x1-l4.yaml</a> — Total of 2 L4: 2 nodes, with 1 L4/ node</li><li>gke/<a href="https://github.com/llm-on-gke/LLaMA-Factory/blob/main/gke/fine-tune-2x2-l4.yaml">fine-tune-2x2-l4.yaml</a> — Total of 4 L4: 2 nodes, with 2 L4/ node</li><li>gke/<a href="https://github.com/llm-on-gke/LLaMA-Factory/blob/main/gke/fine-tune-3x1-l4.yaml">fine-tune-3x1-l4.yaml</a> — Total of 3L4: 3 nodes, with 1 L4/ node</li></ol><p>Update line 42 on container image path with your own project:</p><blockquote>image: us-east1-docker.pkg.dev/rick-vertex-ai/gke-llm/llama-factory:latest</blockquote><p>Also, update line 28 to link to an existing cloud storage bucket to save data and output</p><blockquote>bucketName: “mlops-repo”</blockquote><p>When you are ready, kick off the following fine-tuning jobs one at a time,</p><pre>kubectl delete jobset pytorch<br>kubectl apply -f gke/fine-tune-2x1-l4.yaml</pre><pre>kubectl delete jobset pytorch<br>kubectl apply -f gke/fine-tune-2x2-l4.yaml</pre><pre>kubectl delete jobset pytorch<br>kubectl apply -f gke/fine-tune-3x1-l4.yaml</pre><p>The following are the summary of 3 fine-tuning jobs:</p><p>LLM LoRA <a href="https://github.com/llm-on-gke/LLaMA-Factory/blob/main/examples/train_lora/llama3_lora_sft.yaml">fine-tuning settings</a>,</p><p>### model<br>model_name_or_path: meta-llama/Meta-Llama-3–8B-Instruct</p><p>### dataset<br>dataset: identity,alpaca_en_demo<br>template: llama3<br>cutoff_len: 1024<br>max_samples: 1000<br>overwrite_cache: true<br>preprocessing_num_workers: 16</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bghoHbG0yd9VZb-6E20yeA.png" /></figure><h3>Conclusion</h3><p>This post tries to demonstrate how to perform distributed Open source LLM models fine-tuning such as Llama 3 8B using LLaMA-Factory on GKE is flexible and straightforward.</p><p>LLaMA Factory offers an enterprise-scalable solution for fine-tuning a wide range of LLMs on custom datasets. By leveraging the power of Google Kubernetes Engine (GKE), businesses can distribute fine-tuning jobs across a cluster of machines, enabling them to train models on massive datasets. This empowers enterprises to unlock the full potential of LLMs and custom data, leading to improved performance and new business opportunities.Don’t forget to check out other GKE related resources on AI ML infrastructure offered by Google Cloud and check the resources included in the <a href="https://cloud.google.com/kubernetes-engine/docs/integrations/ai-infra">AI/ML orchestration on GKE</a> documentation.</p><p>For your reference, the code snipptes listed in this blog can be find in this <a href="https://github.com/llm-on-gke/LLaMA-Factory">source code repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bef8257051e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/distributed-opensource-llm-fine-tuning-with-llama-factory-on-gke-3bef8257051e">Distributed OpenSource LLM Fine-Tuning with LLaMA-Factory on GKE</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamline AI ML Model Development on GKE with Skypilot and Vertex AI Workbench]]></title>
            <link>https://medium.com/google-cloud/streamline-ai-ml-model-development-on-gke-with-skypilot-and-vertex-ai-workbench-453729a8897c?source=rss-c074bc07b3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/453729a8897c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gke]]></category>
            <dc:creator><![CDATA[Rick(Rugui) Chen]]></dc:creator>
            <pubDate>Tue, 28 May 2024 04:28:58 GMT</pubDate>
            <atom:updated>2024-05-28T13:52:00.559Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5nrzjRJLsolPOTdCvt9zoQ.png" /></figure><h3><strong>Introduction</strong></h3><p><a href="https://skypilot.readthedocs.io/en/latest/docs/index.html">SkyPilot</a> is transforming the AI/ML development landscape by enabling seamless transitions from local testing to remote training on a wide array of cloud resources. This open-source framework empowers data scientists and ML engineers to streamline their workflows, accelerate model development, and focus on building better models.</p><p>SkyPilot simplifies identifying and utilizing optimal resources for AI/ML workloads across various cloud provider, regions, and a mix of GPU types and machine types. This means you can effortlessly leverage the most cost-effective and performance-efficient resources for your specific needs, whether you’re experimenting with different models or scaling up for production.</p><p>With SkyPilot, you can seamlessly integrate local development with remote training. You can effortlessly test your Jupyter notebooks on small instances and then launch large-scale training jobs on your chosen cloud infrastructure with minimal changes. This seamless transition eliminates the friction between development and deployment, allowing you to iterate faster and experiment more without worrying AI infra resources.</p><p><strong>Key advantages of using SkyPilot:</strong></p><ul><li><strong>Effortless resource discovery:</strong> Identify and utilize the best cloud resources for your AI/ML workload across different providers, regions, GPU types, and machine types.</li><li><strong>Seamless workflow:</strong> Effortlessly move from local testing on Jupyter notebooks to remote training on your chosen cloud infrastructure and platforms.</li><li><strong>Rapid iteration:</strong> Quickly update and execute code changes with less concern on code containerization, thus accelerating the development cycle.</li><li><strong>Optimized resource utilization and cost reduction:</strong> SkyPilot intelligently allocates resources to minimize cloud computing expenses.</li></ul><p>This blog walk through examples on how to setup SkyPilot on GCP Vertex AI Workbench, and kick off Ray training task in mutiple ways(Jupyter notebook, Skypilot Task YAML, or CLI), while connect to GKE platform running distributed job with GPU resources.</p><h3>1. Prepare your environment</h3><p>You can use <a href="https://cloud.google.com/shell">Cloud Shell</a> to manage resources hosted on Google Cloud. Cloud Shell comes preinstalled with the software you’ll need for this tutorial, including <a href="https://kubernetes.io/docs/reference/kubectl/">kubectl</a> and <a href="https://cloud.google.com/sdk/gcloud">gcloud CLI</a>.</p><p>To set up your environment with Cloud Shell, follow these steps:</p><ol><li>In the Google Cloud console, launch a Cloud Shell session by clicking</li><li><strong>Activate Cloud Shell</strong> in the <a href="http://console.cloud.google.com/">Google Cloud console</a>. This launches a session in the bottom pane of Google Cloud console.</li><li>Set the default environment variables:</li></ol><pre>gcloud config set project PROJECT_ID<br>export PROJECT_ID=$(gcloud config get project)<br>export REGION=REGION</pre><p>Replace the following values:</p><ul><li>PROJECT_ID: Your Google Cloud <a href="https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects">project ID</a>.</li><li>REGION: A region that supports the accelerator type you want to use, for example, us-central1, us-east1.</li></ul><p>Also, you may want to clone the github repo has the sample code:</p><pre>git clone https://github.com/llm-on-gke/skypilot-gke.git<br>cd skypilot-gke</pre><h3>2. Create and configure Google Cloud resources</h3><p>We use GKE Standard cluster to walk through Skypilot examples.</p><p>In Cloud Shell, run the following command:</p><pre>CLUSTER_NAME=skypilotcluster<br>gcloud beta container --project &quot;${PROJECT_ID}&quot; clusters create &quot;${CLUSTER_NAME}&quot; --zone &quot;us-central1-c&quot; --cluster-version &quot;1.29&quot; --machine-type &quot;n1-standard-4&quot; --scopes &quot;https://www.googleapis.com/auth/devstorage.read_only&quot;,&quot;https://www.googleapis.com/auth/logging.write&quot;,&quot;https://www.googleapis.com/auth/monitoring&quot;,&quot;https://www.googleapis.com/auth/servicecontrol&quot;,&quot;https://www.googleapis.com/auth/service.management.readonly&quot;,&quot;https://www.googleapis.com/auth/trace.append&quot; --num-nodes=1 --min-nodes=0 --max-nodes=3 --logging=SYSTEM,WORKLOAD --monitoring=SYSTEM --enable-ip-alias --network &quot;projects/${PROJECT_ID}/global/networks/default&quot; --subnetwork &quot;projects/${PROJECT_ID}/regions/us-central1/subnetworks/default&quot; --no-enable-intra-node-visibility --default-max-pods-per-node &quot;110&quot; --security-posture=standard --workload-vulnerability-scanning=disabled --no-enable-master-authorized-networks --addons HorizontalPodAutoscaling,HttpLoadBalancing,GcePersistentDiskCsiDriver --enable-autoupgrade --enable-autorepair --max-surge-upgrade 1 --max-unavailable-upgrade 0 --enable-managed-prometheus --enable-shielded-nodes --node-locations &quot;us-central1-c&quot;</pre><p>Run the following command to create a Nvidia-tesla-t4 nodepool:</p><pre>gcloud beta container --project &quot;${PROJECT_ID}&quot; node-pools create &quot;testla-t4&quot; --cluster &quot;${CLUSTER_NAME}&quot; --zone &quot;us-central1-c&quot; --machine-type &quot;n1-standard-4&quot; --accelerator &quot;type=nvidia-tesla-t4,count=1,gpu-driver-version=latest&quot; --scopes &quot;https://www.googleapis.com/auth/devstorage.read_only&quot;,&quot;https://www.googleapis.com/auth/logging.write&quot;,&quot;https://www.googleapis.com/auth/monitoring&quot;,&quot;https://www.googleapis.com/auth/servicecontrol&quot;,&quot;https://www.googleapis.com/auth/service.management.readonly&quot;,&quot;https://www.googleapis.com/auth/trace.append&quot; --num-nodes=2 --min-nodes=0 --max-nodes=3  --enable-autoupgrade --enable-autorepair --max-surge-upgrade 1 --max-unavailable-upgrade 0 --node-locations &quot;us-central1-c&quot; --spot</pre><h3>3. Prepare Workbench Instance with Skypilot</h3><p>In this example, we create Workbench instance with customized container image to pre-install dependencies including Skypilot and kubectl.</p><p>Update workbench/cloudbuild.yaml file with your own Artifact Registry path to store Container image path:</p><pre>steps:<br>- name: &#39;gcr.io/cloud-builders/docker&#39;<br>  args: [ &#39;build&#39;, &#39;-t&#39;, &#39;us-east1-docker.pkg.dev/$PROJECT_ID/gke-llm/skypilot-bench:latest&#39;, &#39;.&#39; ]<br>images:<br>- &#39;us-east1-docker.pkg.dev/$PROJECT_ID/gke-llm/skypilot-bench:latest&#39;</pre><p>Then run the following commands to build Workbench container image:</p><pre>cd workbench<br>gcloud builds submit .</pre><p>Run the following Cloud Shell command to create a Vertex Workbench instance( replace with your own container image path), when the container image build completed successfully,</p><pre>gcloud workbench instances create skypilot-wb-instance --container-repository=us-east1-docker.pkg.dev/$PROJECT_ID/gke-llm/skypilot-bench --container-tag=latest --machine-type=n1-standard-4 --location=us-central1-b</pre><p>Go to Vertex AI Workbench console, and click OPEN JUPITERLAB when the Workbench instance started successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8W9LQlAn8VR34oBIIzYW0Q.png" /></figure><p>Click Terminal button in the JupiterLab launch screen.</p><p>In terminal shell window, run the following commands to initialize GCP and GKE connections(update PROJECT_ID):</p><pre>gcloud init<br>gcloud auth application-default login<br>gcloud config set project PROJECT_ID<br>gcloud auth application-default set-quota-project PROJECT_ID<br>gcloud container clusters get-credentials $CLUSTER_NAME --zone us-central1-c --project rick-vertex-ai</pre><p>Then validate GCP and GKEconnection with Skypilot:</p><pre>sky check</pre><p>Make sure the following output from skypilot connections:</p><p>🎉 Enabled clouds 🎉</p><p>✔ GCP</p><p>✔ Kubernetes</p><p>Run the following command to download sample repo inside terminal shell:</p><pre>git clone https://github.com/llm-on-gke/skypilot-gke.git<br>cd skypilot-gke</pre><h3>4. Test training workload with Skypilot Task YAML</h3><p>check ray-train.yaml file can be used to run Ray distributed training workload with <a href="https://skypilot.readthedocs.io/en/latest/reference/yaml-spec.html">Skypilot task yaml</a>:</p><p><a href="https://github.com/llm-on-gke/skypilot-gke/blob/main/ray-train/ray-train.yaml">ray-train.yaml</a></p><pre>resources:<br>  accelerators: {T4:1,L4:1}<br>  cloud: kubernetes<br>  disk_tier: best<br>  <br>num_nodes: 2<br><br>workdir: .<br>#file_mounts:<br>#    /checkpoint:<br>#        name: skypilot-train<br>#        mode: MOUNT<br><br>setup: |<br>  conda activate ray<br>  if [ $? -ne 0 ]; then<br>    conda create -n ray python=3.10 -y<br>    conda activate ray<br>  fi<br><br>  pip install &quot;ray[train]&quot;<br>  pip install tqdm<br>  pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118<br>  #git clone https://github.com/llm-on-gke/skypilot-gke.git<br>  sudo mkdir ./checkpoint<br>run: |<br>  sudo chmod 777 -R /var/tmp<br>  conda activate ray<br>  head_ip=`echo &quot;$SKYPILOT_NODE_IPS&quot; | head -n1`<br>  num_nodes=`echo &quot;$SKYPILOT_NODE_IPS&quot; | wc -l`<br>  if [ &quot;$SKYPILOT_NODE_RANK&quot; == &quot;0&quot; ]; then<br>    ps aux | grep ray | grep 6379 &amp;&gt; /dev/null || ray start --head  --disable-usage-stats --port 6379<br>    sleep 5<br>    python ray-train/train.py --num-workers $num_nodes<br>  else<br>    sleep 5<br>    ps aux | grep ray | grep 6379 &amp;&gt; /dev/null || ray start --address $head_ip:6379 --disable-usage-stats<br>  fi</pre><p>This simple Task yaml resource file defines the following components on how to run the task:</p><ol><li>resources: accelerator type and count, we specifiy “cloud: kubernetes” to only narraw down to use GPU resources on GKE.</li><li>num-nodes: number of GKE pods</li><li>workdir: path of workdir, where local resources will be pulled into running GKE pods</li><li>setup: scripts to setup running dependencies, pull git repo resources</li><li>run: task run, can call other python file</li></ol><p>Run the following Skypilot CLI command in Jupiter Instance Terminal shell window to kick off training task:</p><pre>sky launch ray-train/ray-train.yaml -c ray</pre><p>In the prompt to confirm Launching a new cluster ‘ray’, type “Y” and clicke Enter key</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4ZUZI6PblUE0ARq4YTaNA.png" /></figure><p>after around 6 minutes, the training task will be completed with outputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IDf_Yz4X6z8Ql4g0fLM6A.png" /></figure><p>you may release the resources by run the following command:</p><pre>sky down ray</pre><h3>5. Test training workload with Skypilot Python API and Jupiter notebook</h3><p>A lot of Data scientists and ML engineers may prefer to use Python API and Jupiter notebook to perform Model development such as iterative training tasks and promote to different environments. I prepared a sample Jupiter notebook to demonstrate to accomplish Skypilot tasks and run training jobs inside GKE.</p><p>In same JupiterLab window left side panel, open /skypilot-gke/ray-train/ folder, click “<a href="https://github.com/llm-on-gke/skypilot-gke/blob/main/ray-train/ray-dist-train.ipynb">ray-dist-train.ipynb</a>”, then choose “Open with Notebook” :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86tgZbVG0YK0-tqx8EILug.png" /></figure><p>Run through the steps in this notebook, and you will get exactly same output in previous step.</p><p>Upon to this point, we successfully completed Ray distributed Pytorch training task through both Skypilot Task YAML and Jupiter Notebook, and you may see a lot of potentials of Skypilot on front end AI ML Model development with Jupiter notebooks and backend resources on AI Infrastructure such as GKE platform.</p><h3>5. Clean up</h3><p>To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.</p><p>To avoid incurring charges to your Google Cloud account for the resources that you created in this guide, run the following command:</p><pre>gcloud container clusters delete ${CLUSTER_NAME} \<br> --zone &quot;us-central1-c&quot;<br>gcloud workbench instances delete skypilot-wb-instance --location=us-central1-b</pre><h3>Conclusion</h3><p>The integration of SkyPilot and GKE provides a golden path for data scientists and ML engineers to streamline AI workloads and accelerate model development. By abstracting away infrastructure complexities, SkyPilot empowers teams to focus on their core tasks while leveraging the scalability and reliability of GKE. This unified ecosystem not only minimizes the learning curve associated with AI infrastructure but also fosters collaboration between AI/ML practitioners and platform teams. With the ability to seamlessly transition from local development in Jupyter notebooks to distributed training on GKE, SkyPilot truly unlocks the potential of AI/ML, making it more accessible and efficient for everyone.</p><p>Don’t forget to check out other GKE related resources on AI ML infrastructure offered by Google Cloud and check the resources included in the <a href="https://cloud.google.com/kubernetes-engine/docs/integrations/ai-infra">AI/ML orchestration on GKE</a> documentation.</p><p>For your reference, the code snippets listed in this blog can be find in this <a href="https://github.com/llm-on-gke/skypilot-gke/">source code repo</a>, for more Skypilot information and code examples, please refer to official <a href="https://github.com/skypilot-org/skypilot">Skypilot repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=453729a8897c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/streamline-ai-ml-model-development-on-gke-with-skypilot-and-vertex-ai-workbench-453729a8897c">Streamline AI ML Model Development on GKE with Skypilot and Vertex AI Workbench</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serve Sentence Transformer Embedding Models in GKE Autopilot]]></title>
            <link>https://medium.com/google-cloud/serve-sentence-transformer-embedding-models-in-gke-autopilot-ac08bb476cce?source=rss-c074bc07b3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac08bb476cce</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[sentence-transformers]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Rick(Rugui) Chen]]></dc:creator>
            <pubDate>Sat, 18 May 2024 16:02:59 GMT</pubDate>
            <atom:updated>2024-05-20T08:10:59.094Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QleCCX9NdxVtGl4I.jpg" /></figure><h3><strong>Embeddings: The Key to Unlocking LLM &amp; RAG Potential</strong></h3><p>In the world of Large Language Models (LLMs) and Retrieval Augmented Generation (RAG), embeddings are the unsung heroes. These numerical representations of text into multi-dimensional vectors, often generated by powerful models like Sentence Transformers, enable semantic search, clustering, and much more. But to truly harness their power, you need a scalable, efficient serving infrastructure as part of enterprise GenAI backend eco-systems(LLM models, Vector database, Embedding Model etc). That’s where Google Kubernetes Engine (GKE) Autopilot comes in. In this blog series, we’ll dive into how to deploy your Sentence Transformer model on GKE Autopilot, ensuring your LLM or RAG application has the robust backend it needs to thrive.</p><h3>1. Prepare your environment</h3><p>You can use <a href="https://cloud.google.com/shell">Cloud Shell</a> to manage resources hosted on Google Cloud. Cloud Shell comes preinstalled with the software you’ll need for this tutorial, including <a href="https://kubernetes.io/docs/reference/kubectl/">kubectl</a> and <a href="https://cloud.google.com/sdk/gcloud">gcloud CLI</a>.</p><p>To set up your environment with Cloud Shell, follow these steps:</p><ol><li>In the Google Cloud console, launch a Cloud Shell session by clicking</li><li><strong>Activate Cloud Shell</strong> in the <a href="http://console.cloud.google.com/">Google Cloud console</a>. This launches a session in the bottom pane of Google Cloud console.</li><li>Set the default environment variables:</li></ol><pre>gcloud config set project PROJECT_ID<br>export PROJECT_ID=$(gcloud config get project)<br>export REGION=REGION<br>export CLUSTER_NAME=embeddings<br>export HF_TOKEN=HF_TOKEN</pre><p>Replace the following values:</p><ul><li>PROJECT_ID: Your Google Cloud <a href="https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects">project ID</a>.</li><li>REGION: A region that supports the accelerator type you want to use, for example, us-central1, us-east1.</li><li>HF_TOKEN: The Hugging Face token you can copy from your huggingface account.</li></ul><p>Also, you may want to clone the github repo has the sample code:</p><pre>git clone https://github.com/llm-on-gke/sentence_transformers_serving.git<br>cd sentence_transformers_serving</pre><h3>2. Create and configure Google Cloud resources</h3><p>We use GKE Autopilot cluster for a fully managed Kubernetes experience.</p><p>In Cloud Shell, run the following command:</p><pre>gcloud container clusters create-auto ${CLUSTER_NAME} \<br>  --project=${PROJECT_ID} \<br>  --region=${REGION} \<br>  --release-channel=rapid \<br>  --cluster-version=1.29</pre><p>GKE creates an Autopilot cluster with environment that allocate resources requested by the deployed workloads.</p><h4>Create a Kubernetes secret for Hugging Face credentials</h4><p>In Cloud Shell, do the following:</p><ol><li>Configure kubectl to communicate with your cluster:</li></ol><pre>gcloud container clusters get-credentials ${CLUSTER_NAME} --location=${REGION}</pre><p>2. Create a Kubernetes Secret that contains the Hugging Face token:</p><pre>kubectl create secret generic hf-secret \<br>--from-literal=hf_api_token=$HF_TOKEN \<br>--dry-run=client -o yaml | kubectl apply -f -</pre><h3>3. Serve Small embedding model with Huggingface Text Emedding Inference(TEI)</h3><p><a href="https://huggingface.co/docs/text-embeddings-inference/en/index">Huggingface TEI</a> is great start point to serve embedding models, since it provides out of box container image for both CPU and GPU. But currently it provides only <a href="https://huggingface.co/docs/text-embeddings-inference/en/supported_models#supported-embeddings-models">supported models</a> :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*loE6eYd5ijuYODC20t6c7A.png" /></figure><p>Huggingface TEI also provides out of box container images based on hardware architecture to faciliate deploy to any container platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OxwqI4o2HLg6E-6OADKI3Q.png" /></figure><p>With our testing, the TEI supported models are relatively small size, and good enough to try out on CPU nodes.</p><p>Check out the <a href="https://github.com/llm-on-gke/sentence_transformers_serving/blob/master/hf-tei.yaml">hf-tei.yaml</a> included in the repo download directory:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: hf-tei<br>spec:<br>  selector:<br>    matchLabels:<br>      app: hf-tei<br>  template:<br>    metadata:<br>      labels:<br>        app: hf-tei<br>    spec:<br>      volumes:<br>       - name: data<br>         emptyDir: {}<br>       - name: dshm<br>         emptyDir:<br>              medium: Memory<br>      nodeSelector:<br>         cloud.google.com/compute-class: &quot;Balanced&quot;<br>      containers:<br>      - name: embeddings<br>        image: ghcr.io/huggingface/text-embeddings-inference:cpu-1.2<br>        imagePullPolicy: Always<br>        resources:<br>            requests:<br>                cpu: &quot;2&quot;<br>                memory: &quot;2Gi&quot;<br>        env:<br>            - name: model-id<br>              value: WhereIsAI/UAE-Large-V1<br>            - name: shm-size<br>              value: 1g<br>        ports:<br>        - containerPort: 80<br>        volumeMounts:<br>            - mountPath: /dev/shm<br>              name: dshm<br>            - mountPath: /data<br>              name: data<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: tei-embedding<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: hf-tei<br>  ports:<br>  - protocol: TCP<br>    port: 8080<br>    targetPort: 80</pre><p>You may update the value of model-id in:</p><pre>- name: model-id<br>              value: WhereIsAI/UAE-Large-V1</pre><p>Also the resource requirements can be changed:</p><pre>resources:<br>            requests:<br>                cpu: &quot;2&quot;<br>                memory: &quot;2Gi&quot;</pre><p>You may also add more environment variables into hf-tei.yaml based on Huggingface <a href="https://huggingface.co/docs/text-embeddings-inference/en/cli_arguments">TEI CLI reference</a> document</p><p>Then deploy the embedding model to GKE autopilot cluster</p><pre>kubectl apply -f hf-tei.yaml</pre><p>You may see the following output if the model is running properly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kk2KUPAOSCORn7XG0MijSA.png" /></figure><p>And you may validate text embedding with:</p><pre>curl SERVICE_IP:8080/predict \<br>    -X POST \<br>    -d &#39;{&quot;inputs&quot;:&quot;It is great day&quot;}&#39; \<br>    -H &#39;Content-Type: application/json&#39;</pre><h3>4. Serve any Sentence Transformer embedding model with GPU in GKE Autopilot Cluster</h3><p>Unfortunately,most of embedding models listed in <a href="https://huggingface.co/spaces/mteb/leaderboard"><em>MTEB leaderboard</em></a><em> are not supported by Huggingface TEI.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5fEVg1pin_rDyevKyY4LIg.png" /></figure><p>Now, it is time to build your own embedding model serving container image since you need to pick up one of more powerful model listed in MTEB leaderboard.</p><p>In the repo downloaded, a sample is provided to build your own container image and serve any of the sentence transformer embedding model based on Huggingface sentence-transfomer library.</p><p>app.py is the main serving template:</p><pre>import os<br><br>from flask import Flask, jsonify, request<br>from sentence_transformers import SentenceTransformer<br>#from sentence_transformers.util import cos_sim<br>from waitress import serve<br><br>app = Flask(__name__)<br><br><br>@app.route(&#39;/embed&#39;, methods=[&#39;POST&#39;])<br>def encode():<br>    data = request.json<br>    sentences = data.get(&quot;inputs&quot;, [])<br>    #batch_size = int(os.environ.get(&quot;batch_size&quot;, 8))<br>    embeddings = model.encode(sentences)<br>    #embeddings = encoder.encode(sentences, batch_size=batch_size)<br>    embeddings = [x.tolist() for x in embeddings]<br><br>    return jsonify(embeddings)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    model_name_or_path = os.environ.get(&#39;model_name&#39;, &quot;bert-base-nli-stsb-mean-tokens&quot;)<br>    print(model_name_or_path)<br>    model = SentenceTransformer(model_name_or_path=model_name_or_path, trust_remote_code=True)<br>    #encoder = SentenceTransformer(model_name_or_path=model_name_or_path)<br><br>    serve(app, host=&quot;0.0.0.0&quot;, port=5000)</pre><p>Before you start to build the embedding model serving container image, update artifact registry path in the cloudbuild.yaml file:</p><pre>steps:<br>- name: &#39;gcr.io/cloud-builders/docker&#39;<br>  args: [ &#39;build&#39;, &#39;-t&#39;, &#39;us-east1-docker.pkg.dev/$PROJECT_ID/gke-llm/sentence-transformer:latest&#39;, &#39;.&#39; ]<br>images:<br>- &#39;us-east1-docker.pkg.dev/$PROJECT_ID/gke-llm/sentence-transformer:latest&#39;<br>  # Push the container image to Artifact Registry, get sha256 of the image</pre><p>You may create Artifact Registry repo if you dont have one yet.</p><p>Included a Dockerfile, no need to update :</p><pre>FROM continuumio/miniconda3:23.3.1-0<br><br># Install OpenCV3 Python bindings<br>#RUN sudo apt-get update<br><br># Create a working directory<br>#RUN mkdir /app<br><br># Add requirements file<br>WORKDIR /app/<br>ADD requirements.txt /app/<br><br># Install requirements<br><br>RUN pip install -r requirements.txt<br><br># Download Sentence Transformers Model<br>RUN python -c &quot;import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ.get(&#39;model_name&#39;, &#39;bert-base-nli-stsb-mean-tokens&#39;));&quot;<br><br># Move required resources                     <br>ADD app.py   /app/<br><br># Run flask api<br>ENTRYPOINT [&quot;python&quot;]<br>CMD [&quot;app.py&quot;]</pre><p>Simply run the following command to kick of the model serving container image:</p><pre>gcloud builds submit .</pre><p>Once the container image built successfully, go ahead update the embeddings.yaml file:</p><pre>#gcloud container node-pools create embeddings-pool --cluster $CLUSTER_NAME <br>#--accelerator type=nvidia-tesla-t4,count=1,gpu-driver-version=latest   --machine-type n1-standard-4 --ephemeral-storage-local-ssd=count=1   --enable-autoscaling --enable-image-streaming   --num-nodes=1 --min-nodes=0 --max-nodes=3 --shielded-secure-boot   --shielded-integrity-monitoring --node-version=1.29 --node-locations us-east1-c --region us-east1 --spot<br><br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: embedding-serve<br>spec:<br>  selector:<br>    matchLabels:<br>      app: embedding-serve<br>  template:<br>    metadata:<br>      labels:<br>        app: embedding-serve<br>    spec:<br>      volumes:<br>       - name: data<br>         emptyDir: {}<br>       - name: dshm<br>         emptyDir:<br>              medium: Memory<br>      nodeSelector:<br>        cloud.google.com/gke-accelerator: nvidia-tesla-t4<br>        cloud.google.com/compute-class: &quot;Accelerator&quot;<br>        cloud.google.com/gke-accelerator-count: &quot;1&quot;<br>        cloud.google.com/gke-gpu-driver-version: &quot;latest&quot;<br>      containers:<br>      - name: embeddings<br>        image: us-east1-docker.pkg.dev/rick-vertex-ai/gke-llm/sentence-transformer:latest #replace with your sentence transformer image path<br>        resources:<br>            limits:<br>              cpu: &quot;2&quot;<br>              memory: &quot;8Gi&quot;<br>              nvidia.com/gpu: &quot;1&quot;<br>            requests:<br>              cpu: &quot;2&quot;<br>              memory: &quot;8Gi&quot;<br>              nvidia.com/gpu: &quot;1&quot;<br>        env:<br>            - name: model_name<br>              value: Alibaba-NLP/gte-large-en-v1.5<br>            <br>            - name: shm-size<br>              value: 1g<br>        ports:<br>        - containerPort: 5000<br>        volumeMounts:<br>            - mountPath: /dev/shm<br>              name: dshm<br>            - mountPath: /data<br>              name: data<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: embedding-serve<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: embedding-serve<br>  ports:<br>  - protocol: TCP<br>    port: 8080<br>    targetPort: 5000</pre><p>You may update the compute resource requirements:</p><pre>nodeSelector:<br>        cloud.google.com/gke-accelerator: nvidia-tesla-t4 #replace with GPU accelerator type<br>        cloud.google.com/compute-class: &quot;Accelerator&quot;<br>        cloud.google.com/gke-accelerator-count: &quot;1&quot; # number of GPU<br>        cloud.google.com/gke-gpu-driver-version: &quot;latest&quot; # GPU driver version<br><br><br>resources:<br>            limits:<br>              cpu: &quot;2&quot; # cpu requirements<br>              memory: &quot;8Gi&quot; # memory requirements <br>              nvidia.com/gpu: &quot;1&quot; # GCPU count<br>            requests:<br>              cpu: &quot;2&quot;<br>              memory: &quot;8Gi&quot;<br>              nvidia.com/gpu: &quot;1&quot;</pre><p>Please be noted, by default, GKE autopilot will assign same size of limit and requests, you can use one or the other.</p><p>You may update the image path based on where you built container image,</p><pre>- name: embeddings<br>        image: us-east1-docker.pkg.dev/rick-vertex-ai/gke-llm/sentence-transformer:latest #replace with your sentence transformer image path</pre><p>Lastly, don’t forget to update the huggingface model id:</p><pre>env:<br>            - name: model_name<br>              value: Alibaba-NLP/gte-large-en-v1.5</pre><p>We choose Alibaba-NLP/gte-large-en-v1.5 for testing, due to its relatively small memory requirements(1.62G) and higher ranking on MTEB leaderboard( no. 9), with relatively high dimensions(1024) and max token(8192).</p><p>When everything is ready, you may run the following to deploy model in GKE Autopilot,</p><pre>kubectl apply -f embeddings.yaml</pre><p>Run the following commad to check whether deploy and service running properly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UHAvB4A20_xv_mejZBv0lg.png" /></figure><p>Finally, run a quick validation:</p><pre> curl 104.196.213.131:8080/embed  -X POST \<br>    -d &#39;{&quot;inputs&quot;:&quot;What is Deep Learning?&quot;}&#39; \<br>    -H &#39;Content-Type: application/json&#39;</pre><p>And you may see output within 1s like following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-WR9qwMm-pFQJvR0YZ-vA.png" /></figure><h3>5. Clean up</h3><p>To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.</p><p>To avoid incurring charges to your Google Cloud account for the resources that you created in this guide, run the following command:</p><p>gcloud container clusters delete ${CLUSTER_NAME} \<br> --region=${REGION}</p><h3>Conclusion</h3><p>Serving Sentence Transformer embedding models on GKE Autopilot simplifies the operational overhead of managing your AI infrastructure. With GKE autopilot handles infrastructure and workload scaling, resource allocation, and health monitoring, you can focus on building and refining enterprise GenAI applications. This streamlined approach empowers you to deliver powerful LLM, RAG, and other AI-driven experiences to your users seamlessly. From frontend interaction to backend processing with complex models, GKE Autopilot offers a unified platform for your entire GenAI stack. As the demand for AI-powered solutions grows, you can trust GKE Autopilot to scale effortlessly, ensuring your application remains responsive and reliable.</p><p>Don’t forget to check out other GKE related resources on AI ML infrastructure offered by Google Cloud and check the resources included in the <a href="https://cloud.google.com/kubernetes-engine/docs/integrations/ai-infra">AI/ML orchestration on GKE</a> documentation.</p><p>For your reference, the code snippets listed in this blog can be find in this <a href="https://github.com/llm-on-gke/sentence_transformers_serving">source code repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac08bb476cce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/serve-sentence-transformer-embedding-models-in-gke-autopilot-ac08bb476cce">Serve Sentence Transformer Embedding Models in GKE Autopilot</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High-performance Stable Diffusion XL Inference on GKE and TPU v5e with MaxDiffusion]]></title>
            <link>https://medium.com/google-cloud/high-performance-stable-diffusion-xl-inference-on-gke-and-tpu-with-maxdiffusion-97a786c06257?source=rss-c074bc07b3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/97a786c06257</guid>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Rick(Rugui) Chen]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 15:48:08 GMT</pubDate>
            <atom:updated>2024-04-29T14:36:23.744Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMtm5KjiZqqoNW6GAJeJnQ.png" /></figure><h3><strong>Introduction</strong></h3><p>Self managed Image/video generation inference services from Stable Diffusion models can be more challenging than text generation LLM models. At <a href="https://cloud.google.com/blog/products/compute/accelerating-ai-inference-with-google-cloud-tpus-and-gpus">Google Next,</a> we unveiled MaxDiffusion, a game-changing collection of open-source diffusion-model reference implementations built on JAX, designed for performance, scalability, and customization.</p><p>Take the next step in your AI journey with this in-depth blog. I will walk you through a practical example of implementing Stable Diffusion XL (SDXL) inference on Google Kubernetes Engine (GKE) and <a href="https://cloud.google.com/tpu/docs/v5e">Google Cloud TPU v5e</a> using MaxDiffusion.</p><h3>Prerequisites</h3><p>Access to a Google Cloud project with the TPU v5e available and enough quota in the region you select.</p><p>A computer terminal with kubectl and the Google Cloud SDK installed. From the GCP project console you’ll be working with, you may want to use the included Cloud Shell as it already has the required tools installed.</p><p><strong>Setup project environments</strong></p><p>From your console, select the Google Cloud region and project, checking that there’s availability and quota for Compute Engine TPU v5e in the one that you end up selecting. The one used in this tutorial is us-east1, where at the time of writing this article there was availability for TPU v5e( alternatively, you can choose other regions with different TPU v5e accelerator type available):</p><pre>export PROJECT_ID=&lt;your-project-id&gt;<br>export REGION=us-east1<br>export ZONE_1=${REGION}-c # You may want to change the zone letter based on the region you selected above<br><br>export CLUSTER_NAME=tpu-cluster<br>gcloud config set project &quot;$PROJECT_ID&quot;<br>gcloud config set compute/region &quot;$REGION&quot;<br>gcloud config set compute/zone &quot;$ZONE_1&quot;</pre><p>Then, enable the required APIs to create a GK cluster:</p><pre>gcloud services enable compute.googleapis.com container.googleapis.com</pre><p>Now, you need to go ahead download the <a href="https://github.com/llm-on-gke/sdxl-tpu">source code repo</a> provided for this exercise:</p><pre>git clone https://github.com/llm-on-gke/sdxl-tpu.git<br>cd sdxl-tpu</pre><h3>Create GKE Cluster and Nodepools</h3><p>Now, create a GKE standard cluster with a minimal default node pool, as you will be adding a node pool with TPU v5e later on:</p><pre>gcloud container clusters create $CLUSTER_NAME --location ${REGION} \<br>  --workload-pool ${PROJECT_ID}.svc.id.goog \<br>  --enable-image-streaming --enable-shielded-nodes \<br>  --shielded-secure-boot --shielded-integrity-monitoring \<br>  --enable-ip-alias \<br>  --node-locations=$REGION-b \<br>  --workload-pool=${PROJECT_ID}.svc.id.goog \<br>  --addons GcsFuseCsiDriver   \<br>  --no-enable-master-authorized-networks \<br>  --machine-type n2d-standard-4 \<br>  --cluster-version 1.29 \<br>  --num-nodes 1 --min-nodes 1 --max-nodes 3 \<br>  --ephemeral-storage-local-ssd=count=2 \<br>  --scopes=&quot;gke-default,storage-rw&quot;</pre><p>Create an additional Spot node pool (we use spot to save costs, you can remove spot option depends on different use case) with TPU accelerator:</p><pre>gcloud container node-pools create $CLUSTER_NAME-tpu \<br>--location=$REGION --cluster=$CLUSTER_NAME --node-locations=$ZONE_1 \<br>--machine-type=ct5lp-hightpu-1t --num-nodes=0 --spot --node-version=1.29 \<br>--ephemeral-storage-local-ssd=count=0 --enable-image-streaming \<br>--shielded-secure-boot --shielded-integrity-monitoring \<br>--enable-autoscaling --total-min-nodes 0 --total-max-nodes 2 --location-policy=ANY</pre><p>Note how easy enabling TPU in GKE nodepool with proper TPU machine type. Please refer to the following page, for details on <a href="https://cloud.google.com/tpu/docs/tpus-in-gke#v5e">TPU v5e machine type</a> and <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/tpus#choose-tpu-standard">configuration</a> sections.</p><p><em>— machine-type</em></p><p>ct5lp-hightpu-1t is single host with 1x1 = total of 1 TPU chips</p><p>After a few minutes, check that the node pool was created correctly:</p><pre>gcloud container clusters get-credentials $CLUSTER_NAME --region $REGION --project $PROJECT_ID<br>gcloud container node-pools list --region $REGION --cluster $CLUSTER_NAME</pre><h3>MaxDiffusion inference server sample code</h3><p>The sample Stable Diffusion XL <a href="https://github.com/google/maxdiffusion/blob/main/src/maxdiffusion/generate_sdxl_replicated.py">inference code</a> template from MaxDiffusion repo is updated with FastAPI and uvicorn libraries to fit for API requests.</p><p>The updated <a href="https://github.com/llm-on-gke/sdxl-tpu/blob/main/build/server/main.py">Stable Diffusion XL Inference Code</a> sample provided here for reference.</p><ol><li>Add FastAPI and Uvicorn libraries</li><li>Add logging, health check</li><li>Expose /generate as Post methods for REST API requests</li><li>HuggingFace Stable Diffusion XL Model: stabilityai/stable-diffusion-xl-base-1.0</li></ol><p>To make the Stable Diffusion XL inference more efficient, we compile the pipeline._generate function, and pass all parameters to the function and tell JAX which are static arguments,</p><p><em>default_seed = 33</em></p><p><em>default_guidance_scale = 5.0</em></p><p><em>default_num_steps = 40</em></p><p><em>width = 1024</em></p><p><em>height = 1024</em></p><p>The following main exposed SDXL inference method,</p><pre>@app.post(&quot;/generate&quot;)<br>async def generate(request: Request):<br>    LOG.info(&quot;start generate image&quot;)<br>    data = await request.json()<br>    prompt = data[&quot;prompt&quot;]<br>    LOG.info(prompt)<br>    prompt_ids, neg_prompt_ids = tokenize_prompt(prompt, default_neg_prompt)<br>    prompt_ids, neg_prompt_ids, rng = replicate_all(prompt_ids, neg_prompt_ids, default_seed)<br>    g = jnp.array([default_guidance_scale] * prompt_ids.shape[0], dtype=jnp.float32)<br>    g = g[:, None]<br>    LOG.info(&quot;call p_generate&quot;)<br>    images = p_generate(prompt_ids, p_params, rng, g, None, neg_prompt_ids)<br><br>    # convert the images to PIL<br>    images = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:])<br>    images=pipeline.numpy_to_pil(np.array(images))<br>    buffer = io.BytesIO()<br>    LOG.info(&quot;Save image&quot;)<br>    for i, image in enumerate(images):<br>        if i==0:<br>          image.save(buffer, format=&quot;PNG&quot;)<br>    #await images[0].save(buffer, format=&quot;PNG&quot;)<br><br>    # Return the image as a response<br>    return Response(content=buffer.getvalue(), media_type=&quot;image/png&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>   uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000, reload=False, log_level=&quot;debug&quot;)</pre><p>For illustration purposes, we return the bytes of first generated image in PNG format to the frontend app only.</p><h3>Build Stable Diffusion XL Inference Container Image</h3><p>Next, let’s build the Inference server container image with cloud build.</p><p>Sample <a href="https://github.com/llm-on-gke/sdxl-tpu/blob/main/build/server/Dockerfile">Docker file </a>and <a href="https://github.com/llm-on-gke/sdxl-tpu/blob/main/build/server/cloudbuild.yaml">cloudbuild.yaml</a> already in the repo,</p><p>Dockerfile:</p><pre>FROM python:3.11-slim<br>WORKDIR /app<br>RUN apt-get -y update<br>RUN apt-get -y install git<br>COPY requirements.txt ./<br>RUN python -m pip install --upgrade pip<br>RUN pip install -U &quot;jax[tpu]&quot; -f https://storage.googleapis.com/jax-releases/libtpu_releases.html<br>RUN pip install -r requirements.txt<br>RUN pip install git+https://github.com/google/maxdiffusion.git<br>COPY main.py ./<br>EXPOSE 8000<br>ENTRYPOINT [&quot;python&quot;, &quot;main.py&quot;]</pre><p>Notes: we may not have maxdiffusion pip package to be downloaded yet, thus, RUN pip install git+https://github.com/google/maxdiffusion.git is used to download MaxDiffusion from source directly.</p><p>cloudbuild.yaml:</p><pre>steps:<br>- name: &#39;gcr.io/cloud-builders/docker&#39;<br>  args: [ &#39;build&#39;, &#39;-t&#39;, &#39;us-east1-docker.pkg.dev/$PROJECT_ID/gke-llm/max-diffusion:latest&#39;, &#39;.&#39; ]<br>images:<br>- &#39;us-east1-docker.pkg.dev/$PROJECT_ID/gke-llm/max-diffusion:latest&#39;</pre><p><a href="https://github.com/llm-on-gke/sdxl-tpu/blob/1bf43d4a5f3cb281a164f46f59bef70ffc23b83e/build/requirements.txt">requirements.txt</a>:</p><p>Note: replace destination of container image as your own environment</p><p>Run the following commands to kick of container image builds:</p><pre>cd build/server<br>gcloud builds submit .</pre><h3>Deploy Stable Diffusion XL Inference Server in GKE</h3><p>In the downloaded code repo root directory, you can check the following kubernetes deployment resource files,</p><p><a href="https://github.com/llm-on-gke/sdxl-tpu/blob/main/serve_sdxl_v5e.yaml">serve_sdxl_v5e.yaml</a>:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: stable-diffusion-deployment<br>spec:<br>  selector:<br>    matchLabels:<br>      app: max-diffusion-server<br>  replicas: 1  # number of nodes in node-pool<br>  template:<br>    metadata:<br>      labels:<br>        app: max-diffusion-server<br>    spec:<br>      nodeSelector:<br>        cloud.google.com/gke-tpu-topology: 1x1 #  target topology<br>        cloud.google.com/gke-tpu-accelerator: tpu-v5-lite-podslice<br>      volumes:<br>       - name: dshm<br>         emptyDir:<br>              medium: Memory<br>      containers:<br>      - name: serve-stable-diffusion<br>        image: us-east1-docker.pkg.dev/rick-vertex-ai/gke-llm/max-diffusion:latest<br>        securityContext:<br>          privileged: true<br>        env:<br>        - name: MODEL_NAME<br>          value: &#39;stable_diffusion&#39;<br>        ports:<br>        - containerPort: 8000<br>        resources:<br>          requests:<br>            google.com/tpu: 1  # TPU chip request<br>          limits:<br>            google.com/tpu: 1  # TPU chip request<br>        volumeMounts:<br>            - mountPath: /dev/shm<br>              name: dshm<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: max-diffusion-server<br>  labels:<br>    app: max-diffusion-server<br>spec:<br>  type: ClusterIP<br>  ports:<br>    - port: 8000<br>      targetPort: http<br>      name: http-max-diffusion-server<br>  selector:<br>    app: max-diffusion-server</pre><p>To be noted, in deployment specs settings related to TPU accelerators which has to match v5e machine types (ct5lp-hightpu-1t has 1x1=1 total TPU chips):</p><pre>nodeSelector:<br>        cloud.google.com/gke-tpu-topology: 1x1 #  target topology<br>        cloud.google.com/gke-tpu-accelerator: tpu-v5-lite-podslice<br><br>resources:<br>          requests:<br>            google.com/tpu: 1  # TPU chip request<br>          limits:<br>            google.com/tpu: 1  # TPU chip request</pre><p>We use type: ClusterIP to expose inference service availabe to GKE cluster only. Update this file with proper container image name and location,</p><p>Run the following command to deploy Stable Diffusion Inference server to GKE:</p><pre>gcloud container clusters get-credentials $CLUSTER_NAME $REGION<br>kubectl apply -f serve_sdxl_v5e.yaml<br>kubectl get svc max-diffusion-server. </pre><p>It may take 7–8 minutes to wait for the spot nodepool provisioning, model loading and initial pipeline compilation. Note the service IP need to be referenced by later section</p><p>You may use the following command to validate Stable Diffusion Inference Server setup properly,</p><pre>SERVER_URL=XXXX<br>kubectl run -it busybox --image radial/busyboxplus:curl<br><br><br>curl SERVER_URL:8000</pre><h3>Deploy WebApp</h3><p>A simple client webapp provided under build/webapp directory with following files included:</p><p><a href="https://github.com/llm-on-gke/sdxl-tpu/blob/main/build/webapp/app.py">app.py</a> ( main python file), <a href="https://github.com/llm-on-gke/sdxl-tpu/blob/main/build/webapp/Dockerfile"><em>Dockerfile</em></a><em> , </em><a href="https://github.com/llm-on-gke/sdxl-tpu/blob/main/build/webapp/cloudbuild.yaml">cloudbuild.yaml </a>, <a href="https://github.com/llm-on-gke/sdxl-tpu/blob/main/build/webapp/requirements.txt">requirements.txt</a></p><p>You may update cloudbuild.yaml file with your own container image destination accordingly.</p><p>Run the following command to build testing webapp container image using cloud build:</p><pre>cd build/webapp<br>gcloud builds submit</pre><p>Once the webapp image build completed, you may go ahead deploy frontend webapp to test Stable Diffusion XL inference server.</p><p>serve_sdxl_client.yaml:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: max-diffusion-client<br>spec:<br>  selector:<br>    matchLabels:<br>      app: max-diffusion-client<br>  template:<br>    metadata:<br>      labels:<br>        app: max-diffusion-client<br>    spec:<br>      containers:<br>      - name: webclient<br>        image: us-east1-docker.pkg.dev/rick-vertex-ai/gke-llm/max-diffusion-client:latest<br>        env:<br>          - name: SERVER_URL<br>            value: &quot;http://CLusterIP:8000&quot;<br>        resources:<br>          requests:<br>            memory: &quot;128Mi&quot;<br>            cpu: &quot;250m&quot;<br>          limits:<br>            memory: &quot;256Mi&quot;<br>            cpu: &quot;500m&quot;<br>        ports:<br>        - containerPort: 5000<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: max-diffusion-client-service<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: max-diffusion-client<br>  ports:<br>  - port: 8080<br>    targetPort: 5000</pre><p>We use type: LoadBalancer to expose webapp to external public. Update this file with proper container image name and SERVER_URL endpoint location from. Run the following command to deploy frontend webapp:</p><pre>kubectl apply -f serve_sdxl_client.yaml</pre><p>Once the webapp deployment completed,</p><p>you may test text to image capabilities from UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqpnCWEc0cD8Htp-xHJsqQ.png" /></figure><p>Image generated after 3–5s( displaying only first image from inference), which is quite performance efficient for Cloud TPU v5e based on Single-host serving for one single v5e chips.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FLiVu7tnryf3Vkw_hpeT8Q.png" /></figure><h3>Cleanups</h3><p>Don’t forget to clean up the resources created in this article once you’ve finished experimenting with Stable Diffusion inference on GKE and TPU, as keeping the cluster running for a long time can incur in important costs. To clean up, you just need to delete the GKE cluster:</p><pre>gcloud container clusters delete $CLUSTER_NAME - region $REGION</pre><h3>Conclusion</h3><p>With the streamlined process showcased in this post, deploying inference servers for open-source image generation/vision models like Stable Diffusion XL on GKE and TPU has never been simpler or more efficient with MaxDiffusion to serve JAX models directly, without need for download and conversion JAX model to Tensorflow compatible model for <a href="https://cloud.google.com/tpu/docs/tpus-in-gke#run_jax_stable_diffusion_e2e_serving_demo">Stable Diffusion Inference Serving in GKE and TPU</a></p><p>Don’t forget to check out other GKE related resources on AI ML infrastructure offered by Google Cloud and check the resources included in the <a href="https://cloud.google.com/kubernetes-engine/docs/integrations/ai-infra">AI/ML orchestration on GKE</a> documentation.</p><p>For your reference, the code snipptes listed in this blog can be find in this <a href="https://github.com/llm-on-gke/sdxl-tpu">source code repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97a786c06257" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/high-performance-stable-diffusion-xl-inference-on-gke-and-tpu-with-maxdiffusion-97a786c06257">High-performance Stable Diffusion XL Inference on GKE and TPU v5e with MaxDiffusion</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM&FinOps: Cost Optimization Options to Run High Performance AI/ML Workloads on GKE in Google…]]></title>
            <link>https://medium.com/google-cloud/llm-finops-cost-optimization-options-to-run-high-performance-ai-ml-workloads-on-gke-in-google-96f79d79c51b?source=rss-c074bc07b3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/96f79d79c51b</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[finops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rick(Rugui) Chen]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 04:07:36 GMT</pubDate>
            <atom:updated>2024-03-25T16:37:38.335Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>LLM&amp;FinOps: Cost Optimization Options to Run High Performance AI/ML Workloads on GKE in Google Cloud</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*Zb-JlT6NlMHab8StB4sabA.jpeg" /></figure><h3><strong>1. Introduction &amp; The Cost Challenge</strong></h3><p>Artificial intelligence (AI) and machine learning (ML) have revolutionized industries, but their success comes with an often overlooked challenge: cost. Training sophisticated deep learning models and running large-scale inference tasks demands significant computational resources. This translates directly into substantial cloud infrastructure expenses.</p><p>Google Kubernetes Engine (GKE) provides a robust platform for deploying and managing AI/ML workloads at scale. However, without careful optimization, the costs associated with GPUs (Graphics Processing Units) and TPUs (Tensor Processing Units) can quickly become a hurdle. This blog series aims to equip you with the practical strategies to optimize costs while ensuring high performance for your GPU/TPU-powered AI/ML workloads running on GKE.</p><h3><strong>2. Hardware GPU Accelerator Selection and Cost Considerations</strong></h3><p>Choosing the right GPU-equipped instances is a foundational step toward cost optimization. Google Cloud offers various NVIDIA GPU options tailored to different workload requirements in GKE including:</p><ul><li><strong>NVIDIA A100(40gb,80gb), H100 GPUs:</strong> These represent the cutting-edge in GPU acceleration, designed for computationally demanding deep learning models. They excel in large-scale training tasks with complex architectures.</li><li><strong>NVIDIA L4 GPUs:</strong> delivers a versatile platform to accelerate Deep Learning, Graphics and Video processing applications in the Cloud and at the Edge.</li><li><strong>NVIDIA T4 GPUs:</strong> These GPUs offer a balance of cost and performance, making them ideal for inference workloads and less intensive training tasks.</li></ul><p><strong>Key Factors in GPU Selection:</strong></p><ul><li><strong>Model Complexity:</strong> Deep neural networks with millions of parameters and extensive training datasets often necessitate the raw power of A100 or H100 GPUs.</li><li><strong>Training vs. Inference:</strong> Inference workloads tend to be less computationally demanding and might be better served by the cost-effectiveness of L4 o4 T4 GPUs.</li><li><strong>Batch Size:</strong> Larger batch sizes during training generally demand more GPU memory. Align your GPU choice with your model’s batching requirements.</li><li><strong>Regional Pricing:</strong> GPU instance costs can differ across Google Cloud regions. Factor in regional pricing alongside performance needs and data locality.</li></ul><p><strong>“Right-Sizing” Nodes</strong></p><p>The key to cost optimization lies in avoiding both over-provisioning and under-provisioning your GPU nodes. Here’s how to strike the right balance:</p><ul><li><strong>Understand Workload Demands:</strong> Before making a GPU selection, leverage tools like Cloud Monitoring to track existing workloads. Analyze historical GPU utilization metrics to get a clear picture of your resource needs.</li><li><strong>Avoid Over-provisioning:</strong> Choosing a GPU that is far more powerful than your workloads required leads to wasted resources and unnecessary expense. Can Nvidia L4 or T4 is good enough before higher end A100, H100 is considered?</li><li><strong>Prevent Under-provisioning:</strong> Selecting a GPU instance that cannot handle your model’s computational needs will severely impact training or inference times, leading to productivity bottlenecks and potentially higher costs in the long run.</li></ul><h3>3. Hardware Cost Considerations - TPU</h3><p>Tensor Processing Units (TPUs) are Google’s custom-designed ASICs (Application-Specific Integrated Circuits) optimized for accelerating machine learning workloads built with TensorFlow. For TensorFlow-heavy projects, TPUs can provide significant performance gains and potential cost savings.</p><p><strong>When to Choose TPUs</strong></p><p><strong>TensorFlow Focus:</strong> TPUs offer the greatest benefits when your core model development and training pipelines are built extensively using TensorFlow. Consider porting PyTorch models using tools like ‘torch-xla’ if necessary.</p><p><strong>Large-Scale Training:</strong> TPUs excel in scenarios where you’re training large and complex models over substantial datasets.</p><p><strong>Fine-tuning and Inference</strong>: TPU optimized for transformer-based, text-to-image and CNN-based training, fine-tuning, and serving (inference)</p><p><strong>TPU Nodepool Options in GKE:</strong></p><p><a href="https://cloud.google.com/tpu/docs/tpus-in-gke#single-host">Single-host TPU slice</a>, contains one or more independent TPU VMs. Each of these VMs has a TPU device connected to it. While the VMs within a single-host slice node pool can communicate over Data Center Network (DCN), the TPUs attached to the VMs are not interconnected</p><p><a href="https://cloud.google.com/tpu/docs/tpus-in-gke#multi-host">Multi-host TPU slice</a> , contains two or more <em>interconnected</em> TPU VMs. Each VM has a TPU device connected to it. The TPUs in a multi-host slice are connected over a high speed interconnect (ICI)</p><p><strong>TPU machine types for GKE node pools:</strong></p><p><strong>TPU v5e</strong>: is a combined training and inference product. Training jobs are optimized for throughput and availability while inference jobs are optimized for latency</p><p><strong>TPU v4 and v5p: </strong>TPU v4 slice, use the ct4p-hightpu-4t machine type which has one host and contains 4 chips. TPU v5p slice, use the ct5p-hightpu-4t machine type which has one host and contains 4 chips</p><p><strong>Adopting TPUs</strong></p><ul><li><strong>TensorFlow Compatibility:</strong> Ensure your TensorFlow models and custom code are compatible with TPUs. Google provides detailed guides and tools to assist in the process.</li><li><strong>GKE Integration:</strong> GKE seamlessly integrates with TPUs. Provisioning TPUs involves requesting and managing TPU pods within your Kubernetes cluster.</li></ul><h3>4. GPU Discount Options and Strategies</h3><p>Google Cloud offers several ways to reduce the costs associated with GPU instances:</p><ul><li><strong>Committed Use Discounts (CUDs):</strong> If you have predictable long-term workloads (often a characteristic of production inference deployments), commit to a specific GPU instance type and region in exchange for substantial discounts for 1-year or 3-year terms. CUDs are most beneficial when you have a clear understanding of your ongoing stable 24X7 resource needs.</li><li><strong>Spot VMs:</strong> Spot VMs offer the same GPU instances as standard on-demand instances but at deepest discounted prices among all the options. These instances can be preempted by Google at any time with a 30-second notice after 24 hour usage, making them ideal for fault-tolerant workloads, certain types of training, or tasks that can resume from checkpoints.</li><li><strong>Preemptible VMs:</strong> Similar to Spot VMs, preemptible VMs provide discounted GPU instances with the risk of preemption. Preemptible VMs have a maximum lifespan of 24 hours and are generally a good fit for batch processing tasks or exploratory workloads.</li></ul><p>Unlike the normal compute resources, GPU related compute resources does not qualify for Sustained Use Discount (SUD) and spending based Flexible CUD discounts.</p><p><strong>Considerations When Choosing Discount Options</strong></p><ul><li><strong>Workload Predictability:</strong> CUDs necessitate a good understanding of your long-term GPU usage patterns. If needs are variable or unpredictable, Spot or Preemptible VMs might be better choices.</li><li><strong>Fault Tolerance:</strong> Spot and Preemptible VMs come with the risk of interruptions. Evaluate whether your workloads can tolerate restarts or if they require the reliability of on-demand instances.</li><li><strong>Time Sensitivity:</strong> If your workloads are time-critical, Spot VMs or Preemptible VMs might introduce undesirable delays due to the possibility of preemption.</li></ul><p><strong>Incorporating Discounts into your Strategy</strong></p><p>Consider a tiered or hybrid approach based on your AI/ML workloads:</p><ul><li><strong>Production Inference:</strong> Prioritize reliability; use on-demand instances or CUDs for critical inference serving.</li><li><strong>Exploratory Training:</strong> Leverage the cost-effectiveness of Spot VMs or Preemptible VMs for experimentation and prototyping.</li><li><strong>Batch-Oriented Training:</strong> If your training tasks support restarting from checkpoints, Spot and Preemptible VMs can offer significant cost savings.</li></ul><h3><strong>5. GPU Resource Sharing Options — Multi-instance GPU</strong></h3><p>A powerful concept called <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/gpus-multi">Multi-Instance GPU</a>(MIG). MIG technology enables the partitioning of a single physical GPU into multiple smaller, physical isolated GPU instances. This option only availabe to nvidia-tesla-a100, nvidia-a100-80gb, or nvidia-h100-80gb.</p><p>Multi-instance GPU partitions: The A100 GPU and H100 GPU consist of seven compute units and eight memory units, which can be partitioned into GPU instances of varying sizes. A GPU partition size of 1g.5gb refers to a GPU instance with one compute unit (1/7th of streaming multiprocessors on the GPU), and one memory unit (5 GB). See the <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/gpus-multi#multi-instance_gpu_partitions">partition table</a> for details</p><p><strong>Benefits of MIG</strong></p><ul><li><strong>Improved Cost-Efficiency:</strong> MIG is particularly valuable for scenarios where a single, full-fledged GPU might be overkill for specific tasks. Smaller workloads can run on cost-effective MIG slices.</li><li><strong>Inference Optimization:</strong> Inference workloads often benefit from running multiple models concurrently. MIG allows you to serve several inference models on smaller GPU slices derived from a single physical GPU.</li><li><strong>Efficient Experimentation:</strong> Researchers and teams prototyping models can leverage MIG to run lightweight training tasks on multiple slices, improving GPU utilization.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkFX8rqz3Oc49_bKbTjAIw.png" /></figure><p><strong>Configuring MIG in GKE</strong></p><p>Use Gcloud command to create a GKE stand cluster to set gpu-partition-size and other accelerator settings:</p><pre>gcloud container clusters create CLUSTER_NAME  \<br>    --project=PROJECT_ID  \<br>    --zone ZONE  \<br>    --cluster-version=CLUSTER_VERSION  \<br>    --accelerator type=nvidia-tesla-a100,count=1,gpu-partition-size=1g.5gb,gpu-driver-version=DRIVER_VERSION  \<br>    --machine-type=a2-highgpu-1g  \<br>    --num-nodes=1</pre><p>Then, you can use nodeselctor to request specific MIG profiles within your Kubernetes deployment configurations. Here’s an example:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: cuda-simple<br>spec:<br>  replicas: 7<br>  selector:<br>    matchLabels:<br>      app: cuda-simple<br>  template:<br>    metadata:<br>      labels:<br>        app: cuda-simple<br>    spec:<br>      nodeSelector:<br>        cloud.google.com/gke-gpu-partition-size: 1g.5gb<br>      containers:<br>      - name: cuda-simple<br>        image: nvidia/cuda:11.0.3-base-ubi7<br>        command:<br>        - bash<br>        - -c<br>        - |<br>          /usr/local/nvidia/bin/nvidia-smi -L; sleep 300<br>        resources:<br>          limits:<br>            nvidia.com/gpu: 1</pre><h3>6. GPU Resource Sharing Options— Time-sharing</h3><p><a href="https://cloud.google.com/kubernetes-engine/docs/how-to/timesharing-gpus">Time-sharing</a> lets multiple AI ML workload share a single physical GPU attached to a node. Using GPU time-sharing in GKE lets you more efficiently use your attached GPUs and save running costs. Allow to share any GPU between workloads</p><h4><strong>Benefits:</strong></h4><ul><li>Allow to share any GPU between workloads</li><li>Request fractional GPU units.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fOPRrArf7KrR70ercoYeaQ.png" /></figure><h4>Use cases:</h4><p>Time-shared GPUs are ideal for running workloads that don’t need to use high amounts of GPU resources all the time, such as the following:</p><ul><li>Homogeneous workloads with low GPU requests</li><li>Burstable GPU workloads</li></ul><p>Examples of these types of workloads include the following:</p><ul><li>Rendering</li><li>Inference</li><li>Small-scale machine learning model training</li></ul><p><strong>Configuring Time-Sharing GPU in GKE</strong></p><p>Use Gcloud command to create a GKE nodepool, with right parameters:</p><p>gpu-sharing-strategy=time-sharing</p><p>max-shared-clients-per-gpu=Number_OF_CLIENTS_PER_GPU</p><pre>gcloud container node-pools create NODEPOOL_NAME \<br>    --cluster=CLUSTER_NAME \<br>    --machine-type=MACHINE_TYPE \<br>    --region=COMPUTE_REGION \<br>    --accelerator=type=GPU_TYPE,count=GPU_QUANTITY,gpu-sharing-strategy=time-sharing,max-shared-clients-per-gpu=CLIENTS_PER_GPU,gpu-driver-version=DRIVER_VERSION</pre><p>Then, specify workload deployment yaml configuration,</p><ol><li>Add a nodeSelector to your Pod manifest for the following labels:</li></ol><p>cloud.google.com/gke-gpu-sharing-strategy: time-sharing: selects nodes that use time-sharing GPUs.</p><p>cloud.google.com/gke-max-shared-clients-per-gpu: &quot;CLIENTS_PER_GPU&quot;: selects nodes that allow a specific number of containers to share the underlying GPU.</p><p>2. Add the nvidia.com/gpu=1 GPU resource request to your container specification, in spec.containers.resources.limits</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: cuda-simple<br>spec:<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: cuda-simple<br>  template:<br>    metadata:<br>      labels:<br>        app: cuda-simple<br>    spec:<br>      nodeSelector:<br>        cloud.google.com/gke-gpu-sharing-strategy: time-sharing<br>        cloud.google.com/gke-max-shared-clients-per-gpu: &quot;3&quot;<br>      containers:<br>      - name: cuda-simple<br>        image: nvidia/cuda:11.0.3-base-ubi7<br>        command:<br>        - bash<br>        - -c<br>        - |<br>          /usr/local/nvidia/bin/nvidia-smi -L; sleep 300<br>        resources:<br>          limits:<br>            nvidia.com/gpu: 1</pre><h3>7. Intelligent workload orchestration: obtain right resources only when you really need them</h3><p>When managing diverse AI/ML workloads on GKE with varying resource requirements (GPUs, TPUs, CPUs), intelligent workload orchestration becomes crucial for optimizing costs and ensuring efficient resource utilization. This involves the ability to dynamically provision the necessary resources at the right time for each job, eliminating idle periods and overspending.</p><p>Google Cloud offers two primary tools together to facilitate intelligent workload orchestration for automation of AI/ML jobs:</p><ul><li><strong>Dynamic Workload Scheduler (DWS/ProvisioningReques</strong>t)</li><li><strong>Kueue</strong></li></ul><p><strong>DWS:</strong> large-scale batch workloads that can run during off-peak hours with defined GPU capacity management conditions. These workloads might be deep learning model training or a simulations that needs large amounts of GPUs with atomic provisioning model.</p><p><strong>Use Cases for Dynamic Workload Scheduler (DWS)</strong></p><ul><li>You have limited or no <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/consuming-reservations">reserved</a> GPU capacity and you want to improve obtainability of GPU resources.</li><li>Your workload is time-flexible and your use case can afford to wait(from few minutes to few hours) to get all the requested capacity, for example when GKE allocates the GPU resources outside of the busiest hours.</li><li>For workloads requiring multiple nodes, your workload can’t start running until all GPU nodes are provisioned and ready at the same time. For example, distributed machine learning training.</li><li>GKE provisions all GPUs nodes at the same time.</li><li>Batch workloads last up to 7 days only</li></ul><p><strong>Kueue</strong> is an open source Cloud Native Job scheduler that works with the default Kubernetes scheduler, the Job controller, and the cluster autoscaler to provide an end-to-end batch system. Kueue implements Job queueing, deciding when Jobs should wait and when they should start, based on quotas and a hierarchy for sharing resources fairly among teams.</p><p>These are main steps to automate batch workload with DWS and Kueue as illustrated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*av3YZ6yeN7T-uR3TPUmVmA.png" /></figure><p>Sample workload job yaml:</p><pre>apiVersion: batch/v1<br>kind: Job<br>metadata:<br>  name: sample-job<br>  namespace: default<br>  labels:<br>    kueue.x-k8s.io/queue-name: dws-local-queue<br>spec:<br>  parallelism: 1<br>  completions: 1<br>  suspend: true<br>  template:<br>    spec:<br>      nodeSelector:<br>        cloud.google.com/gke-nodepool: dws-nodepool<br>      tolerations:<br>      - key: &quot;nvidia.com/gpu&quot;<br>        operator: &quot;Exists&quot;<br>        effect: &quot;NoSchedule&quot;<br>      containers:<br>      - name: dummy-job<br>        image: gcr.io/k8s-staging-perf-tests/sleep:v0.0.3<br>        args: [&quot;120s&quot;]<br>        resources:<br>          requests:<br>            cpu: &quot;100m&quot;<br>            memory: &quot;100Mi&quot;<br>            nvidia.com/gpu: 1<br>          limits:<br>            cpu: &quot;100m&quot;<br>            memory: &quot;100Mi&quot;<br>            nvidia.com/gpu: 1<br>      restartPolicy: Never</pre><p>Tips: job submitted with suspend: true, nodeselector to match the proper node-pool name:</p><pre>nodeSelector:<br>        cloud.google.com/gke-nodepool: dws-nodepool</pre><p>It is good practice for each namespace to have its own LocalQueue definition:</p><pre>apiVersion: kueue.x-k8s.io/v1beta1<br>kind: LocalQueue<br>metadata:<br>  namespace: &quot;default&quot;<br>  name: &quot;dws-local-queue&quot;<br>spec:<br>  clusterQueue: &quot;dws-cluster-queue&quot;</pre><p>Once the job submitted, use the following command the check job/workload status and trouble-shooting orchestration flows, you may switch to GKE 1.28+ if job does not kick off with proper configurations:</p><pre>kubectl get job jobName -n Namespace<br>kubectl get workload workloadName -n Namespace</pre><p>For step by step walk-through, you can find the <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/provisioningrequest">tutorial doc</a> and the <a href="https://github.com/GoogleCloudPlatform/ai-on-gke/tree/main/tutorials-and-examples/workflow-orchestration/dws-examples">source code repo</a>.</p><p><strong>Benefits of DWS and Kueue:</strong></p><ul><li>Avoid long term reservation/commitments</li><li>Obtainability of DWS for A100,H100 GPUs is better and faster when on-demand pool is out of stock for capacity</li><li>Current wait time to kick-off batch workload may only minutes instead of hours</li><li>Other than one time setup for Kueue, and local/cluster queues, once workload job submitted, everything else will be automatically orchestrated automatically by GKE system: the workload will be kicked off once all resources provisioned at once, the resources will be teared off automatically once the workload completed.</li></ul><p><strong>Additional Considerations for Intelligent Job Orchestration</strong></p><ul><li><strong>Workload Characterization:</strong> Deepen your understanding of your workloads’ resource requirements. Historical data on GPU/TPU utilization and job execution times is invaluable for making informed decisions about resource provisioning.</li><li><strong>Monitoring and Feedback:</strong> Continuously monitor cluster performance and resource utilization using Cloud Monitoring. Analyze job logs and identify areas for improvement. This feedback loop allows you to refine your intelligent job orchestration strategies over time.</li></ul><h3><strong>8. The Big Picture — Holistic Optimization</strong></h3><p>Let’s explore additional strategies that contribute to a holistic cost-optimization approach for your GPU/TPU-powered AI/ML workloads on GKE.</p><ul><li><strong>Spot VMs &amp; Preemptible VMs:</strong> Consider these deeply discounted instances for fault-tolerant or interruptible workloads where the risk of preemption is acceptable. Use cases include exploratory data analysis, non-critical training, or batch processing that can restart from checkpoints.</li><li><strong>GKE Autopilot:</strong> GKE Autopilot simplifies cluster management and automates certain resource optimization tasks. While it’s a relatively new offering than GKE Standard( some features such as DWS, GPU resource sharing options may lag behind), explore whether its managed features align with your cost objectives since you don’t need to worry about managing underlying infrastructure resources</li><li><strong>Minimize Data Transfer:</strong> Cloud providers often charge for data egress (data moving out of their cloud regions). Architect solutions to keep datasets in the same region as your GKE cluster whenever possible, and consider compression techniques to reduce data transfer volumes.</li><li><strong>Cloud Monitoring:</strong> Leverage Cloud Monitoring to track GPU/TPU utilization, leverage Google Managed Prometheus(GMP) to simplify metrics collection, create detailed dashboards, and set alerts for unexpected spikes in usage. Continuous monitoring is essential for identifying optimization opportunities</li></ul><h3><strong>9. Conclusion &amp; Ongoing Evolution</strong></h3><p>Optimizing the costs of running AI/ML workloads on GKE is an iterative process. Experiment with different combinations of GPU instance types, TPU configurations, GPU resource sharing with MIG and time-sharing, and utilize intelligent scheduling with a tool like DWS &amp; Kueue to find the most efficient setup for your projects.</p><p>The cloud landscape evolves rapidly, with new GPU and TPU offerings emerging regularly. Stay updated on the latest innovations and pricing adjustments. Open-source cost optimization tools and community best practices can also provide valuable insights.</p><p>Lastly, don’t forget to check out other GKE related resources on AI ML infrastructure offered by Google Cloud and check the resources included in the <a href="https://cloud.google.com/kubernetes-engine/docs/integrations/ai-infra">AI/ML orchestration on GKE</a> documentation. And feel free to contact me through my <a href="https://www.linkedin.com/in/rugui-chen/">linked-in</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96f79d79c51b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/llm-finops-cost-optimization-options-to-run-high-performance-ai-ml-workloads-on-gke-in-google-96f79d79c51b">LLM&amp;FinOps: Cost Optimization Options to Run High Performance AI/ML Workloads on GKE in Google…</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Google Managed Prometheus and Triton Inference Server on GKE to Simplify LLM observability and…]]></title>
            <link>https://medium.com/google-cloud/use-google-managed-prometheus-and-triton-inference-server-to-simplify-llm-observability-and-b93fb42342c2?source=rss-c074bc07b3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b93fb42342c2</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[triton-inference-server]]></category>
            <dc:creator><![CDATA[Rick(Rugui) Chen]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 17:57:14 GMT</pubDate>
            <atom:updated>2024-03-15T15:14:18.245Z</atom:updated>
            <content:encoded><![CDATA[<h3>Use Google Managed Prometheus and Triton Inference Server on GKE to Simplify LLM observability and monitoring</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8xF2pPp4h5Pz_QDr_9Q6Cw.png" /></figure><h3><strong>Background</strong></h3><p>Large Language Models (LLMs) are revolutionizing various industries, from chatbots to content creation. However, their deployment and maintenance demand careful observability information including monitoring metrics and tracing. You need insights into critical metrics such as CPU/GPU usage, latency, throughput, error rates, and resource utilization to ensure optimal performance and catch potential issues early.</p><p>Traditional monitoring setups can be complex, especially in a Kubernetes environment. Popular tools like self managed local Prometheus offer powerful metrics collection but add operational overhead and lack of persistence as well as centralized views. On the other hand, inference servers like Huggingface TGI are essential to offer entry level model serving but may miss same level of performance metrics comparing to native solutions from Nvidia and Triton Servers.</p><h3><strong>Introduction</strong></h3><p>Here’s where a powerful combination comes into play to simplify LLM inference monitoring metrics: <a href="https://cloud.google.com/stackdriver/docs/managed-prometheus/setup-managed">Google Managed Prometheus(GMP),</a> <a href="https://docs.nvidia.com/deeplearning/triton-inference-server/user-guide/docs/user_guide/metrics.html">Triton Inference Server model metrics</a>, and Google Kubernetes Engine (GKE). GMP managed metric collections eliminates the hassle of operating your own Prometheus instance locally. <a href="https://github.com/triton-inference-server/server">Triton inference server</a> provides optimized model serving through various backend frameworks such vLLM, TensorRT, PyTorch, ONNX and TensorFlow etc, and GKE offers a scalable Kubernetes platform to deploy AI ML training and inference workloads. More importantly, Triton Inference Server includes a lot of LLM enterprise operations tools such as model analyzer, model management, rate limit, trace etc</p><p>In this blog, we’ll dive into how to integrate these technologies to establish a simplifed while robust LLM monitoring solution. You’ll learn how to capture essential metrics, build insightful dashboards, and proactively manage your LLM deployments.</p><h3>Prerequisites</h3><p>Access to a Google Cloud project with the L4 GPUs available and enough quota in the region you select.</p><p>A computer terminal with kubectl and the Google Cloud SDK installed. From the GCP project console you’ll be working with, you may want to use the included Cloud Shell as it already has the required tools installed.</p><p>Some models such as Llama2 will need Huggingface API token to download model files</p><p>Meta access request: <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/">https://ai.meta.com/resources/models-and-libraries/llama-downloads/</a> need regisgter an email address to download</p><p>Go to Hugging face, create account account with same email registered in Meta request. Then find Llama 2 model, fill out access request: <a href="https://huggingface.co/meta-llama/Llama-2-7b.">https://huggingface.co/meta-llama/Llama-2-7b.</a> Need to wait for a few hours with the approval email to be able to use Llama 2</p><p>Get Hugging face access token from your huggingface account profile settings, you will need it in next steps</p><h3><strong>1 Setup GKE cluster and environments</strong></h3><p>To simplify the setup process, please download the sample repo from:</p><pre>git clone https://github.com/llm-on-gke/triton-vllm-gke<br>cd triton-vllm-gke</pre><p>Take a look at create<a href="https://github.com/llm-on-gke/triton-vllm-gke/blob/main/create-cluster.sh">-cluster.sh</a> bootstrap script to provisioning GKE cluster, the scripts include the following steps:</p><ol><li>GKE standard cluster</li><li>GKE spot nodepool with 1 L4 GPU accelerator ( g2-standard-8)</li><li>IAM permissions</li><li>GKE secret to store Huggingface access token</li></ol><p>Update the bootstrap script to fit your need accordly, especially the first two line:</p><pre>export PROJECT_ID=&lt;your-project-id&gt;<br>export HF_TOKEN=&lt;paste-your-own-token&gt;</pre><p>Then run the bootstrap script to provisin base environments:</p><pre>chmod +x create-cluster.sh<br>./create-cluster.sh</pre><p>Wait 5–10 minute still the scripts completed successfully, and you may execute the following to connect to the GKE cluster ( update the command with proper location and cluster name):</p><pre>gcloud container clusters get-credentials triton-inference --location us-central1<br>kubectl get ns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dRh4UnQJ0h66qroBGEIn6g.png" /></figure><p>Please be noted, GMP and managed collection already enabled on <a href="https://cloud.google.com/kubernetes-engine/docs/concepts/choose-cluster-mode#why-standard">GKE Standard clusters</a> running GKE version 1.27 or greater</p><h3><strong>2 Upload the triton vLLM backend model config settings to cloud storage bucket</strong></h3><p>Before we can deploy the any OpenSource LLM model, need to prepare the backend python code and config settings so that it can be available when LLM model is deployed through Triton Inference server</p><p>Look at the sample folder structure under model_repository sub-folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*p2_9fcDVG0HHRbQ3ZtrGTg.png" /></figure><p>There are 2 files included, <a href="https://github.com/llm-on-gke/triton-vllm-gke/blob/main/model_repository/vllm/1/model.py">model.py</a> which is pure python code to load vLLM backed models from Huggingface, while<a href="https://github.com/llm-on-gke/triton-vllm-gke/blob/main/model_repository/vllm/config.pbtxt"> config.pbtxt</a> is used to specify inferencing options.</p><p>You don’t need to make any update to the files since it can be applied to most of vLLM backend LLM models( Llama2, Mistral, Falcon, GPT etc), instead just run the following commands to upload the sample model repository to a cloud storage bucket(replace your-bucket-name)</p><pre>gsutil mb gs://your-bucket-name<br>gsutil cp -r model_repository gs://your-bucket-name/model_repository</pre><h3><strong>3 Deploy LLama2 7b model to Triton Inference Server</strong></h3><p>Now, we are ready to deploy an OpenSource LLM model to Triton Inference Server through vLLM backend.</p><p>As example, take a look at <a href="https://github.com/llm-on-gke/triton-vllm-gke/blob/main/vllm-gke-deploy.yaml">vllm-gke-deploy.yaml</a> downloaded and make updates on:</p><pre>env:<br>  - name: model_name<br>    value: meta-llama/Llama-2-7b-chat-hf<br>args: [&quot;tritonserver&quot;, &quot;--model-store=gs://your-bucket-name/model_repository&quot;,</pre><p>After the updates, you may run the following command to deploy Llam2 7b chat model or other OpenSource LLM to Triton Inference Server:</p><pre>kubectl -n triton apply -f vllm-gke-deploy.yaml</pre><p>The deployment will be completed after 7–10 minutes, and you may check the deployment status:</p><pre>watch kubectl get po -n triton </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mMwz8Y7OFVCfsmrNAPKTA.png" /></figure><p>This shows the deploy is ready, also, you may check the GKE workload console and logs screen for the pod with indication of healthy state for different ports( 8001 for GRPC, 8000 for HTTP, 8002 for Metrics),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCkC3kLj26dp0M13Ut3wqA.png" /></figure><h3><strong>4 Client side validations and metrics retrieval:</strong></h3><p>A sample client provided here to illustrate how you can execute client validations.</p><p>Go to client sub-folder downloaded,</p><pre>cd client</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*IcudRybM5V73ukf-CZdmWw.png" /></figure><p>You can check the cloudbuild.yaml file and replace<strong> gke-llm</strong> with your own Artifact Registry repo name,</p><pre>steps:<br>- name: &#39;gcr.io/cloud-builders/docker&#39;<br>  args: [ &#39;build&#39;, &#39;-t&#39;, &#39;us-east1-docker.pkg.dev/$PROJECT_ID/gke-llm/triton-client:latest&#39;, &#39;.&#39; ]<br>images:<br>- &#39;us-east1-docker.pkg.dev/$PROJECT_ID/gke-llm/triton-client:latest&#39;</pre><p>Then run the following command to build your own client image:</p><pre>gcloud builds submit . </pre><p>Once the image is pushed to Artifact registry repo,</p><p>Run the following commands to kick off triton client app( update the project_id and repo where client image stored):</p><pre>kubectl run -it -n triton --image us-east1-docker.pkg.dev/your-project/gke-llm/triton-client triton-client<br>kubectl exec -it -n triton triton-client -- bash</pre><p>Ignore if the first command returns timeout error, once you are inside the client Pod prompt, you may do a few validation commands:</p><pre>curl $TRITON_INFERENCE_SERVER_SERVICE_HOST:8000/v2<br>curl $TRITON_INFERENCE_SERVER_SERVICE_HOST:8002/metrics<br>python grpc-client.py</pre><p>Make sure all the commands completed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xc6qpSYbEyfGkTVnJ1jNeg.png" /></figure><h3><strong>5 Configure GMP managed collection to target with Triton Inference Server metrics</strong></h3><p>In previous validation steps, the following command will return the CPU/GPU related performance metrics values by on-demand query only.</p><pre>curl $TRITON_INFERENCE_SERVER_SERVICE_HOST:8002/metrics</pre><p>Now, it is time to setup a <a href="https://github.com/GoogleCloudPlatform/prometheus-engine/blob/v0.4.3-gke.0/doc/api.md#podmonitoring">PodMonitoring</a> resource in GMP to collect metrics available from Triton Inference Server metric ports and pass over to Cloud Monitoring system.</p><p>Run the following command to update GMP settings.</p><pre>kubectl edit OperatorConfig -n gmp-public</pre><p>Within the VI based kubernetes resource editor, insert( enter key i) the following section right above line start with metadata and make sure features and metadata both left aligned:</p><pre>features:<br>      targetStatus:<br>        enabled: true</pre><p>Save the Kubernetes VI editor, use Key Esc with :w and :x</p><p>Take a look <a href="https://github.com/llm-on-gke/triton-vllm-gke/blob/main/vllm-podmonitoring.yaml">vllm-podmointoring.yaml </a>to create sample PodMonitoring resource, it points to the Triton Inference Server pods hosting LLM model and collect them from metrics port( 8002) every 10 seconds:</p><pre>apiVersion: monitoring.googleapis.com/v1<br>kind: PodMonitoring<br>metadata:<br>  name: triton-inference<br>spec:<br>  selector:<br>    matchLabels:<br>       app: triton-inference-server<br>  endpoints:<br>  - port: metrics<br>    interval: 10s</pre><p>Then run the following command to create a PodMonitoring resource and target Triton Inference Server metric port:</p><pre>kubectl -n triton apply -f vllm-podmonitoring.yaml</pre><p>You can use the following command to make sure it starts to collect Triton Inference Server metrics</p><pre>kubectl -n triton describe podmonitoring triton-inference </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BcibdSeUWsfTv8B6oXciag.png" /></figure><h3><strong>6 PromQL query and visualization on GMP metrics collected from Triton Inference Server</strong></h3><p>As managed Kubernetes platform, GKE already provides out of box GPU related dashboards in console by navigating to Kubernetes Engine/Clusters/Observability tab,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vn5CnTi5OMx_6BOTMhy2zA.png" /></figure><p>In addition, more GPU and Nvidia specific metrics from <a href="https://docs.nvidia.com/deeplearning/triton-inference-server/user-guide/docs/user_guide/metrics.html">Triton Inference server metrics </a>will be automatically collected through GMP and stored in centralized Google Cloud Monitoring system for long term persistence and ready to be queried and visualized in multiple ways.</p><p>First, you can perform <a href="https://cloud.google.com/stackdriver/docs/managed-prometheus/query-cm">PromQL Query using Cloud Monitoring</a> through Metrics Explorer or create Dashboards from the metrics(start with nv_XXX in metrics explorer) provided by Triton Inference Server. Make sure you switch to PromQL in right side of Monitoring/Metric Explorer screen and start to type in Metric name starting with NV_ in Query box, and a list of Triton Inference Server merics will be available from dropdown list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjWr5XU2ueBpK_yXN7I6yA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-_y4EOfjIIKkcux7r9l3g.png" /></figure><p>Alternatively, you can use Open Source tools such as Grafana or Prometheus UI to visualize or create your own monitoring dashboards based on metrics collected by GMP but as immediately available datasource plug into <a href="https://cloud.google.com/stackdriver/docs/managed-prometheus/query">Grafana</a> or <a href="https://cloud.google.com/stackdriver/docs/managed-prometheus/query-api-ui">Prometheus UI.</a> Please follow the links provided for details.</p><h3><strong>Conclusion</strong></h3><p>In this blog, we walked through steps and demonstrated benefits of AI ML GKE infrastructure together with Google Managed Prometheus and Triton Inference Server to empower enterprise LLM OPS and Platform team with performance and monitoring tools can be applied to production environment and effectively manage and monitoring LLM inference workload observability.</p><p>Don’t forget to check out other GKE related resources on AI ML infrastructure offered by Google Cloud and check the resources included in the <a href="https://cloud.google.com/kubernetes-engine/docs/integrations/ai-infra">AI/ML orchestration on GKE</a> documentation.</p><p>For your reference, the code snipptes listed in this blog can be find in this <a href="https://github.com/llm-on-gke/triton-vllm-gke">source code repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b93fb42342c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/use-google-managed-prometheus-and-triton-inference-server-to-simplify-llm-observability-and-b93fb42342c2">Use Google Managed Prometheus and Triton Inference Server on GKE to Simplify LLM observability and…</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explore Duet AI to assist with React frontend appldevelopment]]></title>
            <link>https://medium.com/google-cloud/explore-duet-ai-to-assist-with-react-frontend-appldevelopment-cc39df3ce7d9?source=rss-c074bc07b3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc39df3ce7d9</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[duet-ai]]></category>
            <category><![CDATA[application-development]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gcp-app-dev]]></category>
            <dc:creator><![CDATA[Rick(Rugui) Chen]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 04:55:09 GMT</pubDate>
            <atom:updated>2024-02-23T15:38:23.065Z</atom:updated>
            <content:encoded><![CDATA[<h3>Explore Duet AI to assist with React frontend application development</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*k3WkCA5SxMepBpIkSrj-Rg.jpeg" /></figure><h3>Introduction</h3><p>This post provides an example to explore how Google Cloud’s <a href="https://cloud.google.com/duet-ai?hl=en#:~:text=Duet%20AI%20for%20Developers%20comes,the%20smart%20action%20you%20need.">Duet AI for Developers </a>can assist with frontend application development.</p><p>With the help of Duet AI, we use React and TypeScript to build a client-side web app. This simple Weather Application allows user to search for locations and displays its current weather conditions. Along the way, we will learn DuetAI’s assistive capabilities in following areas:</p><ul><li>Bootstrapping an app with create-react-app</li><li>Using React with TypeScript</li><li>React Hooks</li><li>Async Communication and integrate with <a href="https://openweathermap.org/">Open Weather</a> service API</li><li>Basic Styling</li></ul><h3>Requirements</h3><ul><li><a href="https://cloud.google.com/duet-ai/docs/discover/set-up-duet-ai">DuetAI project setu</a>p</li><li><a href="https://cloud.google.com/duet-ai/docs/discover/set-up-duet-ai#use-ide">DuetAI compatible IDE setup</a></li><li><a href="https://nodejs.org/en/">NodeJS</a></li><li>Basic familiarity with using the terminal</li><li>Free <a href="https://openweathermap.org/">OpenWeatherMap</a> API key</li></ul><h3>Step 1: <strong>Boot-strapping an App with create-react-app</strong></h3><p>You can use the following prompt to create a skeleton of TypeScript based React project</p><p><strong>Prompt</strong></p><blockquote>Show me step by step how to create an react application as name of weather-react-app, using npx with the latest versions and typescript templates</blockquote><p><strong>Response</strong></p><p>DuetAI will provide detailed steps, include the following command to create React application,</p><p>npx create-react-app weather-react-app --template typescript</p><p>cd weather-app</p><p>npm install</p><p>npm start</p><p>You will get the following project file structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/0*OMLvm3IoSTPn1jpF" /></figure><p>Let’s cleanup the default files</p><p><em>Remove the contents of App.css and index.css</em></p><p><em>Remove the import of logo.svg from App.tsx</em></p><p><em>Delete App.test.tsx and logo.svg,</em></p><p><em>Open src/app.tsx file, Update the definition of the App function (component) :</em></p><p>Next, update the main page app.tsx, to show up “Weather App”</p><p><strong>Prompt</strong></p><blockquote>Update App.tsx only shows Weather App in a div</blockquote><p><strong>Response (app.tsx)</strong></p><pre>import React from &#39;react&#39;;<br><br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Weather App&lt;/h1&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;<br>...</pre><p>Run “npm start”, the following page will show up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/0*M7RzueAC5RCJc4NR" /></figure><h3>Step 2: Initial layout: <strong>Table of Locations with Search Button</strong></h3><p>Let’s design an initial round of main page with following elements:</p><p>Div 1 for Location Search:</p><ul><li>Text label: “Add Location”</li><li>Text box</li><li>Button, “Search”</li><li>Text Label: Locations</li></ul><p>Div 2 for table as list of locations:</p><ul><li>Text label: “Location”</li><li>Table</li></ul><p><strong>Prompt</strong></p><blockquote>In app.tsx component, within Weather App Div, add a div, include “Add location” Label, a text input box with default value “New York”, a Search button</blockquote><blockquote>Add another Div, include h2 text “Location”, follow by a table, head row with Name only, 2 rows with New York, Belfast</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jm7JJbfwkXd0ad73" /></figure><p>The layout does not look well, let’s see how to improve it with bootstrap styles.</p><p>Run the “npm install bootstrap” command in project folder,</p><p>Add the following statement inside index.tsx so that all pages can leverage bootstrap styles:</p><p><em>import ‘bootstrap/dist/css/bootstrap.min.css’;</em></p><p><strong>Prompt</strong></p><blockquote>Update the app.tsx page with proper bootstrap css class Names so that the page looks professional page, set Search button to blue color</blockquote><p>The main page will look like after apply bootstrap styles with DuetAI response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MtGzb0Fm-kJNp4g4" /></figure><p>With the static layouts in place, we need to define a few state variables and hook element event handler:</p><p><strong>Prompt</strong></p><blockquote>Define a locationSearch state variable and set useState initial value to empty string, link “Add Location” text input value and onChange event to this variable. Add locations state variable and set useState initial values to array of strings, update table rows, for each row’s values to map location value in locations state variable</blockquote><p>Noted following state variable and event handler will be created:</p><pre>const [locations, setLocations] = useState&lt;string[]&gt;([]);<br>const addLocation = (location: string) =&gt; setLocations([location, ...locations]);</pre><blockquote>Rename handleSearch to addLocation, inside function, change locations value to append the locationSearch variable value, update locationSearch variable to empty string. Define a boolean constant called disableSearch and assign its value to if locationSearch.trim is ‘’. Link Search button disable attribute to this variable</blockquote><h3><strong>Step 3: — Separate LocationSearch and LocationTable Components out from app.tsx</strong></h3><p>Let’s keep the main component app.tsx as thin as possible, and separate into 2 new components, LocationSearch.tsx and LocationTable.tsx, DuetAI can help with code re-structure too:</p><p><strong>Prompt (create LocationSearch Component)</strong></p><blockquote>Add a component called LocationSearch.tsx, expose it use FC as arrow function as strong type, define onSearch property, move the elements Label “Add Location”, Input Textbox, “Search” Buttom from App.tsx to this LocationSearch component</blockquote><p>Then, define an event handler function to hook-up with the Search button onclick event:</p><p><strong>Prompt( define addLocation event handler hook with button onclick event)</strong></p><blockquote>Add a addLocation event handler, call onSearch function to pass locationSearch parameter, then setLocation to ‘’. Link addLocation event to Search button’s onclick event</blockquote><p><strong>Prompt (create LocationTable Component)</strong></p><blockquote>Add a LocationTable component by creating a file called LocationTable.tsx, expose it use FC as arrow function as strong type,, define locations property as string array, move the elements Label “Location”, fowllowed by table, head and body, use location and index for rows from App.tsx to this locationSearch component</blockquote><p>Also, app.tsx component will be updated based on the previous responses:</p><pre>import React, {useState} from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import {LocationSearch} from &quot;./LocationSearch&quot;;<br>import {LocationTable} from &quot;./LocationTable&quot;;<br><br>function App() {<br>  const [locations, setLocations] = useState&lt;string[]&gt;([]);<br>  const addLocation = (location: string) =&gt; setLocations([location, ...locations]);<br><br>  return (<br>    &lt;div className=&quot;container&quot;&gt;<br>      &lt;h1&gt;Weather App&lt;/h1&gt;<br><br>      &lt;LocationSearch onSearch={addLocation}/&gt;<br>      &lt;LocationTable locations={locations}/&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h3>Step 4: — <strong>Integrate Open Weather API</strong></h3><p>Go to <a href="https://openweathermap.org/">OpenWeatherMap</a>, get a free API key if you have not done that yet</p><p>Before we move ahead, let’s re-organize the project file structure:</p><p>Create 3 new sub folders under src: src/components, src/services, src/models</p><p>Move app.tsx, app.css, LocationSerarch.tsx, LocationTable.tsx to components folder</p><p>Under src/models, create Weather.ts, then</p><p><strong>Prompt (Weather.ts)</strong></p><blockquote><strong>In Weather.ts model, export 2 subsets, first subset Coordinates with lon as number, lat as number, define another subset WeatherLocation with Coord as Coordinates, id as number, name as string</strong></blockquote><p>Under src/services folder, WeatherService.ts then</p><p><strong>Prompt (WeatherService.ts)</strong></p><blockquote>In WeatherService.ts, define a key string variable to get string value environment variable REACT_APP_OPEN_WEATHER_API_KEY, set keyQuery string value to “appid” append with key, set server string value to ‘api.openweathermap.org/data/2.5&#39;</blockquote><blockquote>Remove getWeather function, add searchLocation async function with parameter name Term, fetch results from weather server with query string term and keyQuery, return json data format, add error handling for code ‘400’ or code not ‘200’,</blockquote><blockquote>In WeatherService.ts, update searchLocation async function to return WeatherLocation or undefined</blockquote><p>Make sure WeatherService.ts looks similar to the following:</p><pre>const key = process.env.REACT_APP_OPEN_WEATHER_API_KEY;<br>const keyQuery = `appid=${key}`;<br>const server = &#39;api.openweathermap.org/data/2.5&#39;;<br><br><br>export const searchLocation = async (term: string) =&gt; {<br> const response = await fetch(`${server}/weather?q=${term}&amp;${keyQuery}`);<br><br><br>  if (response.status === 400) {<br>   throw new Error(&#39;Invalid city name&#39;);<br> } else {<br>   throw new Error(&#39;Something went wrong&#39;);<br> }<br><br><br> return response.data;<br> // else<br>};</pre><p>Then, update LocationSearch.tsx as necessary:</p><p><strong>Prompt (LocationSearch.ts)</strong></p><blockquote>Update AddLocation event handler, as async function with parameter term as string, set location value to call searchLocation function in services/WeatherService.ts</blockquote><h3><strong>Step 5: — Showing weather data in the page</strong></h3><p>As final step of this simple Weather application, we will show the weather data by calling weather API.</p><p>First, need to add a currentLocation state variable to app.tsx component:</p><p><strong>Prompt (components/app.tsx)</strong></p><blockquote>In App.tsx, add a currentLocation state variable as WeatherLocation, update LocationTable with currentLocation property and onselect event</blockquote><p><strong>Prompt (components/LocationTable.tsx)</strong></p><blockquote><strong>in LocationTable.tsx, add currentLocation,onSelect to LocationTableProps, update table row onclick function to onSelect</strong></blockquote><p>Also, need to add more properties to Models/Weather.ts</p><p><strong>Prompt (</strong><a href="https://github.com/rick-c-goog/duetai-workshop/blob/main/weather-react-app/src/models/Weather.ts"><strong>models/Weather.ts</strong></a><strong>)</strong></p><blockquote>Extend Weather.ts model, add model WeatherCondition, with fields id, main, description, icon, another model MainWeatherData, with numeric fields temp, feels_like,temp_min,temp_max,pressure, humidity, update Weather model to only include fields: dt as number, weather as WeatherCondition array, main as MainWeatherData</blockquote><p>Then, add 2 more functions(readWeather, getIconURL) to WeatherService.ts</p><p><strong>Prompt (</strong><a href="https://github.com/rick-c-goog/duetai-workshop/blob/main/weather-react-app/src/services/WeatherService.ts"><strong>services/WeatherService.ts</strong></a><strong>)</strong></p><blockquote>In WeatherService.tsx, expose a function readWeather to read the current weather using openWeather API at a specified location, use parameter locationID as number return Weather object, expose another helper function to generate location icon urls, use code as string parameter and return string</blockquote><p>Now, we need to create 2 more page components to display weather data:</p><ol><li>Create components/WeatherEntry.tsx file, then</li></ol><p><strong>Prompt (</strong><a href="https://github.com/rick-c-goog/duetai-workshop/blob/main/weather-react-app/src/components/WeatherEntry.tsx"><strong>components/WeatherEntry.tsx</strong></a><strong>)</strong></p><blockquote>In WeatherEntry.tsx, define WeatherEntryProps to include weather as type of Weather object, add a inline helper function “convertUnixTimeToDate” to convert unitUTC from number to DateTime, expose WeatherEntry as weather props, and include the following weather elements in divs, Date element to convert weather.dt to local datetime, weather.mainWeather data elements: temp, temp_min, temp_max, humidity, image icon element with url from calling getIconURL function by passing WeatherCondition icon value</blockquote><p>2. Create components/WeatherSummary.tsx file, then</p><p><strong>Prompt (</strong><a href="https://github.com/rick-c-goog/duetai-workshop/blob/main/weather-react-app/src/components/WeatherSummary.tsx"><strong>components/WeatherSummary.tsx</strong></a><strong>)</strong></p><blockquote>In WeatherSummary.tsx component, define WeatherSummary props, include location field as WeatherLocation or null. Expose WeatherSummary function to return location, include a weather state variable initialized with Weather or null object, follow by useEffect function to readWeather from location.id, if location.id has value, setWeather</blockquote><p>3. In app.tsx, add WeatherSummary information</p><p><strong>Prompt (</strong><a href="https://github.com/rick-c-goog/duetai-workshop/blob/main/weather-react-app/src/components/App.tsx"><strong>components/a</strong>pp.tsx</a><strong>)</strong></p><blockquote>In app.tsx component, add another div to include WeatherSummary info, also import WeatherSummary.tsx</blockquote><p>Please be noted, exact results from Step 5, might varies significantly, you may use cautions and adjust your prompts accordly. Check with the github links to the files if you get stumbled in this step.</p><p>Run the following command to give a try:</p><pre>export REACT_APP_OPEN_WEATHER_API_KEY=YourOpenWeatherAPIKey;<br>npm start</pre><p>You will see a page can search a location and show real-time weather data conditions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDK67IQiPr83RQgGNMqfZA.png" /></figure><h3>Final thoughts</h3><p>In this post, we walked through the main steps to build a simple React based frontend application with integration of real time weather service API data.</p><p>A few take aways using Google DuetAI for developer to accelerate client based application development:</p><ul><li><strong>Be Specific on Prompts:</strong> Be clear and specific on context, leads to the better Duet AI responses.</li><li><strong>Foundational understanding on React framework:</strong> Solid understanding of React and framework concepts( such as state variables, event hooks etc.) will make Duet AI responses more relevant and productive.</li><li><strong>Duet AI as assistive tool:</strong> Use Duet AI for help and guidance, use judgement to adopt code generated. Be cautious and not to blindly copy-paste</li><li><strong>Duet AI as virtual Pair-programmer: </strong>Just like in-person one, be patient and start with basics, gradually improve the quality with more iterations. Occasionally you may still need to jump in and resolve simple issues such as missing import modules, inconsistency of function names across different components. After all, Duet AI is really good to remember stuff and learn from you as well</li></ul><p>Don’t forget to check out the <a href="https://cloud.google.com/duet-ai/docs/discover/write-prompts">best practices to write better Duet AI prompt</a>, For your reference, all the code snippets and final solution for the weather app related to this blog can be find in this <a href="https://github.com/rick-c-goog/duetai-workshop/tree/main/weather-react-app">source code repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc39df3ce7d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/explore-duet-ai-to-assist-with-react-frontend-appldevelopment-cc39df3ce7d9">Explore Duet AI to assist with React frontend appldevelopment</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serving Open Source LLMs on GKE using vLLM framework]]></title>
            <link>https://medium.com/google-cloud/serving-open-source-llms-on-gke-using-vllm-framework-5e522b3679ee?source=rss-c074bc07b3ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e522b3679ee</guid>
            <category><![CDATA[ai-ml-inference]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Rick(Rugui) Chen]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 22:35:45 GMT</pubDate>
            <atom:updated>2024-05-09T16:56:34.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*5XDg3SZNld3reWiWMYR52A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*1Y4R5TEF_TAGXWMYc6hQ3A.png" /></figure><h3>Introduction</h3><p>This post shows how to serve Open source LLM models(Mistrial 7B, Llama2 etc) on Nvidia GPUs(L4, Tesla-T4, for example) running on Google Cloud Kubernetes Engine (GKE). It will help you understand the AI/ML ready features of GKE and how to use them to serve large language models make life of self-managing OSS LLM models in GKE not as dauting as you may originally think of .</p><p>TGI and vLLM are 2 common frameworks to address significant challenges on slow latencies to obtain an output from a LLM, primarily due to ever increasing LLM substantial sizes to get responses back</p><p><a href="https://github.com/vllm-project/vllm">𝐯𝐋𝐋𝐌</a>(𝐕𝐞𝐫𝐬𝐚𝐭𝐢𝐥𝐞 𝐥𝐚𝐫𝐠𝐞 𝐥𝐚𝐧𝐠𝐮𝐚𝐠𝐞 𝐦𝐨𝐝𝐞𝐥) is an open source framework designed to enhance the inference and serving speed of LLMs. It has demonstrated remarkable performance improvements compared to mainstream frameworks like Hugging Face’s Transformers, primarily because of a highly innovative new algorithm at its core.</p><p>One key reason behind vLLM’s speed during inference is its use of the 𝐏𝐚𝐠𝐞𝐝 𝐀𝐭𝐭𝐞𝐧𝐭𝐢𝐨𝐧 𝐭𝐞𝐜𝐡𝐧𝐢𝐪𝐮𝐞. In traditional attention mechanisms, the keys and values computed are stored in GPU memory as a KV cache. This cache stores attention keys and values for previous tokens, which can consume a significant amount of memory, especially for large models and long sequences. These keys and values are also stored in a contiguous manner.</p><p>𝐓𝐆𝐈 (𝐓𝐞𝐱𝐭-𝐆𝐞𝐧𝐞𝐫𝐚𝐭𝐢𝐨𝐧-𝐈𝐧𝐟𝐞𝐫𝐞𝐧𝐜𝐞) is another solution aimed at increasing the speed of LLM inference. It offers high-performance text generation using Tensor Parallelism and dynamic batching for popular open-source LLMs like StarCoder, BLOOM,Llama and other models.</p><p>𝐓𝐆𝐈 𝐯𝐬 𝐯𝐋𝐋𝐌</p><p>- TGI does not support paged optimization.</p><p>-Both techniques don’t handle all LLM architectures.</p><p>-TGI also allows quantizing and fine-tuning models, which are not supported by vLLM.</p><p>-VLLM achieves better performance than TGI and the Hugging Face transformer library, with up to 24x higher throughput compared to Hugging Face and up to 3.5x higher throughput than TGI.</p><p>This post shows how to serve OSS LLMs(Mistral 7B, or Llama2) model on L4 GPUs running on Google Cloud Kubernetes Engine (GKE). It will help you understand the AI/ML ready features of GKE and how to use them to serve large language models.</p><p>GKE is a fully managed service that allows you to run containerized workloads on Google Cloud. It’s a great choice for running large language models and AI/ML workloads because it is easy to set up, it’s secure, and it’s AI/ML batteries included. GKE installs the latest NVIDIA GPU drivers for you in GPU-enabled node pools, and gives you autoscaling and partitioning capabilities for GPUs out of the box, so you can easily scale your workloads to the size you need while keeping the costs under control.</p><p>For example on how to serve Open source model( Mistral 7B) on GKE using TGI, please refer to this Google community blog:</p><p><a href="https://medium.com/google-cloud/serving-mistral-7b-on-l4-gpus-running-on-gke-25c6041dff27">Serving Mistral 7B on L4 GPUs running on GKE</a></p><p><strong>Opensource Models supported by vLLM</strong></p><p>vLLM supports most of popular open source LLM modes such as Llama2, Mistral, Falcon, etc., see the full supported LLM list in <a href="https://docs.vllm.ai/en/latest/models/supported_models.html">https://docs.vllm.ai/en/latest/models/supported_models.html</a></p><h3><strong>Prerequisites</strong></h3><p>Access to a Google Cloud project with the L4 GPUs available and enough quota in the region you select.</p><p>A computer terminal with kubectl and the Google Cloud SDK installed. From the GCP project console you’ll be working with, you may want to use the included Cloud Shell as it already has the required tools installed.</p><p>Some models such as Llama2 will need Huggingface API token to download model files</p><p>Meta access request: <a href="https://ai.meta.com/resources/models-and-libraries/llama-downloads/">https://ai.meta.com/resources/models-and-libraries/llama-downloads/</a> need regisgter an email address to download</p><p>Go to Hugging face, create account account with same email registered in Meta request. Then find Llama 2 model, fill out access request: <a href="https://huggingface.co/meta-llama/Llama-2-7b.">https://huggingface.co/meta-llama/Llama-2-7b.</a> Need to wait for a few hours with the approval email to be able to use Llama 2</p><p>Get Hugging face access token from your huggingface account profile settings, you will need it in next steps</p><p><strong>Setup project environments</strong></p><p>From your console, select the Google Cloud region and project, checking that there’s availability for L4 GPUs in the one that you end up selecting. The one used in this tutorial is us-central, where at the time of writing this article there was availability for L4 GPUs( alternatively, you can choose other regions with different GPU accelerator type available):</p><pre>export PROJECT_ID=&lt;your-project-id&gt;<br>export REGION=us-central1<br>export ZONE_1=${REGION}-a # You may want to change the zone letter based on the region you selected above<br>export ZONE_2=${REGION}-b # You may want to change the zone letter based on the region you selected above<br>export CLUSTER_NAME=vllm-cluster<br>export NAMESPACE=vllm<br>gcloud config set project &quot;$PROJECT_ID&quot;<br>gcloud config set compute/region &quot;$REGION&quot;<br>gcloud config set compute/zone &quot;$ZONE_1&quot;</pre><p>Then, enable the required APIs to create a GK cluster:</p><pre>gcloud services enable compute.googleapis.com container.googleapis.com</pre><p>Now, you need to go ahead download the <a href="https://github.com/llm-on-gke/vllm-inference/tree/main">source code repo</a> provided for this exercise:</p><pre>git clone https://github.com/llm-on-gke/vllm-inference.git<br>cd vllm-inference</pre><p>In this exercise, you will be using the default service account to create the cluster, you need to grant it the required permissions to store metrics and logs in Cloud Monitoring that you will be using later on:</p><pre>PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format=&#39;value(projectNumber)&#39;)<br>GCE_SA=&quot;${PROJECT_NUMBER}-compute@developer.gserviceaccount.com&quot;<br>for role in monitoring.metricWriter stackdriver.resourceMetadata.writer; do<br>  gcloud projects add-iam-policy-binding $PROJECT_ID --member=serviceAccount:${GCE_SA} --role=roles/${role}<br>done</pre><h3><strong>Create GKE Cluster and Nodepools</strong></h3><p><strong>Quick Estimates of GPU type and number of GPU needed for model infererence:</strong></p><p>Estimate the size of a model in gigabytes by multiplying the number of parameters (in billions) by 2. This approach is based on a simple formula: with each parameter using 16 bits (or 2 bytes) of memory in half-precision, the memory usage in GB is approximately twice the number of parameters. Therefore, a 7B parameter model, for instance, will take up approximately 14 GB of memory. We can comfortably run a 7B parameter model in Nvidia L4 and still have about 10 GB of memory remaining as a buffer for inferencing. Alternatively, you can choose to have 2 Tesla-T4 GPUs with 32G by sharding model across both GPUs, but there will be impacts of moving data around.</p><p>For Models with larger parameter size, resource requirements can be reduced through weights Quantization into lower precision bits.</p><p>Example, for Llama 2 70b model which may need 140G memeory with default half point(16 bits), resource requirements can be reduced with quatization into float 8 bits precision or even further with 4 bits, which only need 35G memory and can fit into 2 L4(48G)GPU.</p><p>Reference: <a href="https://www.baseten.co/blog/llm-transformer-inference-guide/">https://www.baseten.co/blog/llm-transformer-inference-guide/</a></p><p><strong>Create a GKE Cluster</strong></p><p>Now, create a GKE cluster with a minimal default node pool, as you will be adding a node pool with L4 GPUs later on:</p><pre>gcloud container clusters create $CLUSTER_NAME \<br> --location &quot;$REGION&quot; \<br> --workload-pool &quot;${PROJECT_ID}.svc.id.goog&quot; \<br> --enable-image-streaming --enable-shielded-nodes \<br> --shielded-secure-boot --shielded-integrity-monitoring \<br> --enable-ip-alias \<br> --node-locations=&quot;$ZONE_1&quot; \<br> --workload-pool=&quot;${PROJECT_ID}.svc.id.goog&quot; \<br> --addons GcsFuseCsiDriver \<br> --no-enable-master-authorized-networks \<br> --machine-type n2d-standard-4 \<br> --num-nodes 1 --min-nodes 1 --max-nodes 3 \<br> --ephemeral-storage-local-ssd=count=1 \<br> --enable-ip-alias</pre><p><strong>Create GKE Nodepool</strong></p><p>Create an additional Spot node pool with regular (we use spot to illustrate, you can remove spot option depends on different use case) n2d VMs with 1 L4 GPUs each:</p><pre>gcloud container node-pools create g2-standard-8 --cluster $CLUSTER_NAME \<br> --accelerator type=nvidia-l4,count=1,gpu-driver-version=latest \<br> --machine-type g2-standard-8 \<br> --ephemeral-storage-local-ssd=count=1 \<br> --enable-autoscaling --enable-image-streaming \<br> --num-nodes=1 --min-nodes=0 --max-nodes=2 \<br> --shielded-secure-boot \<br> --shielded-integrity-monitoring \<br> --node-locations $ZONE_1,$ZONE_2 --region $REGION --spot</pre><p>Note how easy enabling GPUs in GKE is. Just adding the option accelerator automatically bootstraps the nodes with the necessary drivers and configuration so your workloads can start using the GPUs attached to the cluster nodes. If you need to try tesla-t4, need to update — accelerator and — machine-type parameter values, as one example:</p><p><em>— accelerator type=nvidia-tesla-t4,count=1,gpu-driver-version=latest</em></p><p><em>— machine-type n2d-standard-8</em></p><p>After a few minutes, check that the node pool was created correctly:</p><pre>gcloud container clusters get-credentials $CLUSTER_NAME --region $REGION --project $PROJECT_ID<br>gcloud container node-pools list --region $REGION --cluster $CLUSTER_NAME</pre><p>Also, check that the corresponding nodes in the g2-standard-8 node pool have the GPUs available:</p><pre>kubectl get nodes -o json | jq -r &#39;.items[] | {name:.metadata.name, gpus:.status.capacity.&quot;nvidia.com/gpu&quot;}&#39;</pre><p>You should get one with 2 GPUs available corresponding to the node pool you just created:</p><p><em>{</em></p><p><em>“name”: “vllm-serving-cluster-g2-standard-8-XXXXXX”,</em></p><p><em>“gpus”: “1”</em></p><p><em>}</em></p><p>Now, run the following commands to setup GKE identity pool and IAM roles:</p><pre>kubectl create ns $NAMESPACE<br>kubectl create serviceaccount $NAMESPACE -n $NAMESPACE<br>gcloud iam service-accounts add-iam-policy-binding $GCE_SA \<br> --role roles/iam.workloadIdentityUser \<br> --member &quot;serviceAccount:${PROJECT_ID}.svc.id.goog[${NAMESPACE}/${NAMESPACE}]&quot;<br>kubectl annotate serviceaccount $NAMESPACE \<br> --namespace $NAMESPACE \<br>iam.gke.io/gcp-service-account=$GCE_SA</pre><h3><strong>Deploy model to GKE cluster</strong></h3><p>In the downloaded code repo, you can check the following kubernetes resource file,</p><p>vllm-deploy.yaml</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: vllm-server<br>  labels:<br>    app: vllm-server<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: vllm-inference-server<br>  template:<br>    metadata:<br>      labels:<br>        app: vllm-inference-server<br>    spec:<br>      volumes:<br>       - name: cache<br>         emptyDir: {}<br>       - name: dshm<br>         emptyDir:<br>              medium: Memory<br>      nodeSelector:<br>        cloud.google.com/gke-accelerator: nvidia-l4<br>      serviceAccountName: vllm<br>      containers:<br>        - name: vllm-inference-server<br>          image: vllm/vllm-openai<br>          imagePullPolicy: IfNotPresent<br><br>          resources:<br>            limits:<br>              nvidia.com/gpu: 1<br>          env:<br>            - name: HUGGING_FACE_HUB_TOKEN<br>              valueFrom:<br>                secretKeyRef:<br>                  name: huggingface<br>                  key: HF_TOKEN<br>            - name: TRANSFORMERS_CACHE<br>              value: /.cache<br>            - name: shm-size<br>              value: 1g<br>          command: [&quot;python3&quot;, &quot;-m&quot;, &quot;vllm.entrypoints.openai.api_server&quot;]<br>          args: [&quot;--model=meta-llama/Llama-2-7b-hf&quot;,<br>                 &quot;--gpu-memory-utilization=0.95&quot;,<br>                 &quot;--disable-log-requests&quot;,<br>                 &quot;--trust-remote-code&quot;,<br>                 &quot;--port=8000&quot;,<br>                 &quot;--tensor-parallel-size=1&quot;]<br>          ports:<br>            - containerPort: 8000<br>              name: http<br>          securityContext:<br>            runAsUser: 1000<br>          volumeMounts:<br>            - mountPath: /dev/shm<br>              name: dshm<br>            - mountPath: /.cache<br>              name: cache<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: vllm-inference-server<br>  annotations:<br>    cloud.google.com/neg: &#39;{&quot;ingress&quot;: true}&#39;<br>  labels:<br>    app: vllm-inference-server   <br>spec:<br>  type: NodePort<br>  ports:<br>    - port: 8000<br>      targetPort: http<br>      name: http-inference-server<br>    <br>  selector:<br>    app: vllm-inference-server<br><br>---<br>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: vllm-ingress<br>  annotations:<br>    kubernetes.io/ingress.class: &quot;gce&quot;<br>    kubernetes.io/ingress.global-static-ip-name: &quot;ingress-vllm&quot;<br>spec:<br>  rules:<br>  - http:<br>      paths:<br>      - path: &quot;/&quot;<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: vllm-inference-server<br>            port:<br>              number: 8000</pre><p>We use official vllm container image to run the models: vllm/vllm-openai</p><p>To use with models on hugging face, we need to use Huggingface token you retrieved in prerequisite step,</p><p>Execute the command to deploy inference deployment in GKE(update the HF_TOKEN values first)</p><pre>gcloud container clusters get-credentials $CLUSTER_NAME $REGION<br>export HF_TOKEN=&lt;paste-your-own-token&gt;<br>kubectl create secret generic huggingface --from-literal=&quot;HF_TOKEN=$HF_TOKEN&quot; -n $NAMESPACE</pre><p>This GKE huggingface secrect is used to set the environment value in gke-deploy.yaml( need to keep the name: HUGGING_FACE_HUB_TOKEN ):</p><p><strong>Optional: set vLLM model deployment config parameters:</strong></p><p>Update vllm-deploy.yml file as described earlier,</p><p>You can override the command and arguments,</p><p>if you prefer to Langchain and OpenAI integration in applications, you can use this:</p><p><em>command: [“python3”, “-m”, “vllm.entrypoints.openai.api_server”]</em></p><p>or you can use different entrypoint for native vLLM APIs:</p><p><em>command: [“python3”, “-m”, “vllm.entrypoints.api_server”]</em></p><p>To understand the vLLM model related arguments, See this doc: <a href="https://docs.vllm.ai/en/latest/models/engine_args.html">https://docs.vllm.ai/en/latest/models/engine_args.html</a></p><p>You can adjust the model related parameters in args settings in vllm-deploy.yaml</p><p><em>— model=ModelNameFromHuggingFace, replace with specific models from Huggingface such as: </em>google/gemma-1.1–7b-it,<em> </em>google/gemma-1.1–2b-it, <em>meta-llama/Llama-2–7b-hf, meta-llama/Llama-2–13b-hf, mistralai/Mistral-7B-v0.1, tiiuae/falcon-7b</em></p><p>Tip: If you use Vertex vLLM image, — model value you can be full Cloud Storage path of model files, e.g., gs://vertex-model-garden-public-us-central1/llama2/llama2–13b-hf, check your access permission to the storage bucket first before you make the update</p><p><strong>Deploy the model to GKE</strong></p><p>After vllm-deploy.yaml file been updated with proper settings, execute the following command:</p><pre>kubectl apply -f vllm-deploy.yaml -n $NAMESPACE</pre><p>The following GKE artifacts will be created:</p><p>a. vllm-server deployment</p><p>b. Ingress</p><p>c. Service with endpoint of LLM APIs, routing traffic through Ingress</p><p>Check all the objects you’ve just created:</p><pre>kubectl get all -n $NAMESPACE</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxLuWvRBLJPmStVr5mGzkw.png" /></figure><p>Check that the pod has been correctly scheduled in one of the nodes in the g2-standard-8 node pool that has the GPUs available:</p><p><strong>Model Deployment Initial Tests</strong></p><p>Simply run the following command to get the cluster ip:</p><pre>kubectl get service/vllm-inference-server -o jsonpath=&#39;{.spec.clusterIP}&#39; -n $NAMESPACE</pre><p>Then use the following command to test inside the Cluster:</p><pre>kubectl run curl-test --image=radial/busyboxplus:curl -i --tty --rm<br></pre><p>then update and execute the following when you get prompted:</p><pre>curl http://ClusterIP:8000/v1/models<br>curl http://ClusterIP:8000/v1/completions \<br>-H &quot;Content-Type: application/json&quot; \<br>-d &#39;{<br>&quot;model&quot;: &quot;meta-llama/Llama-2–7b-hf&quot;,<br>&quot;prompt&quot;: &quot;San Francisco is a&quot;,<br>&quot;max_tokens&quot;: 250,<br>&quot;temperature&quot;: 0.1<br>}&#39;</pre><h3><strong>Deploy WebApp</strong></h3><p>Since vLLM can expose different model as OpenAI style APIs, different models will be transparent applications how to access LLM models.</p><p>The sample app provided will use langchain vLLM OpenAI library to initialize any model deployed through vLLM with following python code( no need to run):</p><pre>import gradio as gr<br>import requests<br>import os<br>from langchain.llms import VLLMOpenAI<br>llm_url = os.environ.get(&#39;LLM_URL&#39;)<br>llm_name= os.environ.get(&#39;LLM_NAME&#39;)<br>llm = VLLMOpenAI(<br>openai_api_key=&quot;EMPTY&quot;,<br>openai_api_base=f&quot;{llm_url}/v1&quot;,<br>model_name=f&quot;{llm_name}&quot;,<br>model_kwargs={&quot;stop&quot;: [&quot;.&quot;]},<br>)</pre><p>You need to build the webapp container image first so that you can host the webapp inside the same GKE cluster:</p><p>The following is the cloudbuild.yaml file under webapp directory to replace your own artifactory repository paths,</p><pre>steps:<br>- name: &#39;gcr.io/cloud-builders/docker&#39;<br>args: [ &#39;build&#39;, &#39;-t&#39;, &#39;us-east1-docker.pkg.dev/$PROJECT_ID/gke-llm/vllm-client:latest&#39;, &#39;.&#39; ]<br>images:<br>- &#39;us-east1-docker.pkg.dev/$PROJECT_ID/gke-llm/vllm-client:latest&#39;<br></pre><p>Let’s run the build to build sample app container image use Cloud Build:</p><pre>cd webapp<br>gcloud builds submit .</pre><p>Next, update the vllm-client.yaml file,</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: vllm-client<br>spec:<br>  selector:<br>    matchLabels:<br>      app: vllm-client<br>  template:<br>    metadata:<br>      labels:<br>        app: vllm-client<br>    spec:<br>      containers:<br>      - name: gradio<br>        image: us-east1-docker.pkg.dev/PROJECT_ID/gke-llm/vllm-client:latest<br>        env:<br>          - name: LLM_URL<br>            value: &quot;http://CLusterIP:8000&quot;<br>          - name: LLM_NAME<br>            value: &quot;meta-llama/Llama-2-7b-hf&quot;<br>          - name: MAX_TOKENS<br>            value: &quot;400&quot;<br>        resources:<br>          requests:<br>            memory: &quot;128Mi&quot;<br>            cpu: &quot;250m&quot;<br>          limits:<br>            memory: &quot;256Mi&quot;<br>            cpu: &quot;500m&quot;<br>        ports:<br>        - containerPort: 7860<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: vllm-client-service<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: vllm-client<br>  ports:<br>  - port: 8080<br>    targetPort: 7860<br></pre><p>Need to update the following:</p><ol><li>- image: us-east1-docker.pkg.dev/PROJECT_ID/gke-llm/vllm-client:latest</li></ol><p>2. - name: LLM_URL</p><p>value: “http://CLusterIP:8000&quot;</p><p>3. - name: LLM_NAME</p><p>value: “meta-llama/Llama-2–7b-hf” ( replace with your own Huggingface LLM Model setup earlier)</p><p>Run the command to deploy webapp:</p><pre>cd ..<br>kubectl apply -f vllm-client.yaml -n $NAMESPACE<br>kubectl get service/vllm-client-service -o jsonpath=&#39;{.spec.externalIP}&#39; -n $NAMESPACE</pre><p><strong>Validations:</strong></p><p>Go to the external IP for the webapp, http://externalIP:8080,</p><p>and test a few questions from the web application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-eT6azd2dVOUymndFPvuQ.png" /></figure><h3><strong>Cleanups</strong></h3><p>Don’t forget to clean up the resources created in this article once you’ve finished experimenting with GKE and Mistral 7b, as keeping the cluster running for a long time can incur in important costs. To clean up, you just need to delete the GKE cluster:</p><pre>gcloud container clusters delete $CLUSTER_NAME - region $REGION</pre><h3><strong>Conclusion</strong></h3><p>This post tries to demonstrate how deploying Open source LLM models such as Mistrial 7B and Llama2 7B/13B using vLLM on GKE is flexible and straightforward.</p><p>LLM operations and self manage AI ML workload in flagship Managed kubernates platform GKE enables deploying LLM models in production, bringing ML Ops one step closer to existing platform teams with expertises in those managed platforms. Also, given the resources that are consumed, and the number of potential applications using AI/ML features moving forward, having a framework that offers scalability and cost control features simplifies adoption.</p><p>Don’t forget to check out other GKE related resources on AI ML infrastructure offered by Google Cloud and check the resources included in the <a href="https://cloud.google.com/kubernetes-engine/docs/integrations/ai-infra">AI/ML orchestration on GKE</a> documentation.</p><p>For your reference, the code snipptes listed in this blog can be find in this <a href="https://github.com/llm-on-gke/vllm-inference/tree/main">source code repo</a></p><p><em>Update on May 9: google/gemma-1.1–7b-it, and google/gemma-1.1–2b-it model fully tested.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e522b3679ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/serving-open-source-llms-on-gke-using-vllm-framework-5e522b3679ee">Serving Open Source LLMs on GKE using vLLM framework</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>