Kubernetes – Introduction and Integration with GenAI
local graph
Chapter 2 — Kubernetes – Introduction and Integration with GenAI
Section titled “Chapter 2 — Kubernetes – Introduction and Integration with GenAI”Deploying and managing GenAI workloads at scale presents significant challenges, including building the models, packaging them for distribution, and ensuring effective deployment and scaling. In this chapter, we will discuss the concepts of containers and Kubernetes (K8s) and why they are emerging as powerful solutions to address these complexities. They are becoming the de facto standard for companies such as OpenAI (https://openai.com/index/scaling-kubernetes-to-7500-nodes/) and Anthropic (https://youtu.be/c9NJ6GSeNDM?si=xjei4T9VfZvejD5o&t=2412) to deploy GenAI workloads. We will cover the following main topics:
- Understanding containers
- Why containers for GenAI models
- What is Kubernetes (K8s)?
Understanding containers
Section titled “Understanding containers”Containers have revolutionized the way we manage applications by standardizing the packaging format. With the portability of containers, applications are packaged as a standard unit of software that packages all of your code and dependencies to deploy consistently and reliably across various environments, such as on-premises, public, and private clouds. Containers are also considered an evolution of Virtual Machine (VM) technology, where multiple containers are run on the same operating system, sharing the underlying kernel to increase the overall server utilization. This is a massive advantage of containers as there is no overhead of multiple Operating Systems (OSes) and other OS-level components. So, containers can be started and stopped a lot faster while providing isolation.
The following figure illustrates the evolution of computing environments, highlighting a shift toward higher levels of abstraction and an increased focus on business logic.

Figure 2.1 – Evolution of container technology
Physical servers offer the least abstraction, with extensive manual configuration, and resource inefficiencies. VMs provide a middle ground, by abstracting underlying hardware resources using hypervisor technology. This allows you to run multiple VMs on the same physical server, increasing the resource utilization and security. However, they are bulky and slow to boot up. Containers provide the highest level of abstraction by encapsulating applications and dependencies in portable units, allowing us to focus more on developing and optimizing business logic rather than managing infrastructure. Figure 2*.2* illustrates the high-level differences between VMs and containers.

Figure 2.2 – Virtual machines versus containers
Container technology is made possible because of namespaces and cgroups (control groups) in the Linux kernel. They form the foundational building blocks to provide isolation and resource limits. A Linux Namespace (https://man7.org/linux/man-pages/man7/namespaces.7.html) is an abstraction over resources in the operating system. It partitions OS-level resources such that different sets of processes see a different set of resources (network, file system, etc.,) even though they are running on the same OS kernel. Cgroups (https://man7.org/linux/man-pages/man7/cgroups.7.html) govern the isolation and usage of system resources, such as CPU, memory, and network, for a group of processes and optionally enforce limits and constraints. These capabilities let containers abstract the operating system components for modern applications.
Container terminology
Section titled “Container terminology”The following are some terms associated with containers that will be crucial in following along with this book:
- Container runtime: This is a host-level process that is responsible for creating, stopping, and starting containers. It interacts with low-level container runtimes such as runc to set up namespaces and cgroups for containers. Popular examples include containerd, CRI-O, and so on.
- Container image: This is a lightweight, standalone, executable package that includes everything needed to run a piece of software, including the code, runtime, libraries, environment variables, and configuration files. It is created using a Dockerfile, a plain text definition file that includes a set of instructions to install dependencies, applications, and so on. Typical characteristics of a container image include the following:
- Self-contained: It encapsulates everything needed to run software applications.
- Immutable: It is read-only in nature; any changes would require a new image.
- Layered: Images are built in layers, each layer representing a file system. This is what makes images highly efficient as common layers can be shared across multiple images.
- Portable: As the image packages the application and all its dependencies, they can be run on any system that supports a container runtime, making them highly portable in nature.
- Self-contained: It encapsulates everything needed to run software applications.
- Container registry: This is a tool used to manage and distribute container images. Popular registries include Docker Hub (https://hub.docker.com/), Amazon Elastic Container Registry (https://aws.amazon.com/ecr/), Google Artifact Registry (https://cloud.google.com/artifact-registry), and so on. Tools such as Artifactory and Harbor can be used to self-host a registry.
- Container: This is a running instance or process created from the container image by the container runtime.
Let’s now understand the high-level container workflow using Docker, a software platform designed to help developers build, share, and run container applications. Docker follows traditional client-server architecture. When you install Docker on a host, it runs a server component called the Docker daemon and a client component – the Docker CLI. The Daemon is responsible for creating and managing images, running containers using those images, and setting up networking, storage, and so on. As depicted in Figure 2*.3*, the Docker CLI is used to interact with the Docker daemon process to build and run containers. Once the images are built, the Docker daemon can push and pull those images to/from a container registry. Storing the images in a container registry allows them to be portable and they can be run anywhere a container runtime is available.

Figure 2.3 – Docker architecture overview
Creating a container image
Section titled “Creating a container image”Let’s create our first hello world container image and run it locally. Use the Docker documentation page at https://docs.docker.com/engine/install/ to install Docker Engine on your machine. The following are the links to install Docker Desktop for different operating systems:
- Docker Desktop for Linux: https://docs.docker.com/desktop/install/linux-install/
- Docker Desktop for Mac (macOS): https://docs.docker.com/desktop/install/mac-install/
- Docker Desktop for Windows: https://docs.docker.com/desktop/install/windows-install/
In the following Dockerfile, we are creating a simple hello world application using the nginx server. We will use nginx as the parent image and customize the index.html with our Hello World! message. Let’s start by following these steps:
- Create a Dockerfile with the
FROM nginxRUN echo "Hello World!" > /usr/share/nginx/html/index.html
- Build a container image with a
v1You can list the local container images using the following command:$ docker build -t hello-world:v1 .$ docker imagesREPOSITORY TAG IMAGE ID CREATED SIZEhello-world v1 7a5469eb898f 2 mins ago 273MB - Run a container using the
hello-worldimage and bind nginx port80to the8080$ docker run -p 8080:80 hello-world:v1 - Now that we have the image running, we can test the container by calling
8080$ curl http://localhost:8080/Hello World!
As an optional step, you can also push the container image to an xyz container registry so that you can run it anywhere. Replace xyz with your container repository name. For example, follow the instructions at https://www.docker.com/blog/how-to-use-your-own-registry-2/ to create the registry in Docker Hub:
$ docker tag hello-world:v1 xyz/hello-world:v1$ docker push xyz/hello-world:v1In this section, we learned about the evolution of computing environments, the benefits of using containers over traditional physical servers, and VMs. We gained an understanding of the overall Docker architecture and various key container terminology and built and ran our first hello-world container application. Let’s explore why containers are a great fit for GenAI models.
Why containers for GenAI models?
Section titled “Why containers for GenAI models?”A typical challenge with developing ML or GenAI applications involves using complex and continuously evolving open source ML frameworks such as PyTorch and TensorFlow, ML tool kits such as Hugging Face Transformers, ever-changing GPU hardware ecosystems from NVIDIA, and custom accelerators from Amazon, Google, and so on.
The following figure illustrates various components involved in creating and running an ML or GenAI container.

Figure 2.4 – A typical GenAI container image
At the top layers, the container encapsulates various software libraries, deep learning frameworks, and user-supplied code. The next set of layers contains hardware-layer-specific libraries to interact with GPUs or custom accelerators on the host. The container runtime can be used to launch the containers from the container image. Let’s dive into the significant benefits of using containers for GenAI workloads:
- Dependency management: This could become crucial due to evolving frameworks and interdependencies on specific versions. With containers, we can encapsulate the GenAI application code and its dependencies in a container image and use it on a developer machine or in the test/production environment consistently.
- Resource access: GenAI/ML apps are computationally intensive, need access to single or multiple GPUs or custom accelerators, and adjust resource allocations dynamically based on the workload demand. Containers allow for fine-grained control over resource allocation, enabling efficient utilization of the available resources and avoiding noisy neighbor situations. Containers can also be scaled horizontally or vertically to handle increased demand in the applications.
- Model versioning and updates: Managing different versions of the model and keeping respective dependencies up to date without disrupting applications could be challenging. With containers, different images can be created and versioned, making it easy to track changes, manage different model versions, and seamlessly execute rollbacks if needed. We will also explore how to use container orchestration engines to automate these updates later, in Chapter 11.
- Security: Protecting data during the training and inference stages is crucial when developing GenAI apps. With containers, we can enforce strict access controls and policies for data access, minimize the attack surface by including only the necessary components in the container image, and they also provide a layer of isolation between the containers and the underlying host.
By providing isolated, consistent, and reproducible environments, containers can simplify dependency management, optimize resource efficiency, streamline model deployments, and improve overall system security. Container technology comprehensively addresses all challenges presented by GenAI application development, thus making it a de facto choice.
Building a GenAI container image
Section titled “Building a GenAI container image”Let’s get a first-hand experience of building our first GenAI container image and deploying it locally. To get started, we will download the model files from Hugging Face (https://huggingface.co/), an AI/ML platform that helps users build, deploy, and test machine learning models. Hugging Face operates the Model Hub, where developers and researchers can share thousands of pre-trained models. It also supports various frameworks, including TensorFlow, PyTorch, and ONNX.
In this walk-through, we will take one of the popular open source models, Llama 2 (https://llama.meta.com/llama2/), by Meta. However, you have to read and comply with the terms and conditions of the model. Navigate to the Hugging Face Llama model page (https://huggingface.co/meta-llama/Llama-2-7b) to request access to the model. The Llama 2 model comes in multiple sizes: 7B, 13B, and 70B where B stands for billion parameters. The bigger the size of the model, the greater the resources needed to host it. Given not all personal laptops are equipped with specialized hardware such as GPUs, we will be using the CPU version of the Llama 2 model. This was made possible because of llama.cpp (https://github.com/ggerganov/llama.cpp), an open source project aimed at providing an efficient and portable implementation of Llama models. It enables us to deploy these models on various platforms, including personal computers, without requiring GPUs. llama.cpp applies a custom quantization approach to compress the models in a GGUF format, to reduce the size and resource requirements.
An inference endpoint is created using the Python Flask API (https://flask.palletsprojects.com/), which provides an HTTP POST API on port 5000 and accepts a JSON request with an input prompt, system message, and so on. Input parameters are then passed to the Llama model and model output is returned in the JSON format. Let’s begin the process:
- Install the pre-requisites:
huggingface-clifrom https://huggingface.co/docs/huggingface_hub/en/installationjqfrom https://jqlang.github.io/jq/download/- Docker Engine from https://docs.docker.com/engine/install/
- Authenticate to the Hugging Face platform by following the instructions at https://huggingface.co/docs/huggingface_hub/en/guides/cli.
- Download the Llama 2 model
huggingface-cli$ huggingface-cli download TheBloke/Llama-2-7B-Chat-GGUF llama-2-7b-chat.Q2_K.gguf --local-dir . --local-dir-use-symlinks False - The following message is displayed when the model download
$ Download complete. Moving file to llama-2-7b-chat.Q2_K.ggufllama-2-7b-chat.Q2_K.gguf
- Create an
app.pywith our Flask code. This code block sets up a Python Flask app with a single route,/predict, that accepts HTTP POST requests. It uses thellama_cpplibrary to load the Llama 2 model, generates a response based on the input prompt and system message from the request, and returns the model’s response as a JSON object. You can download theapp.pycode from GitHub at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch2/app.py:from flask import Flask, request, jsonifyimport llama_cppapp = Flask(__name__)model = llama_cpp.Llama("llama-2-7b-chat.Q2_K.gguf")@app.route('/predict', methods=['POST'])def predict():data = request.jsonprompt = f"""<s>[INST] <<SYS>>{data.get('sys_msg', '')}<</SYS>>{data.get('prompt', '')} [/INST]"""response = model(prompt, max_tokens=1000)return jsonify({'response': response})if __name__ == '__main__':app.run(host='0.0.0.0', port=5000) - Create a Dockerfile that packages the Python source code, Llama 2 model, and other dependencies. You can download the Dockerfile code from GitHub https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch2/Dockerfile
# Use an official Python runtime as a parent imageFROM python# Set the working directoryWORKDIR /app# Expose the application on port 5000EXPOSE 5000# Define environment variableENV FLASK_APP=app.py# Install any needed packages specified in requirements.txtRUN pip install --no-cache-dir flask llama-cpp-python# Copy the current dir contents into the container at /appCOPY . /app# Run app.py when the container launchesCMD ["python", "app.py"]
- Build the
$ docker build -t my-llama .
- Run the container and bind the Flask API server to host
8000$ docker run -p 8000:5000 my-llama - Invoke the Llama 2 model by
curl$ curl -X POST http://localhost:8000/predict -H "Content-Type: application/json" -d '{"prompt":"Create a poem about humanity?","sys_msg":"You are a helpful, respectful, and honest assistant. Always provide safe, unbiased, and positive responses. Avoid harmful, unethical, or illegal content. If a question is unclear or incorrect, explain why. If unsure, do not provide false information."}' | jq .
This will run the inference against our local my-llama container and return the following LLM response:
……Of course, I'm here to assist you with a safe and positive response! Here's a poem about humanity:Humanity, oh humanity, so diverse and wide,A mix of cultures, beliefs, and ideals inside.We may come from different places, with different views,But beneath our differences, we share a common brew.……So here's to humanity, in all its grace and might,A masterpiece of diversity, a work of art in sight.Let us cherish each other, with kindness and respect,And create a world where love is the only text.The input request contains two key attributes:
- Prompt: Input to the LLM
- System message: To set the context and guide the behavior of the LLM during the request
Optionally, we can pass additional attributes such as max_tokens to limit the length of the generated output.
If you notice the size of the image we built, it will be around 7+ GB. That is mainly attributed to the model file and other dependencies. We will explore techniques for reducing the size of the image and optimizing the container startup time later, in Chapter 9.
It was easy to create and run a single container instance on our local computer. Just imagine operating hundreds or thousands of these containers running across hundreds or thousands of VMs, and making sure these containers are highly available, scalable, load balanced, managing resource allocations, and implementing automated deployments and rollbacks. This is where Container Orchestrators come to the rescue.
Container orchestrators play a pivotal role in modern software development and deployment, addressing all the preceding concerns and managing containerized applications at scale. Some of their key benefits are as follows:
- High availability and fault tolerance: They continuously monitor the health of the containers at regular intervals and automatically restart/replace failed containers, thus ensuring the desired number of containers are always up and running.
- Scaling: They enable automatic scaling of the applications to match the user load/demand. Container instances are automatically created and removed in response to the application load. As applications are scaled, underlying compute resources are also scaled to accommodate the new containers.
- Automated deployments: They automate the deployment of containerized applications across multiple hosts and rollbacks in case of any failures. We can also implement advanced traffic routing patterns such as canary releases and blue/green deployments to safely roll out new changes.
- Load balancing: They provide built-in load balancing to distribute incoming traffic across multiple container instances, improving performance and reliability. They can also integrate with external load-balancing solutions to load-balance the traffic.
- Service discovery: As containers are ephemeral in nature, orchestrators provide service discovery features to dynamically discover the container endpoints to facilitate inter-service communication. They also manage the container networking, including IP address management, DNS resolution, and network segmentation.
- Observability: They can integrate with monitoring and logging tools, providing visibility into the health and performance of containerized applications.
- Resource management and advanced scheduling: They can also manage the resource allocation for the containers, including CPU, memory, GPUs, and so on. They enforce the resource limits and reservations, preventing noisy neighbor situations. Advanced scheduling policies can be used to schedule the applications with special hardware needs such as GPUs to the specific hosts.
Now that we understand the need for a container orchestrator, the next question is which orchestrator should we pick? There are a number of different open source and proprietary orchestrators on the market. Some notable ones are the following:
- Amazon Elastic Container Service (https://aws.amazon.com/ecs/)
- Azure Container Apps (https://azure.microsoft.com/en-us/products/container-apps)
- Docker Swarm (https://docs.docker.com/engine/swarm/)
- Apache Mesos (https://mesos.apache.org/)
- Kubernetes (https://kubernetes.io/), and managed Kubernetes offerings such as Amazon Elastic Kubernetes Service (https://aws.amazon.com/eks/)
- **Google Kubernetes Engine (**GKE) (https://cloud.google.com/kubernetes-engine)
- **Azure Kubernetes Service (**AKS) (https://azure.microsoft.com/en-us/products/kubernetes-service)
- Red Hat OpenShift (https://www.redhat.com/en/technologies/cloud-computing/openshift)
In this section, we learned about the typical challenges of building GenAI models and how we can use container technology to package GenAI code/models, AI/ML frameworks, hardware-specific libraries, and other dependencies into an image for consistency, reusability, and portability. We also built our first GenAI container image using the open source Llama 2 model and ran inference by deploying it locally. Finally, we discussed the challenges of managing containerized applications at scale and how container orchestrators such as K8s can solve those. In the next section, let’s dive into K8s and its architecture, and why it is a great fit to run GenAI models.
What is Kubernetes (K8s)?
Section titled “What is Kubernetes (K8s)?”Kubernetes, commonly referred to as K8s, is an open source container orchestration platform that automates the deployment, scaling, and management of containerized applications. It is the most widely used container orchestration platform (https://www.cncf.io/reports/kubernetes-project-journey-report/) and has become the de facto choice for many enterprises to run a wide variety of workloads.
Originally developed by Google engineers Joe Beda, Brendan Burns, and Craig McLuckie in 2014 and now maintained by the Cloud Native Computing Foundation (CNCF), its name came from the Ancient Greek for a pilot or helmsman (the person at the helm who steers the ship). It has become the second largest open source project in the world, after Linux, and is the primary orchestrator tool for 71% of Fortune 100 companies (https://www.cncf.io/reports/kubernetes-project-journey-report/). According to Gartner’s The CTO’s Guide to Containers and Kubernetes (https://www.gartner.com/en/documents/5128231), by 2027, more than 90% of global organizations will be running containerized applications in production.
Some notable factors in K8s becoming so popular are as follows:
- Rich community and ecosystem: With 77K+ contributors from 44 different countries and contributed to by 8K+ companies, K8s has the most vibrant and active community (https://www.cncf.io/reports/kubernetes-project-journey-report/). The CNCF survey indicates that Kubernetes-related projects (such as Helm, Prometheus, and Istio) are also widely adopted, further strengthening its ecosystem.
- Comprehensive features: K8s offers a rich set of features including automated rollouts and rollbacks, self-healing, horizontal scaling, service discovery, and load balancing. These capabilities make it a versatile and powerful tool for managing containerized applications.
- Portability: K8s abstracts away the underlying infrastructure, enabling applications to be deployed consistently whether on-premises, in public, private, or hybrid clouds, or edge locations.
- Managed K8s services: The availability of the managed K8s offerings from major cloud providers such as Amazon EKS, GKE, and AKS has significantly lowered the barrier to entry. These offerings take away the operational complexities of running and operating K8s clusters, allowing enterprises to focus on their core business objectives.
- Strong governance: K8s has been governed by CNCF since 2016, which fosters collaborative development and community participation, enabling contributions from a diverse group of developers, organizations, and end users. It follows an open source model with well-defined governance structures, including special interest groups (SIGs) that focus on specific areas of development and operations.
- Declarative configuration: K8s uses a declarative approach for configuration management, allowing users to define the desired state of their applications and infrastructure using YAML or JSON files. As depicted in Figure 2*.5*, K8s controllers continuously monitor the current state of a resource and automatically reconcile to match the desired state, simplifying operations and ensuring consistency.

Figure 2.5 – How K8s controllers work
- Extensibility: This is probably the most significant reason why K8 became so popular. K8s is designed with a modular architecture, supporting custom plugins and extensions through well-defined APIs. This enabled developers and companies to extend or customize the K8s functionality without modifying the upstream code, fostering innovation and adaptability.
Next, let’s look at the architecture of Kubernetes.
Kubernetes architecture
Section titled “Kubernetes architecture”K8s architecture is based on running clusters that allow your applications/containers to run across multiple hosts. Each cluster consists of two types of nodes:
- Control plane: The K8s control plane is the brain behind cluster operations. It consists of critical components such as kube-apiserver, etcd, the scheduler manager, the controller manager, and the cloud controller manager.
- Data plane/worker nodes: The K8s data plane running on the worker nodes is composed of several key components, such as kube-proxy, the kubelet, and the Container Network Interface (CNI) plugin.
Figure 2*.6* depicts the high-level K8s cluster architecture. You will notice kube-apiserver is the frontend of the K8s control plane and interacts with the other control plane components, such as controller managers, etcd, and so on, to fulfil the requests. K8s worker nodes host several key components, responsible for taking instructions from kube-apiserver, executing them on the worker node, and reporting back on the status.

Figure 2.6 – Kubernetes cluster architecture
Control plane components
Section titled “Control plane components”The primary components of a control plane are as follows:
- kube-apiserver: This serves as the entry point or frontend into the K8s cluster and the central management component that exposes the K8s API. K8s users, administrators, and other components use this API to communicate with the cluster. It also communicates with the etcd component to save the state of K8s objects. It also handles authentication and authorization, validation, and request processing, and communicates with other control plane and data plane components to manage the clusters’ states.
- etcd: This is the distributed key-value store and is used as the K8s backing store for all cluster state. It stores the configuration data of all K8s objects and any updates made to them and ensures the cluster state is always reliable and accessible. It’s critical to take regular backups of the etcd database so that clusters can be restored in case of any disruptions.
- kube-controller-manager: This is responsible for managing various controllers in the cluster. This includes the default upstream controllers and any custom-built ones. Some examples include the following:
- Deployment controller: This watches for K8s deployment objects and manages the updates to K8s Pods.
- kube-scheduler: This is responsible for scheduling the K8s Pods on the worker nodes. It monitors the API server for newly created Pods and assigns a worker node based on the resource availability, scheduling requirements defined in the Pod configuration such as nodeSelectors, Pod/node affinity, topology spreads, and so on. When unable to schedule a Pod due to resource exhaustion and so on, it will mark the Pods as Pending so that other operational add-ons such as the cluster autoscaler can kick in and add/remove compute capacity (worker nodes) to the cluster.
- cloud-controller-manager: This manages the cloud-specific controllers to handle the cloud provider API calls for resource management. It’s the gateway to the Cloud Provider API from the K8s core and is responsible for creating and managing cloud-provider-specific resources (such as nodes, LoadBalancers, and so on) based on changes to K8s objects (such as nodes, Services, and so on). Some examples include the following:
- Node controller: This is responsible for monitoring the health of the worker nodes and handling the addition or removal of nodes in the cluster
- Service controller: This watches for service and node object changes, and creates, updates, and deletes cloud provider load balancers accordingly
- Node controller: This is responsible for monitoring the health of the worker nodes and handling the addition or removal of nodes in the cluster
Data plane components
Section titled “Data plane components”The primary components of a data plane are as follows:
- kubelet: This is an agent that runs on every worker node in the cluster. It’s responsible for taking instructions from kube-apiserver, executing them on the respective worker node, and reporting the updates on the node components back to the cluster control plane. It interacts with other node components such as the container runtime to launch container processes, the CNI plugin to set up the container networking, and CSI plugins to manage the persistent volumes and so on.
- kube-proxy: This is a network proxy that runs on each worker node in the cluster, implementing the K8s service concept. It maintains the network routing rules on the worker node, to allow the network communications to and from your Pods from within/outside the cluster. It uses the operating system packet filtering layer, such as IP tables, IPVS, and so on, to route the traffic to other endpoints in the cluster.
- Container runtime: containerd is the de facto container runtime responsible for launching the containers on the worker node. It is responsible for managing the lifecycle of containers in the K8s environment. K8s also supports other container runtimes such as CRI-O.
Apart from these components, it’s essential to deploy additional add-on software on the K8s cluster for production operations. These add-ons add capabilities such as monitoring, security, and networking.
Add-on software components
Section titled “Add-on software components”Here are a few examples of add-on software:
- CNI plugin: This is a software add-on that implements container network specifications. They adhere to the K8s networking tenets and are responsible for allocating IP addresses to K8s Pods (https://kubernetes.io/docs/concepts/workloads/pods/) and enabling them to communicate with each other within the cluster. Popular add-ons in this space are Cilium (https://github.com/cilium/cilium), Calico (https://github.com/projectcalico/calico), and Amazon VPC CNI (https://github.com/aws/amazon-vpc-cni-k8s).
- CSI plugin: This is a software add-on that implements container storage interface specifications. They are responsible for providing persistent storage volumes to K8s Pods and managing the lifecycle of those volumes. A couple of notable add-ons are Amazon EBS CSI driver (https://github.com/kubernetes-sigs/aws-ebs-csi-driver) and Portworx CSI Driver (https://docs.portworx.com/portworx-enterprise/operations/operate-kubernetes/storage-operations/csi).
- CoreDNS: This is an essential software add-on that provides DNS resolution within the cluster. Containers launched in K8s worker nodes automatically include this DNS server in their DNS searches.
- Monitoring plugins: This is a software add-on that provides observability into the cluster infrastructure and workloads. They extract essential observability details such as logs, metrics, and traces and write to monitoring platforms such as Prometheus, Amazon CloudWatch, Splunk, Datadog, and New Relic.
- Device plugins: Modern AI/ML apps use specialized hardware devices such as GPUs from NVIDIA, Intel, and AMD and custom accelerators from Amazon, Google, and Meta. K8s provides a device plugin framework that you can use to advertise system hardware resources to the kubelet and control plane so that you can make scheduling decisions based on their availability.
This is not an exhaustive list of all K8s components and add-ons. We will dive into AI/ML-related add-ons in a later part of the book.
In this section, we dove into K8s architecture, learned about various control plane and data plane components, and explored the advantages of the K8s platform and why it became the de facto standard in the community. Let’s understand why K8s is a great fit for running GenAI models next.
Why K8s is a great fit for GenAI models
Section titled “Why K8s is a great fit for GenAI models”Now that we understand the K8s architecture, its components, and the advantages of the platform, let’s discuss how we apply those to solve common challenges with operating GenAI models.
Challenges of running GenAI models
Section titled “Challenges of running GenAI models”Some common challenges of running GenAI models are as follows:
- Computational requirements: GenAI models are increasingly becoming large and complex, thus requiring substantial computational resources, including GPUs, TPUs, and custom accelerators for training and inference. Managing these resources efficiently is crucial to ensure performance and cost-efficiency.
- Scalability: As the demand for AI/ML services increases, scaling GenAI models to handle the demand is essential. This requires seamless scaling of computational resources without sacrificing the performance and cost of the models.
- Observability: As GenAI models proliferate, it’s critical to understand their performance by monitoring both business-level KPIs and the health of the overall system using logs and metrics.
- Data management: GenAI models rely on vast amounts of data for both training and inference. Data preparation, security, and management are critical in increasing the model’s accuracy and performance.
- Deployment complexity: As we learned earlier in this chapter, all GenAI models require custom frameworks, plugin libraries, and other dependencies to deploy them. This complexity can lead to deployment issues, delays, and increased errors.
K8s advantages
Section titled “K8s advantages”K8s offers several advantages for addressing the challenges of running GenAI models, such as the following:
- Efficient resource management: K8s has a robust resource management system built into kube-scheduler. It automates the distribution of K8s Pods into the worker nodes while meeting different scheduling requirements/constraints. Schedulers can be configured to operate in lowest-cost, random, or bin-pack modes for flexibility. With the K8s extensibility, you can develop custom schedulers and use them for scheduling workloads. A common application of this is to schedule training or inference workloads on devices with custom devices such as AWS Trainium and Inferentia. By using K8s, we can implement dynamic resource allocation based on model requirements, thus optimizing costs and improving performance.
- Seamless scalability: Training or fine-tuning a GenAI model requires a significant number of computational resources. Inference endpoints of these models also need to scale horizontally based on the workload demand. This will be achieved seamlessly using K8s autoscaling mechanisms such as Horizontal Pod Autoscaling (HPA) (https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/), Vertical Pod Autoscaling (VPA) (https://github.com/kubernetes/autoscaler/tree/master/vertical-pod-autoscaler), and Cluster Autoscaling (https://kubernetes.io/docs/concepts/cluster-administration/cluster-autoscaling/). HPA automatically scales a workload resource (such as a Deployment or StatefulSet) to match the workload demand. It does this by creating and deploying new K8s Pods in response to the demand. VPA automatically adjusts the resource limits (such as CPU, memory, and so on) of Pods to match their actual usage. It helps in optimizing resource allocation, ensuring workloads are run efficiently. Cluster autoscaling is responsible for ensuring the right number of resources are attached to the cluster at all times. We will take a deeper look at these mechanisms in Chapter 6.
- Extensibility: Extensibility plays a crucial role in running GenAI workloads on K8s. It allows you to extend the functionality of K8s in a scalable manner without modifying the upstream code. We can use custom-built add-ons such as Kubeflow (https://www.kubeflow.org/), an AI/ML platform that provides custom resources for managing ML pipelines, model training, and deployment. Hardware companies can also leverage this by developing device plugins to manage GPU resources in K8s so that GenAI training and inference workloads are scheduled accordingly. GenAI workloads often require specific frameworks such as PyTorch, TensorFlow, and Jupyter Notebook. We can use custom-built operators to integrate these frameworks and tools for seamless development and deployment.
- Security: K8s has many in-built security mechanisms to secure GenAI workloads. One can use Role-Based Access Control (RBAC) (https://kubernetes.io/docs/reference/access-authn-authz/rbac/) to limit access to resources, ensuring that only authorized users or applications can access sensitive data. K8s Secrets or external secret management solutions can be used to safeguard sensitive information. K8s network policies can be used to implement network segmentation so that only authorized Pods can access data stores. On top of this, we can enable security controls such as encryption, audit logging, security scanning, and Pod Security Standards (PSS) (https://kubernetes.io/docs/concepts/security/pod-security-standards/) to ensure a robust security posture. We will explore all these features in detail in Chapter 9.
- High Availability (HA) and fault tolerance: These play a critical role in running GenAI workloads efficiently and reliably. Foundational model training often takes weeks or months. If a node or Pod fails, K8s’s in-built self-healing mechanism can automatically schedule the job to another node, thus minimizing interruptions. AI frameworks can be used along with this to implement a checkpointing strategy, to save the training state periodically. For model inferencing, K8s can automatically scale inference Pods based on the demand and recover the failed ones by launching replacement Pods. K8s can also perform rolling blue/green updates to deploy new model versions and seamlessly roll back in case of failures. We will take a deeper look at this topic in Chapter 13.
- Rich ecosystem and add-ons: The Cloud Native Artificial Intelligence Whitepaper (https://www.cncf.io/wp-content/uploads/2024/03/cloud_native_ai24_031424a-2.pdf) underscores the growing adoption of Kubernetes-native tools and frameworks to streamline the development, training, and deployment of AI models. Notable examples include Kubeflow and MLflow for operating end-to-end ML platforms on K8s; KServe, Seldon, and RayServe for model serving and scaling; and OpenLLMetry, TruLens, and Deepchecks for model observability. This list will continue to grow as the industry matures around GenAI use cases.
In this section, we learned about the typical challenges of operating GenAI models and looked at the advantages of using K8s to address them. K8s extensibility, efficient resource management, security, HA, and fault tolerance capabilities make it a great fit to run GenAI models at scale.
Summary
Section titled “Summary”In this chapter, we started with the evolution of compute technologies and how containers emerged as a standard to package and ship applications and abstract away infrastructure complexities for developers. We discussed the benefits of using containers for GenAI models and built and ran our first hello-world, GenAI container images. Then we looked at the challenges of running and managing containers at scale and how container orchestrator engines such as K8s can help simplify that.
We dove into the high-level K8s architecture and various components that made up the control plane and data plane. We also learned how the extensibility, portability, declarative nature, and rich community behind K8s made it popular and the de facto container orchestrator in the market.
Finally, we discussed the typical challenges of operating GenAI workloads at scale and how K8s is a great fit to address those challenges with its efficient resource management, seamless scaling, extensibility, and security capabilities. In the next chapter, we will explore how to build a K8s cluster in a cloud environment, leverage popular open source tooling to manage GenAI workloads, and deploy our my-llama container in it.
Get This Book's PDF Version and Exclusive Extras
AppendixSection titled “Appendix”Following are some great resources for in-depth training on Kubernetes:
|