3.2 Orchestration with Kubeflow Pipelines
Choosing a Tool
Several tools exist for automating ML workflows. Apache Airflow is flexible and functional, but requires significant administrative effort. Prefect offers a modern interface and convenient state management, but has a less developed ecosystem. Kubeflow Pipelines is a specialized solution for ML tasks, tightly integrated with Kubernetes. For LLM systems it is especially convenient thanks to the flexibility of its components and good integration with cloud infrastructure.
Core Concepts
Figure 24. Key concepts of Kubeflow Pipelines.
Kubeflow Pipelines is built on several key concepts (see Fig. 24).
A pipeline is a description of a workflow in the form of a Python function with a decorator. It defines the sequence of steps and the dependencies between them.
Components are individual steps of a pipeline, each of which runs in its own container. They are isolated and reusable.
Artifacts are data passed between components. These can be simple types (for example, numbers or strings) as well as complex objects (files, models).
The Kubeflow Pipelines SDK provides modules for defining and compiling pipelines:
from kfp import dsl
from kfp import compiler
The dsl module contains decorators and classes for defining components and pipelines. The compiler module converts a Python definition into a YAML specification that can be run in Kubeflow.
Defining Components
Figure 25. Anatomy of a Kubeflow component.
A component in Kubeflow is a separate function that performs an atomic operation. It is defined with the @dsl.component decorator (see Fig. 25).
from kfp import dsl
@dsl.component(
base_image="python:3.10",
packages_to_install=["openai==1.0.0"]
)
def generate_embeddings(
texts: list,
model: str = "text-embedding-ada-002"
) -> list:
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
embeddings = []
for text in texts:
response = client.embeddings.create(
input=text,
model=model
)
embeddings.append(response.data[0].embedding)
return embeddings
The decorator specifies the base Docker image and additional packages to install. The types of the arguments and the return value define the component's interface. Kubeflow uses this information to serialize data between steps.
For simple components without external dependencies, a lightweight syntax can be used:
@dsl.component
def add_numbers(a: int, b: int) -> int:
return a + b
A Practical Example: A Documentation Indexing Pipeline
Figure 26. Documentation indexing pipeline — DAG.
Consider a typical scenario (Fig. 26): you need to regularly reindex a knowledge base from several sources. The sources include Confluence (the most widespread platform in companies), Google Docs, and local Markdown files. The pipeline should run weekly and on manual trigger after major updates.
If this pipeline were implemented as a set of scripts run by cron, problems would quickly arise. When one of the sources becomes unavailable, the script fails halfway through. Part of the data is loaded, part is not. The index ends up in an inconsistent state. Manual recovery takes hours of work.
Kubeflow solves these problems. Each source is processed by a separate component, and the failure of one does not affect the others. Artifacts are saved after each step, and on retry there is no need to restart the components that already succeeded. Logs and metrics of each run are available in the Kubeflow UI.
This is how components for loading from Confluence are defined:
from kfp import dsl
@dsl.component(
base_image="python:3.10",
packages_to_install=["atlassian-python-api==3.41.0"]
)
def load_confluence_docs(
space_key: str,
confluence_url: str
) -> list:
from atlassian import Confluence
import os
confluence = Confluence(
url=confluence_url,
username=os.environ.get("CONFLUENCE_USER"),
password=os.environ.get("CONFLUENCE_TOKEN")
)
pages = confluence.get_all_pages_from_space(space_key)
documents = []
for page in pages:
content = confluence.get_page_by_id(page["id"], expand="body.storage")
documents.append({
"id": page["id"],
"title": page["title"],
"content": content["body"]["storage"]["value"],
"source": f"confluence/{space_key}/{page['id']}"
})
return documents
Next, the component that splits documents into chunks:
@dsl.component(
base_image="python:3.10",
packages_to_install=["langchain==0.1.0", "tiktoken==0.5.0"]
)
def chunk_documents(
documents: list,
chunk_size: int = 1000,
chunk_overlap: int = 200
) -> list:
from langchain.text_splitter import RecursiveCharacterTextSplitter
splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap
)
chunks = []
for doc in documents:
doc_chunks = splitter.split_text(doc["content"])
for i, chunk_text in enumerate(doc_chunks):
chunks.append({
"text": chunk_text,
"source": doc["source"],
"chunk_index": i,
"metadata": {
"title": doc["title"],
"doc_id": doc["id"]
}
})
return chunks
The component for creating embeddings. An important point: processing in batches, so as not to overload the API:
@dsl.component(
base_image="python:3.10",
packages_to_install=["openai==1.0.0"]
)
def create_embeddings(
chunks: list,
model: str = "text-embedding-3-small"
) -> list:
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
texts = [chunk["text"] for chunk in chunks]
batch_size = 100
all_embeddings = []
for i in range(0, len(texts), batch_size):
batch = texts[i:i + batch_size]
response = client.embeddings.create(input=batch, model=model)
batch_embeddings = [item.embedding for item in response.data]
all_embeddings.extend(batch_embeddings)
for chunk, embedding in zip(chunks, all_embeddings):
chunk["embedding"] = embedding
return chunks
And finally, the component for indexing into a vector database (in this case, Pinecone):
@dsl.component(
base_image="python:3.10",
packages_to_install=["pinecone-client==2.2.0"]
)
def index_to_pinecone(
chunks: list,
index_name: str,
namespace: str
) -> str:
import pinecone
import os
pinecone.init(
api_key=os.environ.get("PINECONE_API_KEY"),
environment=os.environ.get("PINECONE_ENV")
)
index = pinecone.Index(index_name)
vectors = [
{
"id": f"{chunk['source']}_{chunk['chunk_index']}",
"values": chunk["embedding"],
"metadata": {
"text": chunk["text"],
"source": chunk["source"],
**chunk["metadata"]
}
}
for chunk in chunks
]
batch_size = 100
for i in range(0, len(vectors), batch_size):
batch = vectors[i:i + batch_size]
index.upsert(vectors=batch, namespace=namespace)
return f"Indexed {len(vectors)} vectors to {index_name}/{namespace}"
Combining Components into a Pipeline
Figure 27. Dependency graph of the indexing pipeline.
Now the components need to be combined into a pipeline by defining the dependencies (Fig. 27):
@dsl.pipeline(
name="documentation-indexing-pipeline",
description="Weekly indexing of documentation sources"
)
def indexing_pipeline(
confluence_space: str = "DOC",
confluence_url: str = "https://company.atlassian.net",
chunk_size: int = 1000,
chunk_overlap: int = 200,
embedding_model: str = "text-embedding-3-small",
pinecone_index: str = "documentation",
pinecone_namespace: str = "weekly"
):
load_task = load_confluence_docs(
space_key=confluence_space,
confluence_url=confluence_url
)
chunk_task = chunk_documents(
documents=load_task.output,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap
)
embed_task = create_embeddings(
chunks=chunk_task.output,
model=embedding_model
)
index_task = index_to_pinecone(
chunks=embed_task.output,
index_name=pinecone_index,
namespace=pinecone_namespace
)
Pipeline parameters make it possible to tune behavior without changing the code. This is convenient for running with different configurations or in different environments: dev, staging, and production.
Compilation and Running
Figure 28. Compiling and running a pipeline in Kubeflow.
The Python definition of the pipeline needs to be compiled into a YAML specification that Kubeflow understands (Fig. 28):
compiler.Compiler().compile(
pipeline_func=indexing_pipeline,
package_path="indexing_pipeline.yaml"
)
The compiled file can be uploaded to the Kubeflow UI and started through the interface, or started programmatically through the Python client:
from kfp.client import Client
client = Client(host="https://kubeflow.company.com")
run = client.create_run_from_pipeline_package(
pipeline_file="indexing_pipeline.yaml",
arguments={
"confluence_space": "DOCS",
"chunk_size": 800,
"pinecone_namespace": "2024-01-15"
},
run_name="weekly-indexing-2024-01-15"
)
print(f"Run ID: {run.run_id}")
Passing Data Between Components
Figure 29. Two ways of passing data between components.
Components exchange data through outputs and inputs (Fig. 29). Simple types (int, str, float, bool, list, dict) are serialized automatically. For large data, artifacts are used (files that are stored in a repository, usually S3 or GCS):
from kfp.dsl import Output, Input, Dataset
@dsl.component
def save_chunks(
chunks: list,
output_dataset: Output[Dataset]
):
import json
with open(output_dataset.path, 'w') as f:
json.dump(chunks, f)
@dsl.component
def load_chunks(
input_dataset: Input[Dataset]
) -> list:
import json
with open(input_dataset.path, 'r') as f:
return json.load(f)
Artifacts are saved in the repository and remain available after the pipeline finishes for analysis and debugging.
Versioning
Figure 30. Versioning the pipeline configuration.
To ensure reproducibility, it is important to version all inputs of the pipeline (Fig. 30).
import hashlib
import json
from datetime import datetime
def compute_config_hash(config: dict) -> str:
config_str = json.dumps(config, sort_keys=True)
return hashlib.sha256(config_str.encode()).hexdigest()[:12]
def create_versioned_namespace(config: dict) -> str:
timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
config_hash = compute_config_hash(config)
return f"v_{timestamp}_{config_hash}"
run_config = {
"chunk_size": 1000,
"chunk_overlap": 200,
"embedding_model": "text-embedding-3-small"
}
namespace = create_versioned_namespace(run_config)
Versioned namespaces in the vector database make it possible to roll back to a previous version of the index if the new one shows a drop in quality.
Error Handling and Automatic Retries
Figure 31. Error-handling strategies in Kubeflow.
Kubeflow supports built-in retries for failed components. When a network error or a temporary failure causes an error, the component will be retried automatically (Fig. 31):
@dsl.component
def unreliable_api_call(data: list) -> list:
pass
@dsl.pipeline
def pipeline_with_retry():
task = unreliable_api_call(data=[])
task.set_retry(
num_retries=3,
backoff_duration="60s",
backoff_factor=2.0
)
For more complex error-handling logic, retries can be implemented directly inside the component:
@dsl.component
def robust_embedding_creation(
chunks: list,
model: str
) -> list:
from openai import OpenAI, RateLimitError
import time
import os
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
results = []
for chunk in chunks:
for attempt in range(3):
try:
response = client.embeddings.create(
input=chunk["text"],
model=model
)
chunk["embedding"] = response.data[0].embedding
results.append(chunk)
break
except RateLimitError:
time.sleep(2 ** attempt)
else:
chunk["embedding"] = None
chunk["error"] = "Rate limit exceeded after retries"
results.append(chunk)
return results
Here exponential backoff is used: after the first failure we wait 1 second, after the second 2 seconds, and after the third 4 seconds. This reduces the load on the API during temporary failures.
Questions for Reflection and Practice
Theoretical questions
-
What are the differences between an experiment in a notebook and a production pipeline in terms of organization and reproducibility?
-
What role does orchestration play in automating an LLM workflow, and why does manual management not scale?
-
Which specific aspects of LLMOps distinguish it from traditional MLOps?
-
Which tools exist for orchestrating ML pipelines, and which criteria should be used when choosing one?
-
Describe the concepts of Pipeline, Component, and Artifact in Kubeflow.
-
What role does a component's interface play in determining its reusability?
-
How does the @dsl.component decorator work, and which parameters does it accept?
-
How do you define a pipeline with parameters and dependencies between steps?
-
How does compiling a Python pipeline definition into YAML work?
-
Which types of artifacts does Kubeflow support, and when should they be used?
-
How do you ensure pipeline reproducibility when non-deterministic operations are involved?
-
What advantages does versioning the configuration and data of a pipeline provide?
-
How do you organize error handling and retry logic in Kubeflow?
-
Which criteria of engineering quality are important for production pipelines?
-
How do you combine the flexibility of experiments with the reliability of production systems?
Practical exercises
-
Create a simple component that takes a list of numbers and returns their sum.
-
Define a pipeline with two connected components: the first generates data, the second processes it.
-
Compile the pipeline into a YAML file and study its structure.
-
Implement working with PipelineTask and passing data between three components in a chain.
-
Create a component with error handling and automatic retries for external API calls.
-
Write a component that loads data from Confluence (or another API) with validation of the results.
-
Implement a component for creating embeddings with batching and rate-limit handling.
-
Create a configuration versioning function that generates a unique identifier.
-
Write a script that launches the pipeline through the Kubeflow client with parameterization.
-
Design a complete document indexing pipeline: loading, chunking, embeddings, indexing.